Himanshu Kansal wrote:The String class is the only class type that work out of a stack by default and String s = "string" is that, behaving almost as a primitive. It places this string value on the stack. Whereas, String s = new String("string"); creates a new place holder, a new object for this String. It would go to the Heap where all other objects go.
This is not exactly right...
All objects are on the heap. Objects are never on the stack in
Java.
Java has an optimization technique for strings, called the string pool. If you use the same literal string in your source code multiple times, then Java creates only one String object, which is shared between all the places where you use that string literal. For example, if you do this:
then there is just one String object, containing "Hello", and variables 'one' and 'two' are both referring to that same String object. Note that that String object is on the
heap, just like any other object in Java.
To keep track of String objects that are the same, Java puts a reference to such String objects in the string pool.
When you explicitly use 'new' to create a String object, like this:
then this is what happens:
There is a String object that contains "Hello", which is created for the string literal in the source code.A new String object is created and the content of the String object mentioned above is copied to it.
Note that this is unnecessary and inefficient.
You should never use new String("...") in Java programs. If you see a fellow programmer doing that, explain to him or her that it's wrong!