which one is better
System.out.println(\"hello world\");
or
String s=\"hello world\";
System.out.println(s);
There is no difference in this case.
It's important to realize how references works, and that local variables are distinct from the objects they are referring to. The memory required by local variables themselves are insignificant; you should never hesitate from declaring local variables if it makes the code more readable.
Consider for example the following code:
String s1 = "a very long string...";
String s2 = s1;
This code declares two String
references, but they both refer to the same String
object. The memory requirement is not doubled in cases like this.
You should never underestimate how smart the compiler can be at optimizing codes. Consider the following for example:
System.out.println("Hello world!");
System.out.println("Hello world!");
System.out.println("Hello world!");
The above snippet in fact does NOT store the string object "Hello world!"
three times in memory! The literal is interned and only stored once in memory.
JLS 3.10.5 String Literals
Each string literal is a reference to an instance of
class String
.String
objects have a constant value. String literals --or, more generally, strings that are the values of constant expressions-- are "interned" so as to share unique instances, using the method String.intern.
"string"
vs new String("string")