Variables in Java

A Java variable is a container for holding a specific type of data. The type designation of a variable determines what kind of data it can hold. For example, some variables hold integers, some hold logical Boolean values, and some hold strings of characters such as names.

Variables, as there name indicates, can change the data that they hold. However, they can not change the type of data that they hold. That is, a variable that holds integers can be set to store a number like 82 or 4, but it can not hold a name like "" That requires a String type variable.

There are some limitations on what can be used for variable names. The characters that can be used in variable names are restricted the sets of upper and lower case letters, digits, _, and $. Also, variable names can not begin with a digit. So, xoax4 is a valid variable name but 4xoax is not. Lastly, variable names can not be any of Java's reserved words.


Example 1

// Declaring and initializing a boolean variable to true.
boolean bResult = true;

Example 2

// Declaring and then initializing an int variable.
int iMyInt;
iMyInt = 92;

Example 3

// Declaring and initializing a long, using underscores for readability.
long lSpeedOfLight = 299_792_458;

Example 4

// Declaring multiple variables on one line.
double dX, dY, dZ;
dX = 863.35;
dY = 27.9;
dZ = 691.3;

Example 5

// Declaring three variables and setting them all equal.
double dX, dY, dZ;
dX = dY = dZ = 8.03;

Example 6

// Initializing a variable with a unicode smiley face.
char cSmileyFace = '\u263a';

Example 7

// Initializing a String object with the default constructor.
// Then assigning it a new string value.
String sName = new String();
sName = "";

Example 8

// Declaring and initializing two Strings with the same value,
// using two different notations. The statements are equivalent.
String sName = "";
String sName2 = new String("");