String comparison by reference in java [duplicate] - java

I have a simple question about strings in Java. The following segment of simple code just concatenates two strings and then compares them with ==.
String str1="str";
String str2="ing";
String concat=str1+str2;
System.out.println(concat=="string");
The comparison expression concat=="string" returns false as obvious (I understand the difference between equals() and ==).
When these two strings are declared final like so,
final String str1="str";
final String str2="ing";
String concat=str1+str2;
System.out.println(concat=="string");
The comparison expression concat=="string", in this case returns true. Why does final make a difference? Does it have to do something with the intern pool or I'm just being misled?

When you declare a String (which is immutable) variable as final, and initialize it with a compile-time constant expression, it also becomes a compile-time constant expression, and its value is inlined by the compiler where it is used. So, in your second code example, after inlining the values, the string concatenation is translated by the compiler to:
String concat = "str" + "ing"; // which then becomes `String concat = "string";`
which when compared to "string" will give you true, because string literals are interned.
From JLS §4.12.4 - final Variables:
A variable of primitive type or type String, that is final and initialized with a compile-time constant expression (§15.28), is called a constant variable.
Also from JLS §15.28 - Constant Expression:
Compile-time constant expressions of type String are always "interned" so as to share unique instances, using the method String#intern().
This is not the case in your first code example, where the String variables are not final. So, they are not a compile-time constant expressions. The concatenation operation there will be delayed till runtime, thus leading to the creation of a new String object. You can verify this by comparing byte code of both pieces of code.
The first code example (non-final version) is compiled to the following byte code:
Code:
0: ldc #2; //String str
2: astore_1
3: ldc #3; //String ing
5: astore_2
6: new #4; //class java/lang/StringBuilder
9: dup
10: invokespecial #5; //Method java/lang/StringBuilder."<init>":()V
13: aload_1
14: invokevirtual #6; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
17: aload_2
18: invokevirtual #6; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
21: invokevirtual #7; //Method java/lang/StringBuilder.toString:()Ljava/lang/String;
24: astore_3
25: getstatic #8; //Field java/lang/System.out:Ljava/io/PrintStream;
28: aload_3
29: ldc #9; //String string
31: if_acmpne 38
34: iconst_1
35: goto 39
38: iconst_0
39: invokevirtual #10; //Method java/io/PrintStream.println:(Z)V
42: return
Clearly it is storing str and ing in two separate variables, and using StringBuilder to perform the concatenation operation.
Whereas, your second code example (final version) looks like this:
Code:
0: ldc #2; //String string
2: astore_3
3: getstatic #3; //Field java/lang/System.out:Ljava/io/PrintStream;
6: aload_3
7: ldc #2; //String string
9: if_acmpne 16
12: iconst_1
13: goto 17
16: iconst_0
17: invokevirtual #4; //Method java/io/PrintStream.println:(Z)V
20: return
So it directly inlines the final variable to create String string at compile time, which is loaded by ldc operation in step 0. Then the second string literal is loaded by ldc operation in step 7. It doesn't involve creation of any new String object at runtime. The String is already known at compile time, and they are interned.

As per my research, all the final String are interned in Java. From one of the blog post:
So, if you really need to compare two String using == or != make sure you call String.intern() method before making comparison. Otherwise, always prefer String.equals(String) for String comparison.
So it means if you call String.intern() you can compare two strings using == operator. But here String.intern() is not necessary because in Java final String are internally interned.
You can find more information String comparision using == operator and Javadoc for String.intern() method.
Also refer this Stackoverflow post for more information.

If you take a look at this methods
public void noFinal() {
String str1 = "str";
String str2 = "ing";
String concat = str1 + str2;
System.out.println(concat == "string");
}
public void withFinal() {
final String str1 = "str";
final String str2 = "ing";
String concat = str1 + str2;
System.out.println(concat == "string");
}
and its decompiled with javap -c ClassWithTheseMethods
versions you will see
public void noFinal();
Code:
0: ldc #15 // String str
2: astore_1
3: ldc #17 // String ing
5: astore_2
6: new #19 // class java/lang/StringBuilder
9: dup
10: aload_1
11: invokestatic #21 // Method java/lang/String.valueOf:(Ljava/lang/Object;)Ljava/lang/String;
14: invokespecial #27 // Method java/lang/StringBuilder."<init>":(Ljava/lang/String;)V
17: aload_2
18: invokevirtual #30 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
21: invokevirtual #34 // Method java/lang/StringBuilder.toString:()Ljava/lang/String;
...
and
public void withFinal();
Code:
0: ldc #15 // String str
2: astore_1
3: ldc #17 // String ing
5: astore_2
6: ldc #44 // String string
8: astore_3
...
So if Strings are not final compiler will have to use StringBuilder to concatenate str1 and str2 so
String concat=str1+str2;
will be compiled to
String concat = new StringBuilder(str1).append(str2).toString();
which means that concat will be created at runtime so will not come from String pool.
Also if Strings are final then compiler can assume that they will never change so instead of using StringBuilder it can safely concatenate its values so
String concat = str1 + str2;
can be changed to
String concat = "str" + "ing";
and concatenated into
String concat = "string";
which means that concate will become sting literal which will be interned in string pool and then compared with same string literal from that pool in if statement.

Stack and string conts pool concept

Let's see some byte code for the final example
Compiled from "Main.java"
public class Main {
public Main();
Code:
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String[]) throws java.lang.Exception;
Code:
0: ldc #2 // String string
2: astore_3
3: getstatic #3 // Field java/lang/System.out:Ljava/io/PrintStream;
6: aload_3
7: ldc #2 // String string
9: if_acmpne 16
12: iconst_1
13: goto 17
16: iconst_0
17: invokevirtual #4 // Method java/io/PrintStream.println:(Z)V
20: return
}
At 0: and 2:, the String "string" is pushed onto the stack (from the constant pool) and stored into the local variable concat directly. You can deduce that the compiler is creating (concatenating) the String "string" itself at compilation time.
The non final byte code
Compiled from "Main2.java"
public class Main2 {
public Main2();
Code:
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String[]) throws java.lang.Exception;
Code:
0: ldc #2 // String str
2: astore_1
3: ldc #3 // String ing
5: astore_2
6: new #4 // class java/lang/StringBuilder
9: dup
10: invokespecial #5 // Method java/lang/StringBuilder."<init>":()V
13: aload_1
14: invokevirtual #6 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/Stri
ngBuilder;
17: aload_2
18: invokevirtual #6 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/Stri
ngBuilder;
21: invokevirtual #7 // Method java/lang/StringBuilder.toString:()Ljava/lang/String;
24: astore_3
25: getstatic #8 // Field java/lang/System.out:Ljava/io/PrintStream;
28: aload_3
29: ldc #9 // String string
31: if_acmpne 38
34: iconst_1
35: goto 39
38: iconst_0
39: invokevirtual #10 // Method java/io/PrintStream.println:(Z)V
42: return
}
Here you have two String constants, "str" and "ing" which need to be concatenated at runtime with a StringBuilder.

Though, when you create using String literal notation of Java, it automatically call intern() method to put that object into String pool, provided it was not present in the pool already.
Why does final make a difference?
Compiler knows the final variable never gonna change, when we add these final variables the output goes to String Pool because of str1 + str2 expression output also never gonna change, So finally compiler calls inter method after output of the above two final variables. In case of non-final variable compiler do not call intern method.

Related

Related to String interning

public static void main(String[] args) {
String a = new String("lo").intern();
final String d = a.intern();
String b = "lo";
final String e = "lo";
String c = "Hello";
System.out.println(b==a);//true
System.out.println(d==a);//true
System.out.println(e==a);//true
System.out.println(c=="Hel"+a); //why is this false? when e==a is true
System.out.println(c=="Hel"+d); //why is this false?
System.out.println(c=="Hel"+b); //why is this false?
System.out.println(c=="Hel"+e); //this is true
}
This results in
true
true
true
false
false
false
true
The expression e==a is true implies same reference. So why the last expression is true but the 4th to last ie c== "Hel"+a is false?
The expression
"Hel" + a
Is not a compile time constant. Actually, it compiles to:
new StringBuilder().append("Hel").append(a).toString()
(or similar) which creates a new String object at runtime.
However, because e is final, the compiler can determine that the concatenation of "Hel" and e's value is a constant value, and so interns it.
all these strings are calculated in runtime, this is why they are different
System.out.println(c=="Hel"+a); //why is this false? when e==a is true
System.out.println(c=="Hel"+d); //why is this false?
System.out.println(c=="Hel"+b); //why is this false?
this one calculated during compile time, because e is final:
System.out.println(c=="Hel"+e); //this is true
if you change code to this:
System.out.println(c==("Hel"+a).intern()); //why is this false? when e==a is true
System.out.println(c==("Hel"+d).intern()); //why is this false?
System.out.println(c==("Hel"+b).intern()); //why is this false?
all of them will produce true
Java compiler (javac) translates your code in Java to byte code which is executed by the JVM.
It also does some optimizations for you. You can check the generated byte code using javap utility with -c parameter
Concatenation with final String
c==a is true because c is final
Here is the byte code for this snippet (last comparison only):
public static void main(java.lang.String[]);
Code:
0: ldc #2; //String Hello
2: astore_2
3: getstatic #3; //Field java/lang/System.out:Ljava/io/PrintStream;
6: aload_2
7: ldc #2; //String Hello
9: if_acmpne 16
12: iconst_1
13: goto 17
16: iconst_0
17: invokevirtual #4; //Method java/io/PrintStream.println:(Z)V
20: return
}
As you see the java compiler has merged the "Hel" with "lo" and just comparing two string leterals "Hello". Java interns string literals by default - that's why it returns true
Concatenation with non-final String
If you are concatenating the string literal with non-final String variable, the byte code will be different:
public static void main(java.lang.String[]);
Code:
0: ldc #2; //String lo
2: astore_1
3: ldc #3; //String Hello
5: astore_2
6: getstatic #4; //Field java/lang/System.out:Ljava/io/PrintStream;
9: aload_2
10: new #5; //class java/lang/StringBuilder
13: dup
14: invokespecial #6; //Method java/lang/StringBuilder."<init>":()V
17: ldc #7; //String Hel
19: invokevirtual #8; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
22: aload_1
23: invokevirtual #8; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
26: invokevirtual #9; //Method java/lang/StringBuilder.toString:()Ljava/lang/String;
29: if_acmpne 36
32: iconst_1
33: goto 37
36: iconst_0
37: invokevirtual #10; //Method java/io/PrintStream.println:(Z)V
40: return
}
Here we are comparing the result of java/lang/StringBuilder.toString:()Ljava/lang/String; method which obviously returns another object - it is equal to "Hello" by value but not by reference
You can find more details on comparing strings in this stackoverflow question
Even though you are using intern() method, you have to still remember that == compares by reference and not value.
So in the cases of
System.out.println(c=="Hel"+a);
System.out.println(c=="Hel"+d);
System.out.println(c=="Hel"+b);
"Hel" + a or "Hel" + d or "Hel" + b will have a new reference in memory that is not equal to that of c.
in the final case since the string value is final, the evaluation happens at compile time instead of runtime as optimization since it will never change. Also if you are thinking when you define string literal, Java internally interns them.

Java compiler not optimizing string concatenation

I have noticed that Java compiler does not converting String addition (+) to StringBuilder.append() method. I have created a class which has only one method
public void doSomething(String a, String b) {
String c = a + "a";
String d = b + "b";
String e = c + d;
String f = e;
System.out.println(f);
}
After compilation and decompilation my method looked like this:
public void doSomething(String paramString1, String paramString2)
{
String str1 = paramString1 + "a";
String str2 = paramString2 + "b";
String str3 = str1 + str2;
String str4 = str3;
System.out.println(str4);
}
Why compiler not optimizing my code? I am using ant for packaging and debug setting is false. I've also tried javac for single java file but result is the same.
Your decompiler is indeed simplifying the code.
Consider this source file:
public class foo {
public void a(String[] args) {
String b = (new StringBuilder()).append("x").append(args[0]).toString();
}
public void b(String[] args) {
String b = "x" + args[0];
}
}
javap output:
public class foo {
public foo();
Code:
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: return
public void a(java.lang.String[]);
Code:
0: new #2 // class java/lang/StringBuilder
3: dup
4: invokespecial #3 // Method java/lang/StringBuilder."<init>":()V
7: ldc #4 // String x
9: invokevirtual #5 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
12: aload_1
13: iconst_0
14: aaload
15: invokevirtual #5 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
18: invokevirtual #6 // Method java/lang/StringBuilder.toString:()Ljava/lang/String;
21: astore_2
22: return
public void b(java.lang.String[]);
Code:
0: new #2 // class java/lang/StringBuilder
3: dup
4: invokespecial #3 // Method java/lang/StringBuilder."<init>":()V
7: ldc #4 // String x
9: invokevirtual #5 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
12: aload_1
13: iconst_0
14: aaload
15: invokevirtual #5 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
18: invokevirtual #6 // Method java/lang/StringBuilder.toString:()Ljava/lang/String;
21: astore_2
22: return
}
See that the bytecodes are essentially identical: the compiler has transformed method b into method a using the StringBuilder.append optimization.
Now let's see what JD says:
public class foo
{
public void a(String[] paramArrayOfString)
{
String str = "x" + paramArrayOfString[0];
}
public void b(String[] paramArrayOfString) {
String str = "x" + paramArrayOfString[0];
}
}
That's right: JD actually takes the function a and interprets it as being a string addition, even though the original source code was specified using an explicit StringBuilder!
Therefore, we can see that JD will try to reverse the StringBuilder optimization if it detects that pattern being used.
I did javap -c Test.class and StringBuilder appeared (Java 8).
public void doSomething(java.lang.String, java.lang.String);
Code:
0: new #2 // class StringBuilder
3: dup
4: invokespecial #3 // Method StringBuilder."<init>":()V
7: aload_1
8: invokevirtual #4 // Method StringBuilder.append:(LString;)LStringBuilder;
11: ldc #5 // String a
13: invokevirtual #4 // Method StringBuilder.append:(LString;)LStringBuilder;
16: invokevirtual #6 // Method StringBuilder.toString:()LString;
19: astore_3
20: new #2 // class StringBuilder
23: dup
24: invokespecial #3 // Method StringBuilder."<init>":()V
27: aload_2
28: invokevirtual #4 // Method StringBuilder.append:(LString;)LStringBuilder;
31: ldc #7 // String b
33: invokevirtual #4 // Method StringBuilder.append:(LString;)LStringBuilder;
36: invokevirtual #6 // Method StringBuilder.toString:()LString;
39: astore 4
41: new #2 // class StringBuilder
44: dup
45: invokespecial #3 // Method StringBuilder."<init>":()V
48: aload_3
49: invokevirtual #4 // Method StringBuilder.append:(LString;)LStringBuilder;
52: aload 4
54: invokevirtual #4 // Method StringBuilder.append:(LString;)LStringBuilder;
57: invokevirtual #6 // Method StringBuilder.toString:()LString;
60: astore 5
62: aload 5
64: astore 6
66: getstatic #8 // Field System.out:Ljava/io/PrintStream;
69: aload 6
71: invokevirtual #9 // Method java/io/PrintStream.println:(LString;)V
74: return
I think the decompiler tries to simplify this to achieve a natural coding.
The Java compiler doesn't do any optimization at compile time because that's left for the JIT at runtime. If you want to build up a string efficiently across multiple statements, you should use a StringBuilder.
The + operator compiles into calls on a StringBuilder object. When you write:
String c = a + "a";
the compiler produces code as if you'd written:
String c = new StringBuilder().append(a).append("a").toString();
If you use + several times within a single expression, such as a + "a" + b + "b", the compiler will use a single StringBuilder for the whole expression, calling append as many times as necessary. But it doesn't optimize multiple statements into a single equivalent expression, so if you want to use a single StringBuilder to join all your strings together, you'll need to either write it as a single expression or use StringBuilder explicitly in your code.

Appending the string

Can anyone please explain what is the difference between below implementation of String-
1)
{
String comma=",";
return finalStr = "Hello"+comma+"Welcome"+comma+"to"+comma+"Stack"+comma+"overflow";
}
2)
{
return finalStr = "Hello,Welcome,to,Stack,overflow";
}
How many string object will be created in first (1) block, will there be only one string finalStr which refer to memory location where Hello,Welcome,to,Stack,overflow is stored or will it create multiple locations for each word and then once appended it will create a new memory location.
In both cases, only one String object will be created for each. Since, compiler is smart enough for understand the concatenation in compile time. These are string literals, they will be evaluated at compile time and only one string will be created for each cases.
As per JLS
A long string literal can always be broken up into shorter pieces and
written as a (possibly parenthesized) expression using the string
concatenation operator + [...] Moreover, a string literal always
refers to the same instance of class String.
Strings computed by constant expressions (§15.28) are computed at compile time and then treated as if they were literals.
Strings computed by concatenation at run-time are newly created and therefore distinct.
Take a look at this or this answer. The compiler will optimize some things for you. So stick with the most readable solution.
Similar questions have been asked several times, you will find some useful further information about your question if you read those answers.
use javap to check how the compiler is trying to optimize the code, i first scenario, a concatenation happen using the StringBuilder and finally toString is called
Code:
0: ldc #16 // String ,
2: astore_1
3: new #18 // class java/lang/StringBuilder
6: dup
7: ldc #20 // String Hello
9: invokespecial #22 // Method java/lang/StringBuilder."<init>":(Ljava/lang/String;)V
12: aload_1
13: invokevirtual #25 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
16: ldc #29 // String Welcome
18: invokevirtual #25 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
21: aload_1
22: invokevirtual #25 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
25: ldc #31 // String to
27: invokevirtual #25 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
30: aload_1
31: invokevirtual #25 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
34: ldc #33 // String Stack
36: invokevirtual #25 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
39: aload_1
40: invokevirtual #25 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
43: ldc #35 // String overflow
45: invokevirtual #25 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
48: invokevirtual #37 // Method java/lang/StringBuilder.toString:()Ljava/lang/String;
51: astore_2
Scenario 2
52: ldc #41 // String Hello,Welcome,to,Stack,overflow
54: astore_2
55: return
As far as I know,
In first cast JVM continuously making instant variables to keep Strings like "Hello", "Welcome", etc...
Further more, every appending operation it needs another variable to save appended String for example "Hello," + "Welcome" ...
On the other hand, second case, it allocate once for String. Thanks.

String Object. Clarification needed

Say i have the following line in my program:
jobSetupErrors.append("abc");
In the case above where jobSetupErrors is a StringBuilder(), what i see happen is:
New String Object is created and assigned value "abc"
value of that String object is assigned to the existing StringBuilder object
If that is correct, and I add 1 more line ...
jobSetupErrors.append("abc");
logger.info("abc");
In the above example are we creating String object separately 2 times?
If so, would it be more proper to do something like this?
String a = "abc";
jobSetupErrors.append(a);
logger.info(a);
Is this a better approach? Please advise
In the above example are we creating
String object separately 2 times?
No, because in Java String literals (anything in double-quotes) are interned. What this means is that both of those lines are referring to the same String, so no further optimization is necessary.
In your second example, you are only creating an extra reference to the same String, but this is what Java has already done for you by placing a reference to it in something called the string pool. This happens the first time it sees "abc"; the second time, it checks the pool and finds that "abc" already exists, so it is replaced with the same reference as the first one.
See http://en.wikipedia.org/wiki/String_interning for more information on String interning.
To help find out, I wrote a class like the following:
class Test {
String a = "abc" ;
StringBuilder buffer = new StringBuilder() ;
public void normal() {
buffer.append( "abc" ) ;
buffer.append( "abc" ) ;
}
public void clever() {
buffer.append( a ) ;
buffer.append( a ) ;
}
}
If we compile this, and then run javap over it to extract the bytecode:
14:09:58 :: javap $ javap -c Test
Compiled from "Test.java"
class Test extends java.lang.Object{
java.lang.String a;
java.lang.StringBuilder buffer;
Test();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."<init>":()V
4: aload_0
5: ldc #2; //String abc
7: putfield #3; //Field a:Ljava/lang/String;
10: aload_0
11: new #4; //class java/lang/StringBuilder
14: dup
15: invokespecial #5; //Method java/lang/StringBuilder."<init>":()V
18: putfield #6; //Field buffer:Ljava/lang/StringBuilder;
21: return
public void normal();
Code:
0: aload_0
1: getfield #6; //Field buffer:Ljava/lang/StringBuilder;
4: ldc #2; //String abc
6: invokevirtual #7; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
9: pop
10: aload_0
11: getfield #6; //Field buffer:Ljava/lang/StringBuilder;
14: ldc #2; //String abc
16: invokevirtual #7; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
19: pop
20: return
public void clever();
Code:
0: aload_0
1: getfield #6; //Field buffer:Ljava/lang/StringBuilder;
4: aload_0
5: getfield #3; //Field a:Ljava/lang/String;
8: invokevirtual #7; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
11: pop
12: aload_0
13: getfield #6; //Field buffer:Ljava/lang/StringBuilder;
16: aload_0
17: getfield #3; //Field a:Ljava/lang/String;
20: invokevirtual #7; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
23: pop
24: return
}
We can see 2 things.
First, the normal method is using the same String instance for both of those calls (indeed it is the same literal as is set to the a member variable of this class in the initialisation block)
And secondly, the clever method is longer than the normal one. This is because extra steps are required to fetch the property out of the class.
So the moral of the story is that 99% of the time, Java does things the right way on it's own, and theres no need in trying to be clever ;-) (and javap is a really cool tool for when you want to know exactly what's going on)

Does Java compiler handle inline Strings efficiently?

1.
static final String memFriendly = "Efficiently stored String";
System.out.println(memFriendly);
2.
System.out.println("Efficiently stored String");
Will Java compiler treat both (1 and 2) of these in the same manner?
FYI: By efficiently I am referring to runtime memory utilization as well as code execution time. e.g. can the 1st case take more time on stack loading the variable memFriendly?
This is covered in the Java Language Spec:
Each string literal is a reference
(§4.3) to an instance (§4.3.1, §12.5)
of class String (§4.3.3). String
objects have a constant value. String
literals-or, more generally, strings
that are the values of constant
expressions (§15.28)-are "interned" so
as to share unique instances, using
the method String.intern.
You can also see for yourself using the javap tool.
For this code:
System.out.println("Efficiently stored String");
final String memFriendly = "Efficiently stored String";
System.out.println(memFriendly);
javap gives the following:
0: getstatic #2; //Field java/lang/System.out:Ljava/io/PrintStream;
3: ldc #3; //String Efficiently stored String
5: invokevirtual #4; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
8: getstatic #2; //Field java/lang/System.out:Ljava/io/PrintStream;
11: ldc #3; //String Efficiently stored String
13: invokevirtual #4; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
public static void main(String[] args) {
System.out.println("Hello world!");
String hola = "Hola, mundo!";
System.out.println(hola);
}
Here is what javap shows as the disassembly for this code:
0: getstatic #16; //Field java/lang/System.out:Ljava/io/PrintStream;
3: ldc #22; //String Hello world!
5: invokevirtual #24; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
8: ldc #30; //String Hola, mundo!
10: astore_1
11: getstatic #16; //Field java/lang/System.out:Ljava/io/PrintStream;
14: aload_1
15: invokevirtual #24; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
18: return
Looks like the second string is being stored, whereas the first one is simply passed to the method directly.
This was built with Eclipse's compiler, which may explain differences in my answer and McDowell's.
Update: Here are the results if hola is declared as final (results in no aload_1, if I'm reading this right then it means this String is both stored and inlined, as you might expect):
0: getstatic #16; //Field java/lang/System.out:Ljava/io/PrintStream;
3: ldc #22; //String Hello world!
5: invokevirtual #24; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
8: ldc #30; //String Hola, mundo!
10: astore_1
11: getstatic #16; //Field java/lang/System.out:Ljava/io/PrintStream;
14: ldc #30; //String Hola, mundo!
16: invokevirtual #24; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
19: return
In this case, the compiler will handle both the same.
Anytime a String is defined at compile time, Java will optimize the storage of Strings.
If a string is defined at runtime, Java has no way of doing the same optomization.
The code you have is equivilant because string literals are automatically interned by the compiler.
If you are really concerned about String performance and will be reusing the same strings over and over you should take a look at the intern method on the string class.
http://java.sun.com/javase/6/docs/api/java/lang/String.html#intern()

Categories

Resources