Is a String literal stored on the stack? Is a new String stored on the stack?

Some Java Guy picture Some Java Guy · Apr 3, 2012 · Viewed 44.8k times · Source

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?

Answer

aioobe picture aioobe · Apr 3, 2012

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.