Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are autoboxed Integers and .getClass() values ==-equal, not only .equals()-equal?

Tags:

java

equals

Maybe I've been working too long on Java without really understanding some of its basics.
I do understand that == is for object reference equality and .equals() is for object value equality.

  1. Comparing Integers:

    Integer x = 1, y = 1;  
    System.out.println(x == y); // true
    

    Why? Since object reference equality is used, it should be false since they are both different objects.

  2. Comparing getClass() return values:

    String s1 = "a", s2 = "b";  
    System.out.println(s1.getClass() == s2.getClass()); // true 
    

    Why? Again as per above, object reference is used. Both using getClass will return separate Class objects.

Did I miss something or is my mind is too tired of coding in Java?

like image 883
yapkm01 Avatar asked Dec 16 '22 09:12

yapkm01


1 Answers

Integer objects

Integer x = 1, y = 1;
System.out.println(x==y); // true, why?

This happens because for values in the byte range (-128 to +127), java uses cached Integer objects, stored in Integer's inner class, IntegerCache. Every time an Integer object is created with value between -128 and +127, the same object will be returned (instead of creating the new object).

Conversely, for values outside the byte range, the comparison is false:

Integer x = 999, y = 999;
System.out.println(x==y); // false

Class objects

String s1 = "a", s2 = "b";
System.out.println(s1.getClass() == s2.getClass()); // true. Why?

This is true because the class of both objects is String, and there is only one copy of each class object per JVM (it's like a singleton). The class object returned from getClass() of each String is the same class object (String.class).

like image 142
Bohemian Avatar answered Jan 14 '23 15:01

Bohemian