2

which one is better

System.out.println("hello world");

or

String s="hello world";
System.out.println(s);
Lucero
  • 59,176
  • 9
  • 122
  • 152
kaka
  • 7,425
  • 4
  • 19
  • 23

4 Answers4

9

There is no difference in terms of memory allocation for this simple example.

Lucero
  • 59,176
  • 9
  • 122
  • 152
6

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.

References

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.

Related questions

Community
  • 1
  • 1
polygenelubricants
  • 376,812
  • 128
  • 561
  • 623
0

Check out JLS to understand how strings are treated internally by JVM.

reevesy
  • 3,452
  • 1
  • 26
  • 23
Jugal Shah
  • 3,621
  • 1
  • 24
  • 35
0

No difference.

But, if you were to compare

String s=new String("hello world");
System.out.println(s);

with

System.out.println("hello world");

Then there would be a potential difference, as the latter case would be a candidate for string internalisation, wheras the former would not.

pauljwilliams
  • 19,079
  • 3
  • 51
  • 79