Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

if i write below code(in java):

Integer a =new Integer(5);
Integer b=new Integer(5);
if(a==b){
  System.out.println("In ==");
}
if(a.equals(b)){
 System.out.println("In equals");
}

My output is: "In equals" But if i change first and second line to ->

Integer a =5;
Integer b=5;

then my o/p is:

In == 
In equals

So what is difference in creating a Integer object? How it gets created when we do Integer a =5?

Does it mean that a and b object refer to same object, if i create Integer a=5 and creates another object Integer b=5 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
179 views
Welcome To Ask or Share your Answers For Others

1 Answer

Integer a = 5; is called autoboxing, compiler converts this expression into actual

Integer a = Integer.valueOf(5);

For small numbers, by default -128 to 127, Integer.valueOf(int) does not create a new instance of Integer but returns a value from its cache. So here

Integer a = 5;
Integer b= 5;

a and b point to the same Object and a == b is true.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...