Q:

Java-trouble with not equal to

I am trying to solve a question. But the program control is going into the if statement even when both the numbers I check are the same which is not supposed to happen. What is the reason?
static int lonelyinteger(int[] a) {
Integer[] b=new Integer[a.length];
for(int i=0;i<a.length;i++){
    b[i]=new Integer(a[i]);
}
int val=0;
Arrays.sort(b);
boolean flag=false;
for(int i=0;i<a.length-2;i+=2)
    if (b[i]!=b[i+1]){
        val=b[i];
        flag=true;
        break;
    }
if(flag==true)
    return val;
else
    return b[a.length-1];

A:

You are using != on Integer objects. This will only work with integer values between -128 and 127 (reference) because these are cached by the JVM. But it won't work for larger/smaller values. Instead use .equals
if (!b[i].equals(b[i+1])){
     val=b[i];
     flag=true;
     break;
}

As correctly pointed out by Jesper in the comments, the cache used for Integer objects by the JVM is not used when you force the JVM to create new Integer objects through the explicit call of the constructor as in new Integer(value). Calling the constructor will create new Integer instances instead of returning the cached Integer instances, which means that != and == which check whether the two objects are the same instance will always think the instances are different. 

