Recall that variables are memory cells.
Each variable is given a type when it is declared. A variable may not be assigned a value that is not of the type specified. Types are checked at compile time and errors (as shown below) are reported.
The line 1 of the main method above declares a variable of type String named msg. This gives you a memory cell that can hold something of type String and you may refer to this memory cell using the label msg. To declare a variable in Java, you must specify its type followed by its name.
The rules for naming variables are as follows:
You can also declare a variable and assign it a value in a single line of code as follows:
A primitive type variable that is not initialized is typically given a value of 0, but it is bad programming style to rely upon that. Your program should always initialize variables appropriately. The example below declares a variable of type int named number and initializes it to the value 4.
Reference types are pointers to objects. In the example above, line 1 declares a variable of type Hello and names it h. h is the label of 32-bits of memory that initially contains the value null. null is the special value used to indicate that a reference contains no value.
Line 2 of the example initializes the variable h by creating a new instance of the Hello class and setting the value stored in h to be the memory address of the new object. To create a new object you must use the new keyword. This calls the constructor of the class. A new object is created on the heap, and the location of the new object is stored in the variable h.
The String type is treated in a special way in Java. It is not a primitive type, but you can create a String object without using the new keyword. In addition, String objects are immutable, which means they cannot be changed.
In line 1 of the example, an object with contents "Michael Mouse" is created and the address of that object is stored in the reference labeled name. In line 2, a new object with contents "Mickey Mouse" is created and the address of that object is stored in name. Note that the address of the object containing "Michael Mouse" is overwritten. If there are no other references to the "Michael Mouse" object, it will eventually be reclaimed by the garbage collector. The garbage collector periodically looks at all of the memory that your program has requested to use and reclaims all of the memory that your program is no longer using.