Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a String literal stored on the stack? Is a new String stored on the stack? [duplicate]

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?

like image 704
Some Java Guy Avatar asked Apr 03 '12 10:04

Some Java Guy


People also ask

Are string literals stored in the stack?

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.

Where does string literals get stored?

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'.

How the string literals are stored in Java?

String literals (or more accurately, the String objects that represent them) are were historically stored in a Heap called the "permgen" heap.

What happens when you store a new string literal value that is already present in the string pool?

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.


1 Answers

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.

like image 99
aioobe Avatar answered Sep 19 '22 15:09

aioobe