In Java, == checks for reference equality while .equals() checks for content equality, which is true in every case. But, java refers to the memory in some inconsistent way which brings up all the confusion.
Check the following code -
class you{ public static void main(String[] args){ Integer a = 1; Integer b = 1; // a & b are pooled from the same memory location Integer i = 128; Integer j = 128; /* i and j are not pooled. Hence stored in different memory location */ System.out.println("a == b: "+(a == b)); //true System.out.println("a.equals(b): "+(a.equals(b))); //true System.out.println("i == j: "+(i == j)); //false System.out.println("i.equals(j): "+(i.equals(j))); //true String x="abc"; /* Since strings are immutable, x and y are stored in the same location in the heap memory for same value*/ String y="abc"; /*Creating a new reference. z has a different memory location but same value*/ String z=new String("abc"); System.out.println("x == y: "+(x == y)); //true System.out.println("x.equals(y): "+(x.equals(y))); //true System.out.println("x == z: "+(x == z)); //false System.out.println("x.equals(z): "+(x.equals(z))); //true } }
For Integer objects, when the value is below 8-bits(-128 to 127), java stores it ,for the same values, in the same location in the memory and pools it from there. Hence all objects point to the same memory location for these values. But when the value is out of this range, dedicated memory locations are created and hence at those times == returns false.
For Strings, since they are immutable, java stores them in the same memory location (irrelevant of size) when declared directly. However, if u create a string type object and then assign the same value, the memory location is diff.
So its always safer to use .equals() when u want to do content checking for strings.
No comments:
Post a Comment