Java Reference
In-Depth Information
Why does it work like this? The answer is, “How could it work any other way?” How could the JVM print out an
object? Should the source code be printed? Or, all the variable values? Or, only the class variable values? Is there really
a correct way to print an object?
In addition, don't forget that the println statements specify that the reference variable emp should be displayed,
not the Employee object. Because the reference variable contains the location of the object (not the object), the JVM
is actually being helpful. The JVM displays not only the location but also what the location contains (a c5.Employee
object). You can interpret the text “c5.Employee@125e69d4” as “There is a c5.Employee object at main memory
location 125e69 d4.”
Tutorial: Working with Primitive Variables
Let's have a go at working with primitive variables:
1.
In EmployeeApp, at the end of the main method, add the following statement:
int intTest = 2109876543;
A primitive variable is created just like any other variable: first the type ( int ) is specified, and then the name of
the variable (intTest). Notice that an equal sign is used to assign a value, just like a reference variable. However, on the
right side of the assignment things are quite different: no object is instantiated , a value is simply assigned.
2.
Change the 0 (in the intTest value) to 4.
The error message will be, “The literal 2149876543 of type int is out of range.” This number is too large to store as
an int . Remember, whole number values greater than 2.1 billion (give or take a few million) must be stored in a larger
primitive type such as a long variable.
3.
Change intTest's value back to 2109876543.
4.
At the end of the main method add the following statement and run EmployeeApp:
System.out.println("The value of intTest is " + intTest);
The result of the new println statement will be:
The value of intTest is 2109876543
No storage location is displayed because the value stored in the variable intTest is 2109876543 not a storage
location, as with the reference variable emp.
5.
At the end of the main method, add the following statement:
double doubleTest = 3210.12345678901234567890;
Notice that the value of doubleTest is more precise than a double variable can hold, yet there is no error message.
This is because the JVM rounds the number so that it will fit in the variable. We'll prove this by printing out the value.
6.
At the end of the main method add the following statement and run EmployeeApp:
System.out.println("The value of doubleTest is " + doubleTest);
The result of the new println statement will be:
The value of doubleTest is 3210.1234567890124
 
Search WWH ::




Custom Search