Java Reference
In-Depth Information
The following
ReferenceDemo
program demonstrates comparing references. Examine the
code and try to determine its output.
1. import java.io.File;
2. import java.util.Date;
3.
4. public class ReferenceDemo {
5. public static void main(String [] args) {
6. File f1 = new File(“mydata.txt”);
7. File f2 = new File(“mydata.txt”);
8. if(f1 != f2) {
9. System.out.println(“f1 != f210.
11. }
12. Date today = new Date();
13. Date now = today;
14. if(today == now) {
15. System.out.println(“today == now”);
16. }
17.
18. String s1 = “Hello”;
19. String s2 = “Hello”;
20. if(s1 == s2) {
21. System.out.println(“s1 == s2”);
22. }
23.
24. String x1 = new String(“Goodbye”);
25. String x2 = new String(“Goodbye”);
26. if(x1 == x2) {
27. System.out.println(“x1 == x2”);
28. }
29. }
30. }
Let's study this program. The references
f1
and
f2
point to two different
File
objects,
so the two references cannot be equal. It is irrelevant that the two
File
objects look the
same in memory; they are clearly two different objects so their references are not equal. On
the other hand, there is only one
Date
object in memory and
today
and
now
both point to
it, so
today == now
is
true
.
Comparing
String
references in Java tends to be confusing because of how the JVM
treats string literals. Because
String
objects are immutable, the JVM can reuse string
literals for effi ciency and to save memory. Because
“Hello”
is a
String
literal known at
compile time, the JVM only creates one
“Hello”
object in memory, and
s1
and
s2
both
Search WWH ::
Custom Search