What is the difference between the string s = "something"; and String s = new line ("something");

Possible duplicate:
difference between string object and string literal

When initializing a String object, there are at least two ways, for example:

String s = "some string"; String s = new String("some string"); 

Who cares?

+4
source share
4 answers

The Java language has special processing for strings; a string literal automatically becomes a String object.

So, in the first case, you initialize the link s this String object.

In the second case, you create a new String object, passing a reference to the original String object as a constructor parameter. In other words, you are creating a copy. Link s then initialized to reference this copy.

+8
source

In the first case, you can take this string from the pool, if it exists. In the second case, you explicitly create a new string object.

You can check this on these lines:

 String s1 = "blahblah"; String s2 = "blahblah"; String s3 = new String("blahblah"); String s4 = s3.intern(); System.out.println(s1 == s2); System.out.println(s1 == s3); System.out.println(s2 == s3); System.out.println(s1 == s4); Output: true false false true 
+7
source

String s = "some string"; assigns this value s from the string pool (perm.gen.space) (creates one if it does not exist)

String s = new String ("some string"); creates a new line with the value specified in the constructor, the memory allocated on the heap

The first method is recommended, as it will help reuse a literal from a string pool

+1
source

Semantically, the first assigns "some string" - s , and the second assigns a copy of "some string" - s (since "some string" already has a String ). I see no practical reasons for this in 99.9% of cases, so I would say that in most contexts, the only difference between the two lines is as follows:

  • The second line is longer.
  • The second line can consume more memory than the first.
  • As Anish-Dasappan mentions, the second one will matter on the heap, while the first one will be in the row pool - I'm not sure if this interests the programmer, but I may be missing a smart trick there.
0
source

Source: https://habr.com/ru/post/1380157/


All Articles