The two following codes give me the same result even though only one of them use the keyword new
:
Code 1:
Integer test = new Integer(3);
Code 2:
Integer test = 3;
From an OOP perspective, is there anything different between the two codes?
The two following codes give me the same result even though only one of them use the keyword new
:
Code 1:
Integer test = new Integer(3);
Code 2:
Integer test = 3;
From an OOP perspective, is there anything different between the two codes?
Instantiating variables with new keyword allocating the variable in the heap memory as a new object but if you used direct initialization the variable will be stored into the JVM pooled memory and if you declared a new variable with the same value it will reference the value for the first variable , there is two benefits of using direct initializing :
Note : you should be aware of using direct initializing as the JVM pooled memory has limited size .
What is actually happening here is the compiler is generating the same byte code for the line test = 3;
as if you wrote test = Integer.valueOf(3);
. In Java, this is called autoboxing. It allows primitive types to be converted to an Object (reference type) and vice-versa without explicitly declaring so in your code. You can read more about it here: Autoboxing and Unboxing at the Oracle Java Tutorials.
In Java, at some point, almost all instances of objects are created with the new
keyword, and it is necessary to use new
to call a constructor, which will allocate memory for and initialize the fields of an object; whether it's done explicitly by the programmer or behind the scenes is another matter. For example, Integer.valueOf(3)
could create a new instance of Integer representing the primitive int 3 when called, but it could also return an old reference to a previously created instance of Integer representing 3, since instances of the Integer class are immutable. Either way, you'll get a reference to an Integer object representing the primitive int value 3.