Class object

I have a piece of code:

public class Test{
    public static void main(String args[]){
        Integer a = 100;
        Integer b = 100;
        Integer c = 5000;
        Integer d = 5000;

        System.out.println(a);
        System.out.println(b);
        System.out.println(c);
        System.out.println(d);
        if(a == b)
            System.out.println("a & b Both are Equal");
        else
            System.out.println("a & b are Not Equal");
        if(c == d)
            System.out.println("c & d Both are Equal");
        else
            System.out.println("c & d are Not Equal");
    }
}

I do not understand why this is so? Output:
a & b Both are equal
c & d are not equal
I usejdk1.7

+5
source share
4 answers

This is due to optimization in a virtual machine that maps small (frequently used) integers to a pool of objects that are reused. This answer explains some details.

+7
source

, java- Integer. inetger. 100 , . 5000 cahce, .

, , , , - .

+4

Integer ==, a b , c d . equals, :

public class Test{
    public static void main(String args[]){
        Integer a = 100;
        Integer b = 100;
        Integer c = 5000;
        Integer d = 5000;

        System.out.println(a);
        System.out.println(b);
        System.out.println(c);
        System.out.println(d);
        if(a.equals(b))
            System.out.println("a & b Both are Equal");
        else
            System.out.println("a & b are Not Equal");
        if(c.equals(d))
            System.out.println("c & d Both are Equal");
        else
            System.out.println("c & d are Not Equal");
    }
}

100
100
5000
5000
a & b Both are Equal
c & d Both are Equal
+2

. , 8 :

boolean Boolean char short Short int Integer long Long float Float double to type Double :

p boolean, p r Boolean, r.booleanValue() == p p , p r Byte, r.byteValue() == p p char, p r Character, r.charValue() == p p short, p r Short, r.shortValue() == p p int, p r Integer, r.intValue() == p p long, p r Long, r.longValue() == p p - float, : p NaN, p r Float, r.floatValue() p p r Float , r.isNaN() true. p - double, p NaN, p r Double, r.doubleValue() p p r Double, r.isNaN() true. p , (5.1.1). p true, false, , a char \u0000 \u007f int -128 127, r1 r2 . , r1 == r2 - http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#5.1.7

0
source

All Articles