I am new in java.
In java, String is a class.But
we do not have to use new keyword to create an object of class String where as new is used for creating objects for other classes.
I have heard about Wrapper classes like Integer,Double which are similar to this.
But String is not Wrapper,isn’t it?
Actually what is happening when i use
String message = "Hai";
??
How it is different from
String message = new String("Hai");
Here is message a reference variable or something else??
Are there other classes which do not require new to create object ??
With the following line you are not creating a new
Stringobject in the heap but reusing a string literal (if already available):"Hai"is a string literal in the string literal pool. Since, strings are immutable, they are reusable so they are pooled in the string literal pool by the JVM. And this is the recommended way, because you are reusing it.But, with the following you are actually creating a new object (in the heap):
new String("Hai")is a newStringobject. In this case, even if the literal"Hai"was already in the string literal pool, a new object is created. This is not recommended because chances are that you might end with more than oneStringobjects with the same value.Also see this post: Questions about Java's String pool
Actually, you can not create any object in Java without using the keyword
new.e.g.
Does, not mean that the
Integerobject is created without usingnew. It’s just not required for us to use thenewkeyword explicitly. But under the hood, if theIntegerobject with value 1 does not already exist in cache (Integerobjects are cached by JVM),newkeyword will be used to create it.