Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integer class object [duplicate]

Tags:

java

I'd a code snippet:

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'm not getting why the output is so? the Output is:
a & b Both are equal
c & d are not equal
I'm using jdk1.7

like image 850
Mohammad Faisal Avatar asked Nov 22 '11 09:11

Mohammad Faisal


People also ask

How do you duplicate an object in Java?

The clone() method of the class java. lang. Object accepts an object as a parameter, creates and returns a copy of it.

What is clone () in Java?

Clone() method in JavaIt creates a new instance of the class of the current object and initializes all its fields with exactly the contents of the corresponding fields of this object. Using Assignment Operator to create a copy of the reference variable. In Java, there is no operator to create a copy of an object.


1 Answers

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

like image 180
Björn Pollex Avatar answered Oct 08 '22 20:10

Björn Pollex