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?
source to share
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.
source to share
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.
source to share
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.
source to share