This question already has an answer here:
- Why is 128==128 false but 127==127 is true when comparing Integer wrappers in Java? 6 answers
- How to properly compare two Integers in Java? 8 answers
My Question about Wrapper classes. Case 1: I'm Declaring two Integer
variables and assigning same values 127
, and i'm printing both hashCode. It's Generated same hashCode and result will be printed true
. But In Case 2: Generated the Same hashCode but result will be printing false
. Please Could you relate. Why Printing a false
result.
package com.oca.test.exam;
public class TestCasesIntegerAndDouble {
public static void main(String[] args) {
//Case 1:
Integer i1 = 127;
Integer i2 = 127;
System.out.println(i1.hashCode()); //127
System.out.println(i2.hashCode()); //127
System.out.println(i1 == i2); //true
//Case 2:
Double d1 = 127.0;
Double d2 = 127.0;
System.out.println(d1.hashCode());//1080016896
System.out.println(d2.hashCode());//1080016896
System.out.println(d1 == d2); //false
}
}