Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
182 views
in Technique[技术] by (71.8m points)

java - what is difference between integer a = 5 and new Integer(5)?

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...