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

我怕爱的太早我们不能终老 提交于 2019-11-27 21:45:20
Evgeniy Dorofeev

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.

In Java, you should never use the new Integer, even though it is valid syntax it is not the best way to declare integers as you have found out. Use instead Integer.valueOf(int) This has multiple advantages.

You are not creating extra objects needlessly. Whenever you use the new operator you are forcing the vm to create a new object which is not needed in most cases. valueOf(int) will return a cached copy. Since Integer objects are immutable this works great. This means that you can use == though in practice you should use a null safe compare like in Apache ObjectUtils

The == operator tests for equality. References are only equal when they refer to the same object in memory. equals method ensures 2 object instances are 'equivalent' to each other.

Integer a = new Integer(5);
Integer b = a;

a == b; // true!
a.equals(b); // true
b = new Integer(5);
a == b; // false
a.equals(b); // true

Primitives are equal whenever their value is the same.

int a = 5; int b = a;
a == b;  // true!

for primitive data types like int the equality operator will check if the variables are equal in value

for reference data types like your java.lang.Integer objects, the equality operator will check if the variables reference the same object. In the first case, you have two "new" and separate integer objects, so the references are different

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.

I believe when you create using new operator it creates object reference. In first case, there are two object references and they are not same but their value is same. That is not the situation in second case.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!