Java Reference
In-Depth Information
Most business applications only need boolean variables and the numeric types of int and double . In addition, most
organizations try to limit the number of variable types used because working with and converting between the different
types can be tricky. For instance, converting a double with a value of 3.75 to an int would result in a value of 3 for the int
variable. Now you may say, “Big deal, .75 of something can't be that important.” But, what if it were your GPA?
We will explain how to work with primitives later in the chapter. Right now, let's investigate the difference
between primitives and reference variables.
Tutorial: Displaying Reference Variable Values
We will use EmployeeApp to show some of the differences between primitive and reference variables. In addition, pay
attention to how EmployeeApp's main method is used as a testing tool. Main methods will often be added to classes
for testing purposes. In future examples, we will quickly check the progress of our application development by using
this technique.
1.
Create a new package called c5 in the Tutorials project.
2.
Copy the six Employee classes from c4 to c5.
In the c5.EmployeeApp source code:
3.
Comment out the two statements in the main method.
We are going to substitute two statements for the first statement so that we clearly separate the creation of the
Employee variable from the creation of the Employee object.
4.
After the main method header, insert the following:
Employee emp = null ;
emp = new Employee("Mary Worker", "1 Main St.",
"Enid", "OK", "77777");
The first statement sets the reference variable emp to null . This means that emp does not reference any object.
We will now insert a statement to display the value of emp after each statement.
5.
Enter the following after the first statement in the main method:
System.out.println("emp value before the object is assigned: " +
emp);
6.
Enter the following statement after the last (i.e., now the third) statement in the main
method and run c5.EmployeeApp:
System.out.println("emp value after the object is assigned: " +
emp);
Running EmployeeApp would result in the following messages in the console:
emp value before the object is assigned: null
emp value after the object is assigned: c5.Employee@7a627a62
The location value you get will probably be different from 7a627a62 . Notice that the second message also displays
the object type—which is the package name and class name separated by a period. (The package name is part of the
class/object identifier.)
 
Search WWH ::




Custom Search