A variable is a place in memory that holds a piece of data. It is also known as a field, and it has a name, type, value, and address (a location in RAM). There are two different types of variables: one is a primitive type and the other is of a reference type.
Primitive Variables
Primitive variables hold only those of type boolean, byte, short, char, int, long, float, and double variables. A boolean only contains one of two values: true or false. The byte, short, int (as in integer), and long variables are all whole numbers, but they each hold different ranges of values. A char is a single character enclosed in single quotes, such as 'a' or 'i'. Characters can also be assigned using Unicode or ASCII values. The float and double variables are capable of handling decimals and extremely large numbers. The following table shows the range of values and size for each of these variables (8bits=1byte). Pick a data type with the smallest size possible.
| Type |
Bytes |
Range |
| byte |
1 |
-128 to 127 |
| short |
2 |
-32768 to 32767 |
| int |
4 |
-2147483648 to 2147483648 |
| long |
8 |
+/-9223372036854775807 |
| float |
4 |
6-7 significant digits |
| double |
8 |
14-16 significant digits |
| boolean |
1bit |
true or false |
| char |
2 |
'\u0000' to '\uffff' (\u means Unicode)
or 0..65535 |
(Note: String variables are reference variables, and will be taught in another tutorial.)
Reference Variables
Reference variables can hold a reference to an object, such as an array, or have a null reference. These will be discussed in a later tutorial.
Declaring and Initializing Variables
To declare a variable means to give a variable a name and a type.
int myVariable; // int is the type, myVariable is the name
The name of a variable should be meaningful and related to the context of the program. A variable name such as a, b, or c which represents price, tax, and total in a program is NOT good programming practice. The second word of a variable is usually capitalized (e.g. myVariable). Variable names must also have no spaces and they must not start with a number.
To initialize a variable means to give the variable a value. You cannot use variables until they are initialized.
int, byte, short, and long types can only hold integer values, or whole numbers.
int num1;
// the variable num1 is declared
int num2;
// the variable num2 is declared
num1 = -5;
// num1 is initialized, called an assignment statement
num2 = num1 + 1;
// num2 is initialized, and will equal -4 (-5 + 1)
double and float types can hold decimal values
double number = 1234567890.1234;
A variable of type char is not limited to just upper and lower-case letters and numbers. Anything with a Unicode value can be used.
char letter = 'a'; // letter is declared and initialized in one line
// note the single quotes around the single character
char letter = '\u0051'; // letter equals 'a'
boolean types hold true or false values. They're useful for flagging if something has happened.
boolean flag = true;
Constants
A constant is any type of variable that is fixed throughout the program (e.g. PI=3.14 will never change). It is created with the final type modifier (aka. it changes an attribute of the variable) and static type modifier, and is usually written in capital letters. The final type modifier means that the variable cannot be changed at all throughout the program. The static type modifier means that it is a class constant and belongs to the class instead of an object of the class (this will be discussed in the Object-Oriented Programming Tutorial).
Examples
//declaring (creating) constants isn't much different than declaring any other variable
class Circle
{
final static float PI = 3.1415;
//code goes here
}
Now, if you try to change the value of PI, your program will throw an error. So don't try something like this:
final static float PI = 3.1415;
PI = 4;
Scope of local and global variables
An interesting thing about variables is that certain variables only exist in certain parts of your code. The scope of a variable is the period or duration in which it exists. Outside of that scope, the variable cannot be called or used. Global variables can be accessed throughout the entire program, and therefore the scope of a global variable is the entire program. Local variables are variables created within a class or method and their scope only exists within that class or method.
Example
File 1: Global.java
public class Global {
public static int sum = 80;
}
File 2: Variables.java
public class Variables
{
public static void main(String [] args)
{
int total = 0;
for (int i = 0; i < 5 ; i++)
total += i; // the scope of "i" is only this for loop
System.out.println(total);
System.out.println(Global.sum);
Global.sum += total;
System.out.println(Global.sum);
//The scope of 'total' ends here
}
/* Global.sum has been initialized externally, and can be referenced anywhere in this program. It is therefore a global variable */
}
System Output of Variables.java
10
80
90
Note: In the program, the scope of "i" only exists within the for loop because it was created in the for loop. Interestingly enough, after the for loop, you are able to create a new variable using the name "i" again.
Type Conversion and Casting
Type conversion (or implicit casting) is when you change one type of variable into another type of variable (like from an int variable to a double variable). Say, for instance, you have 2 (an integer number) apple pies. But say you want to split those pies amoungst 4 people. You no longer have an integer number, but pies cannot hold a decimal. This is when you have to do type conversion.
A variable itself cannot change types. It must pass its value on to another variable of a different type. This, however, can cause problems.
int pies = 0.5; // this will throw an ERROR
Let's try again:
int pies = 4;
float piePortion = 0.5;
pies = piePortion; // this will also throw an ERROR
One more time:
int pies = 4;
float piePortion = 0.5;
piePortion = pies; // this works just fine
So why does this work? Because of hierarchy. In an assignment statement, the value being assigned must be more general than the variable it is assigned to (according to the hierarchy of types below). Otherwise, an error will occur and casting must be used.
(general) double > float > long > int > short > byte (specific)
In this use, general means that the variable is able to hold more information, and is therefore larger in size. Double, taking up the most memory, has the capability to hold any of the other types of values. However, as the variable size decreases, so do the capabilities. For example, long and int values can no longer hold the decimal places that doubles can. If we tried to assign a decimal value to an integer, an error would occur. Therefore, any value being assigned must be equal to or more specific than the variable to which it is assigned.
Example
double first = 1.2345;
int second = 56;
first = second;
This is correct because the value of the variable on the right (second) of the equal sign is an int type variable, which is more specific than first, which is a double type variable. The value of first now becomes 56.
double first = 1.2345;
int second = 56;
second = first;
This is INCORRECT because the value of the variable on the right (first) of the equal sign is a double type variable, which is more general than second, which is an int type variable. An error would occur, and the only way to get around this problem is to use casting.
Type casting (or explicit casting) is when you tell the program to convert a value to another variable type (as opposed to the automatic conversion discussed above).
Example
variable = (type) expression;
double x;
int number = 1;
x = number / 2;
The value of x becomes 0 because both 1 and 2 are int-type variables. When an int is divided by another int, the result will give an int. Since 1/2=0.5, the computer automatically truncates (cuts off) the decimals, giving you 0 as the answer.
x = number / 2.0;
x now becomes 0.5 because the result of an operation always takes the largest, or more general, type.
Now if you cast the variable number into a double type variable, as in:
x= (double) number/2;
the result would also be a double value of 0.5. The variable number has been cast (or converted) from an int to a double.
Note: Be careful of the following mistake:
x= (double) (number/2);
//this also gives an answer of 0 becuase the value has been cast AFTER the division is done.
Related Links
For more information on variables and casting, check out some useful links:
|