A variable is a container that holds some value.  In Java, before a variable can be used it must be defined with a variable declaration statement and an optional initialization assignment.  The variable declaration includes the type of data that can be stored in the variable and an identifier.

type identifier [= value];

Tab, newline, and space characters are considered whitespace characters.  When writing programs we place whitespace characters (at least one) between the tokens in a statement.  In most cases, multiple whitespace characters are allowed and ignored.

Java is a strongly typed programming language.  That means each variable declaration specifies a specific type which defines the values that can be stored in the variable.  A type can be either primitive or reference.


  • Can be made of upper and lowercase letters, numbers, underscore and dollar sign.
  • Can not begin with number
  • Can not be a Java keyword

Identifier Conventions

  • Variables and methods begin with lowercase letters
  • Classes begin with capital letters

A literal defines an explicit value.  We often initialize variables using literals.

int age = 1;
double grade = 98.6;
char initial = 'A';
String phrase = "Hello World!";
boolean foundToken = false;

Variables can also be initialized using other expressions, but we’ll get to them later.

int w = x;
int y = foo();
int z = w * x;

An assignment statement is terminated with a semi-colon.

Primitive Types

The Java primitive types are

  • byte, short, int, long
  • float, double
  • char
  • boolean

Integers (byte, short, int, and long)

  • long (64)  [-2^63, 2^63-1]
  • int (32) [-2^31, 2^31-1]
  • short (16) [-32,768, 32,767]
  • byte (8)  [-128, 127]
int age = 10;
long age = 100000000;
  • byte and shorts are promoted (actually stored as) ints

Floating-point (float, double)

  • double (64)
  • float (32)
double average = 3.04;
double count = 10.3E10;
  • double is often faster than float on modern computers
  • Many math functions return doubles

Characters (char)

  • char (16)
  • Represent Unicode symbols
char ch1, ch2;
ch1 = 88;                // ASCII decimal value for 'X'
ch2 = 'Y';

char ch3 = '\'';         // single quote character
char ch4 = '\n';         // new line character

Boolean (boolean)

  • boolean (size undefined)
  • Represents true/false
boolean flag = true;

Reference Types

A variable that has a reference type can store a reference (memory location) to where an instance of the reference type is stored.  For example we can store a sequence of characters in memory and have a reference variable hold the location to where the strings are stored.

String name = "Eric";
String directory = "\\root";
String title = "\"To Kill a Mockingbird\"";

© 2017 – 2020, Eric. All rights reserved.