Dworza Dworza - 1 month ago 9
Java Question

Comparing primitive types and their values

I'm preparing for OCA and even after some years of experience with java, I got surprised, when I tried to run this code:

public class Main {
static Integer integer = 3;
static String string = "Some String";

public static void main(String[] args) {
Integer i = new Integer(3);
String s = new String("Some String");
System.out.println(string == s); //false
System.out.println(string == s.toString()); //false
System.out.println(string.equals(s)); //true
System.out.println(string.equals(s.toString())); //true
System.out.println(integer == i); //false
System.out.println(integer == i.intValue()); //true
}
}


I was not surprised with the result of first 4 comparisons. Nor with the fifth one, since I'm trying to compare two different objects. Nevertheless I don't understand, why the last output is true. I'm trying to compare an Integer object with a int value. Is there happening something under the hood? If yes, why the same mechanism won't work for Strings (second comparison)?

Answer

Since you understand the reasons for the first 5 results, let's concentrate solely on the 6th.

When the expression integer == i.intValue() evaluates, integer auto-unboxes to a primitive type (JLS-15.21.1).

(Note that this expression will throw a NullPointerException if integer is null.)

For me this is touchstone of the many problems that were introduced when this design decision was taken by Java.

Comments