Java uses the Flyweight design pattern to manage String instances in JVM. This pattern in short comes down to sharing objects that could potentially have too many instances to store.
String s ="hello";
Here, the JVM first checked in the String pool if "hello" already existed. If it did, s
starts pointing to it directly. Otherwise, first "hello" gets added to the pool and then s
points to it.
String s= new String ("hello");
Here, the literal string "hello" was already present in the String pool but the use of new still goes ahead and creates a new String object on the heap with the same value "hello".
String s1= new String("hello");
Same as above. We have three String objects by now.
String s = null;
Here, you've simple initialized a variable to null
. Nothing special going on here.
String s = new String (null);
This won't work because String constructor is overloaded. It may take a String
; it may take a char[]
as well. But when you pass it a null
compiler doesn't know which constructor to invoke because it doesn't have any data type to make a match on and hence it gives you an ambiguity error.