Possible Duplicate:
difference between string object and string literal
Let’s say I have two statements.
String one = "abc";
String two = new String("abc");
Which one is a stack memory and which is stored in heap?
What is the difference between these both?
How many objects are created and how is the reference in memory?
What is the best practice?
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:
You’ll have two objects on the heap (two String objects containing
"abc") and two references, one for each object, on the stack (providedoneandtwoare 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.)
It is interesting that you ask, because Strings are special in the Java language.
One thing is guaranteed however: Whenever you use
newyou will indeed get a new reference. This means thattwowill not refer to the same object asonewhich 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.