Lets say we do
String s=new String ("test");
String s="test";
And
Integer i=new Integer(10);
Integer i=10;
What is the difference ?
Lets say we do
String s=new String ("test");
String s="test";
And
Integer i=new Integer(10);
Integer i=10;
What is the difference ?
String s=new String ("test") >> Will always create a new instance.
String s="test" >> If the String literal "test" is already present in string pool ( Java Heap) , reference s will point to this literal, No new instance will be created. Please refer below image for more clarity.
Integer i=new Integer(10);
Integer i=10;
What is the difference ?
Integer i = new Integer(10);
The above statement constructs a newly created Integer object that represents the specified int value. i is a reference variable, and new Integer(10) creates an object of type Integer with a value of int 10, and assigns this object reference to the variable i.
More info about Integer at: java.lang.Integer
Consider the statement:
Integer i = 10;
The result is same as that of the earlier construct; an integer wrapper object is created. It is just a convenience syntax. For example, see the following code:
Integer i = new Integer(10);
System.out.println(++i); // this prints 11
There is no such syntax as ++ in the java.lang.Integer class definition. What is happening here?
The statement ++i, unboxes the Integer to an int, performs the ++ operation on the int value, and then boxes it back - which results in an object integer with the int value incremented from 10 to 11. This feature is called Autoboxing; note that this feature was introduced in Java 5.
NOTE: The above clarification doesn't apply to the question asked in this post regarding the String class.