|
A Java class declares member variables to store the object's state. It can also declare variables (better known as local variables) that are used as a temporary storage while implementing the object’s behavior. Any kind of variable declaration should at least have a variable name and an associated data type. The general format for a single variable declaration is as follows:
datatype variableName [ = assignedValue] ;
Note that the elements between the pair of square brackets [] are optional.
As you can see, you can optionally assign some initial value to a variable at the time of its declaration itself. Let us declare an integer variable as,
int number = 5;
With the above declaration, you have declared that an integer variable named number which will have a value of 5 initially. The type int is one of the Java primitive types. Besides primitives, there is another kind of data types called as the object-reference types. A variable of object-reference type holds a reference (or address) to an object as a value. We will take a quick look at these two kinds of Java data types in the following section.
|
|
When you assign a value to a variable, the assigned value must be compatible with variable’s type. For instance, a variable of a primitive type can only hold a value of that primitive type. Or a variable of object-reference type can hold a reference to an object as long as the object’s type is assignment-compatible with the variable’s type. A variable of object-reference type can also hold a null reference as a initial value. In chapter 10, we will learn more about compatible datatypes. |