Is a String literal stored on the stack? Is a new String stored on the stack?
All objects are stored on the heap (including the values of their fields).1
Local variables (including arguments) always contain primitive values or references and are stored on the stack.1
So, for your two lines:
String one = "abc";
String two = new String("abc");
You'll have two objects on the heap (two String objects containing "abc"
) and two references, one for each object, on the stack (provided one
and two
are local variables).
(Actually, to be precise, when it comes to interned strings such as string literals, they are stored in the so called string pool.)
How many objects are created and how is the reference in memory?
It is interesting that you ask, because Strings are special in the Java language.
One thing is guaranteed however: Whenever you use new
you will indeed get a new reference. This means that two
will not refer to the same object as one
which means that you'll have two objects on the heap after those two lines of code.
1) Formally speaking the Java Language Specification does not specify how or where values are stored in memory. This (or variations of it) is however how it is usually done in practice.
The first one is called as a String Literal and created at the time of compilation of the program and the 2nd one is string object and is created at the runtime.
As you used new keyword in 2nd case so it is allocated in heap.
In the first case the objects are created with the mechanism called interning. When you try to create another string literal representing the same sequence of characters, then instead of creating a new object compiler will refer to the previous string created and stored in the string pool