I have a question about comparing String and Integer objects...
a. Comparing String references:
String string1 = "Hi";
System.out.printf("%s \n", string1);
String originalString = string1;
System.out.printf("%-9s %-9s %b \n", string1, originalString, originalString == string1);
System.out.println();
string1 += " there";
originalString += " there";
System.out.printf("%-9s %-9s %b \n", string1, originalString, originalString.equals(string1));
System.out.printf("%-9s %-9s %b \n", string1, originalString, originalString == string1);
Produced output:
Hi
Hi Hi true
Hi there Hi there true
Hi there Hi there false
Here, the last line compares the addresses and as to be expected gives false. OK so far ;)
b. Comparing Integer references:
Integer integer1 = 10;
System.out.printf("%d \n", integer1);
Integer originalInteger = integer1;
System.out.printf("%d %d %b \n", integer1, originalInteger, originalInteger == integer1);
System.out.println();
integer1++;
originalInteger++;
System.out.printf("%d %d %b \n", integer1, originalInteger, originalInteger == integer1);
Produced output:
10
10 10 true
11 11 true
By the time the last line is printed out, both 'integer1' and 'originalInteger' are referencing completely different objects... nevertheless
originalInteger == integer1 --> true ???
Does this imply that not the addresses of the objects but the the contents of the objects are compared? In other words, is it because, with type wrappers, the values are always 'unboxed' before being compared?
So, to resume:
originalString == string1 --> false
originalInteger == integer1 --> true
I don't understand why originalInteger == integer1 --> true
Thank you