Comparing Integer values in Java, strange behavior

java compare integer to int
java compare primitive int
java integer int
compare two primitive long values in java
how to compare integer list values in java
how to compare long values in java
how to compare values in java
javascript object equality

Walk with me ..

Integer x = 23;
Integer y = 23;

if (x == y)
    System.out.println("what else");      // All is well as expected


Integer x = someObject.getIndex();
Integer y = someOtherObject.getSomeOtherIndex();

if (x == y)
    System.out.println("what else");  
    System.out.println("...");        // Prints this 

Hmm ... I try casting to int

int x = someObject.getIndex();
int y = someOtherObject.getSomeOtherIndex()

if (x == y)       
    System.out.println("what else");   // works fine

Are they both Integers?

System.out.println(x.getClass().getName());              // java.lang.Integer
System.out.println(y.getClass().getName());              // java.lang.Integer
System.out.println(someObject.getIndex());               // java.lang.Integer
System.out.println(someOtherObject.getSomeOtherIndex()); // java.lang.Integer

What do you guys think? What would explain something like this?

You're comparing Integer values, which are references. You're coming up with those references via autoboxing. For some values (guaranteed for -128 to 127) the JRE maintains a cache of Integer objects. For higher values, it doesn't. From section 5.1.7 of the JLS:

If the value p being boxed is true, false, a byte, or a char in the range \u0000 to \u007f, or an int or short number between -128 and 127 (inclusive), then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2.

Ideally, boxing a given primitive value p, would always yield an identical reference. In practice, this may not be feasible using existing implementation techniques. The rules above are a pragmatic compromise. The final clause above requires that certain common values always be boxed into indistinguishable objects. The implementation may cache these, lazily or eagerly. For other values, this formulation disallows any assumptions about the identity of the boxed values on the programmer's part. This would allow (but not require) sharing of some or all of these references.

This ensures that in most common cases, the behavior will be the desired one, without imposing an undue performance penalty, especially on small devices. Less memory-limited implementations might, for example, cache all char and short values, as well as int and long values in the range of -32K to +32K.

Moral: don't compare Integer references when you're interested in the underlying int values. Use .equals() or get the int values first.

java: What is the exact behaviour of comparing Integers in Java?, This question already has an answer here: Comparing Integer values in Java, strange behavior 3 answers as far as I understand due to Java autobox. Integer comparison in Java is tricky, in that int and Integer behave differently. I get that part. But, as this example program shows, (Integer)400 (line #4) behaves differently than (Integer)5 (l

To compare the Integers correctly, you need to use .equals() or compare their primitive values by casting to int or calling intValue() on them.

Using == checks whether the two Integers are the same Object, not whether they contain the same numerical value.

    Integer a = new Integer(1);
    Integer b = new Integer(1);

    System.out.println(a.equals(b));                  //true
    System.out.println((int)a == (int)b);             //true
    System.out.println(a.intValue() == b.intValue()); //true
    System.out.println(a == b);                       //false

Edited to illustrate Jon's point from the JLS about autoboxing:

    Integer a = 1;
    Integer b = 1;
    System.out.println(a.equals(b));                  //true
    System.out.println((int)a == (int)b);             //true
    System.out.println(a.intValue() == b.intValue()); //true
    System.out.println(a == b);                       //true


    Integer a = 128;
    Integer b = 128;
    System.out.println(a.equals(b));                  //true
    System.out.println((int)a == (int)b);             //true
    System.out.println(a.intValue() == b.intValue()); //true
    System.out.println(a == b);                       //false

Equality comparisons and sameness, JavaScript provides three different value-comparison operations: +0 (giving it the same behavior as === except on those special numeric values). except in rare cases console.log(obj == null); console.log(obj == undefined); 32-bit integer type, -0 will not survive a round trip after an inverse operation. Comparing Integers. When comparing two integer values, Java provides a couple options. In Java, all primitive data types (such as int, float, double, and byte) have individual wrapper classes. Integer is a wrapper class of int, and it provides several methods and variables you can use in your code to work with integer variables.

Sounds like something is funky with auto-boxing when you use == on the two integers.

I would assume that it works fine when using Integer if you use the equals() method? That would by my guess anyway.

You're not using java 1.4 or something are you?

EXP03-J. Do not use the equality operators when comparing values , Use of the == and != operators for comparing the values of boxed primitive types that are Note that Java Virtual Machine (JVM) implementations are allowed, but not Code that depends on implementation-defined behavior is nonportable. The Integer class is guaranteed to cache only integer values from -128 to 127  Questions for java. 6879. Comparing Integer values in Java, strange behavior. 9746. Visual Studio 2013 SQL Schema Compare: Ignore Column Order;

Interface Comparator<T>, A comparison function, which imposes a total ordering on some collection of objects. only if, e2)==0 has the same boolean value as e1.​equals(e2) inconsistent with equals, the sorted set (or sorted map) will behave "strangely. Returns a negative integer, zero, or a positive integer as the first argument is  In both cases, we are comparing “object references” but in first case, since the value was in the range for both objects hence, Java assigned the same reference location to both objects, making the condition “true” on comparing memory location for two objects. Now, the question is why between –128 to 127?.

Chapter 4. Types, Values, and Variables, The values of the integral types are integers in the following ranges: The comparison operators, which result in a value of type boolean : The Java programming language requires that floating-point arithmetic behave as if every with an argument expression that had type Collection<Object> , which would be quite rare. is comparing with ==, so it unboxes your Long, and you are comparing two primitives, both of which are zero. This one: System. out. println (longWrapper. equals (0)); is comparing with equals, so it boxes up the (int) zero as an Integer. A Long object is never equal to an Integer object, even if they are holding the same number.

Comparing Objects, In Java, we can distinguish two kinds of equality. Object reference equality: when two object references point to the same object. Object value equality: when two  The title of your thread was "comparing sign of a number in java", and signum() treats 0 differently from any other value. In strictly binary terms, the "sign" of a 0 is ' + ', because the sign bit indicates whether a number is negative or not, so a "check to see if given integers digits a, b are both positive or both negative" can be