Java Reference
In-Depth Information
< Day Day Up >
Puzzle 13: Animal Farm
Readers of George Orwell's Animal Farm may remember old Major's pronouncement that "all
animals are equal." The following Java program attempts to test this pronouncement. What does it
print?
public class AnimalFarm {
public static void main(String[] args) {
final String pig = "length: 10";
final String dog = "length: " + pig.length();
System.out.println("Animals are equal: "
+ pig == dog);
}
}
Solution 13: Animal Farm
A superficial analysis of the program might suggest that it should print Animals are equal: true .
After all, pig and dog are both final String variables initialized to the character sequence "length:
10" . In other words, the strings referred to by pig and dog are and will forever remain equal to each
other. The == operator, however, does not test whether two objects are equal; it tests whether two
object references are identical . In other words, it tests whether they refer to precisely the same
object. In this case, they do not.
You may be aware that compile-time constants of type String are interned [JLS 15.28]. In other
words, any two constant expressions of type String that designate the same character sequence are
represented by identical object references. If initialized with constant expressions, both pig and dog
would indeed refer to the same object, but dog is not initialized with a constant expression. The
language constrains which operations are permitted to appear in a constant expression [JLS 16.28],
and method invocation is not among them. Therefore the program should print Animals are
equal: false , right?
Well, no, actually. If you ran the program, you found that it prints false and nothing else. It doesn't
print Animals are equal: . How could it not print this string literal, which is right there in black
and white? The solution to Puzzle 11 contains a hint: The + operator, whether used for addition or
 
 
Search WWH ::




Custom Search