Definition:
A
variable is a container in your program that is
used to hold data of a particular type.
You must explicitly provide a name and a type for each
variable you want to use in your program.
The variable's name is its
identifier.
You use the variable name to refer to the data it contains.
The variable's type determines what values it can hold
and what operations can be performed on it.
To give a variable a type and a name,
you write a variable
declaration, which generally looks like this:
type name
In addition to the name and type that you explicitly give a variable,
a variable also has
scope.
Scope is the life-span of the variable,
it determines what sections of code can use the variable.
The location of the variable declaration,
that is,
where the declaration appears in relation to other code elements,
determines its scope.
The
MaxVariables
program, shown below,
declares eight variables of different types
within its main
method.
The variable declarations are red:
public class MaxVariables {
public static void main(String args[]) {
// integers
byte largestByte = Byte.MAX_VALUE;
short largestShort = Short.MAX_VALUE;
int largestInteger = Integer.MAX_VALUE;
long largestLong = Long.MAX_VALUE;
// real numbers
float largestFloat = Float.MAX_VALUE;
double largestDouble = Double.MAX_VALUE;
// other primitive types
char aChar = 'S';
boolean aBoolean = true;
// display them all
System.out.println("The largest byte value is " + largestByte);
System.out.println("The largest short value is " + largestShort);
System.out.println("The largest integer value is " + largestInteger);
System.out.println("The largest long value is " + largestLong);
System.out.println("The largest float value is " + largestFloat);
System.out.println("The largest double value is " + largestDouble);
if (Character.isUpperCase(aChar)) {
System.out.println("The character " + aChar + " is upper case.");
} else {
System.out.println("The character " + aChar + " is lower case.");
}
System.out.println("The value of aBoolean is " + aBoolean);
}
}
The following sections elaborate on
the various aspects of variables.
You will learn about the if
-else
statement
in the
Control Flow Statements section later in this lesson.