-3

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 ?

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
Sanjay
  • 117
  • 4
  • 13
  • 4
    In your example, very little. Maybe ask the question, what's the difference between being handed a baby and giving birth – MadProgrammer Oct 05 '18 at 05:09
  • I dnt understand this . Can you elaborate in terms of java ?? Or can you make me understand both ? – Sanjay Oct 05 '18 at 05:36
  • @Sanjay-Dev i suggest you read the concept `OOP` there are many site teach about the concept. – dwir182 Oct 05 '18 at 06:04

2 Answers2

2

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.

enter image description here

Jeetendra
  • 133
  • 2
  • 15
1

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.

Community
  • 1
  • 1
prasad_
  • 12,755
  • 2
  • 24
  • 36
  • For additional info see notes from Oracle's website on [Data Types](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html), [Number classes](https://docs.oracle.com/javase/tutorial/java/data/numberclasses.html) and [Autoboxing](https://docs.oracle.com/javase/tutorial/java/data/autoboxing.html). – prasad_ Oct 05 '18 at 07:05