Java Reference
In-Depth Information
3.
Enter the following statements after the string definitions:
System.out.println(emp1);
System.out.println(emp2);
if (emp1==emp2)
System.out.println("emp1 is equal to emp2");
else
System.out.println("emp1 is NOT equal to emp2");
4.
Save the source, and run StringCompApp as a Java application.
The results will be:
Joe
Joe
emp1 is NOT equal to emp2
Are you surprised by the results? Can you explain these results?
emp1 and emp2 are reference variables that contain the location of two different Employee objects. These
Employee objects have the same values for their name and street address properties but they are two different objects.
Now, the println statements may have confused you. They both display the employee names (not the memory
location) because we changed the toString method to return the Employee object name. If we comment out the
toString method, you will see a little better why the two objects are not equal.
5.
In c6.Employee, comment out the toString method.
6.
Run StringCompApp as a Java application.
The results will look like the following (the memory addresses will probably be different from the following):
c6.Employee@646d646d
c6.Employee@64796479
emp1 is NOT equal to emp2
Notice that the addresses in the variables are different, therefore the comparison results in a value of false .
7.
In StringCompApp, enter the following statements after the if/else statements:
if (emp1.getEmpName() == emp2.getEmpName())
System.out.println("emp1 name is equal to emp2 name");
else
System.out.println("emp1 name is NOT equal to emp2 name");
8.
Save the source, and run StringCompApp as a Java application.
The results should be the following:
c6.Employee@7a807a80
c6.Employee@7ac87ac8
emp1 is NOT equal to emp2
emp1 name is equal to emp2 name
Notice that the comparison between the name values was equal. This is the same as comparing two
character strings.
Search WWH ::




Custom Search