Question

I have a simple java class

public class T {
         public static void main(String[] args) {
                 Integer x = 0;
                 Integer y = 0;
                 Integer a = 255;
                 Integer b = 255;
                 System.out.println( (x==y) );
                 System.out.println( (a==b) );
 }

The console output result is:

true
false

Why is the output for comparing x with y are different from comparing a with b? Why does Java doesn't create objects for small int values?

No correct solution

OTHER TIPS

If you want to compare objects in Java use .equals().

public class T {
         public static void main(String[] args) {
                 Integer x = 0;
                 Integer y = 0;
                 Integer a = 255;
                 Integer b = 255;
                 System.out.println( (x.equals(y)) );
                 System.out.println( (a.equals(b)) );
 }

Using == you will just compare the references to both objects, which wont be the same.

Use == only when comparing primitive values.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top