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

前端 未结 5 877
隐瞒了意图╮
隐瞒了意图╮ 2020-12-05 22:33

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.o         


        
5条回答
  •  感情败类
    2020-12-05 22:54

    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.

提交回复
热议问题