Java Variables

Java variables come in two types:


Object Reference

Primitives hold fundamental values (simple bit patterns including integers, Boolean, and floating point numbers.


Object references hold, well, references to objects.

1. Variables must have a type

2. Variables must have a name

A variable is similar to a cup or a container. Each cup holds a value.

The sizes for six numeric primitives in Java are byte (8), short (16), int (32), and long (64).

You can assign a value to a variable in several ways:

1. Type a literal value after the equals sign

2. assign the value of one variable to another (x=y)

3. use an expression combining the two (x = y + 32)

Here are some examples of literal values that have been marked in bold:

int size = 28;     -declare an int named ‘size’, assign it the value 28

char initial = ‘j’;     -declare a char named ‘initial’, assign it the value ‘j’

double d = 465.783;     -declare a double named ‘d’, assign it the value of 465.783

Boolean isCrazy;     -declare a Boolean named ‘isCrazy’ (no assignment)

isCrazy = true;     -assign the value ‘true’ to the previously-declared isCrazy

int y = x + 234     -declare an int named ‘y’, assign it the value that is the sum of whatever x is now plus 234