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

前端 未结 5 880
隐瞒了意图╮
隐瞒了意图╮ 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:57

    Integer wrapper shares few properties of String class. In that it is immutable and that can be leveraged by using intern() like functionality.

    Analyse this:

    String a = "foo";
    String b = "foo";
    String c = new String("foo");
    String d = new String("foo");
    
    a == b   //true
    c == d   //false
    

    The reason is when JVM creates a new String object implicitly it reuses existing String object which has the same value "foo", as in case a and b.

    In your case JVM implicitly auto-boxes the ints and re-uses existing Integer object. Integer.valueOf() can be used explicitly to re-use existing objects if available.

提交回复
热议问题