0

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?

Ferdz
  • 1,182
  • 1
  • 13
  • 31
qwazer
  • 7,174
  • 7
  • 44
  • 69

1 Answers1

1

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.

Sirko
  • 72,589
  • 19
  • 149
  • 183
  • This however, is not true for Integers from -128 to 127 (including). Here, the `==` comparison will work. – Christoph Mar 03 '14 at 15:52