JVM strings stored in memory

What is the difference (from memory) between

private static final String FAILURE_MESSAGE=    "...";

protected String getFailedMsg() {
    return FAILURE_MESSAGE;
}

      

and

protected String getFailedMsg() {
    return "...";
}

      

Assuming FAILURE_MESSAGE

only referring to the above function.

I mean where and how are the above objects / strings stored in memory in the above cases? Is this JVM specific?

Edit: I know the string is interned in the first approach, but where is this value stored / held / (interned?) In the second approach before the function is called?

Second edit as an idea - what if strings are replaced with int or some other class that is not a string?

+3


source to share


5 answers


The generated bytecode is the same in both cases:

protected java.lang.String getFailedMsg()
    0 ldc 2 (java.lang.String) "..."
    2 areturn

      



so it's pure sugar.

+1


source


The first example does not compile, but the second example does.

Performance is usually less important than simplicity and clarity, and you have a good example. If compiled, the first example will be as fast as the second.



BTW: It doesn't matter how many times and how many classes a string literal is used, they will all be String.intern () , so they will all be the same object.

+4


source


String literals refer to the same object String

, so there is no memory difference in this case.

Section 3.10.5 String Literals of the Java 3.0 Language Specification:

A string literal always refers to the same instance (Β§4.3.1) of the String class ... [they] are "interned" to exchange unique instances using the String.intern method.

+1


source


All String literals will be interned, so it makes no difference (from memory, looking at the instance String

).

The only difference is that in your first case, the class contains a single reference pointer to a String instance. The second approach only creates a reference to the stack.

+1


source


In both cases, it creates a literal in the string pool. After String s = "..." is created, if u tries to return "..." in either method, both point to the same string literal created in the string pool.

0


source







All Articles