1

I that know in Java the == operator compares references, not the values pointed to, but if so why this gives equal comparison?:

class MainClass{      
   public static void main(String[] args) {      
      Integer x = 2;
      Integer y = 2;
      if(x==y) System.out.println("Equal");
   }
}
gian_
  • 95
  • 6
  • 5
    Integers in a certain range are cached for performance. – Glains Oct 20 '20 at 19:10
  • @Glains There is any way to avoid that? I'm trying to tranverse a Queue by doing poll() and adding back with add(), and need to check when I arrive to the original top of the Queue again. – gian_ Oct 20 '20 at 19:14
  • 4
    @gian_ Use `new Integer(2)`. – xehpuk Oct 20 '20 at 19:16
  • You can disable the cache, but you have to configure the JVM, which i do not recommend for this type of problem. – Glains Oct 20 '20 at 19:16

0 Answers0