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?
A string is always different from a string literal: a string will be stored in heap and string literal is stored in the stack because the size of the string literal is known at compile time.
String literals are stored in C as an array of chars, terminted by a null byte. A null byte is a char having a value of exactly zero, noted as '\0'.
String literals (or more accurately, the String objects that represent them) are were historically stored in a Heap called the "permgen" heap.
If the literal is already present in the pool, it returns a reference to the pooled instance. If the literal is not present in the pool, a new String object takes place in the String pool.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With