Why shouldn't I instantiate a string object using a constructor?

In Java, it seems to be String s = "foo"preferable String s = new String("foo").

Why? Is a new string object created in both cases? Why does the first case exclude a constructor call?

+5
source share
4 answers

Why?

Since the second approach leads to two string objects (the original is due to the string literal plus an explicit copy).

+9
source

- , . String - , , .

String, , , String. , .

, String ( , , , char , .

+4

, . , "", , , "==", equals, , , . ( == "" )

, , ,

+1

? ?

, , , , :

String s = "foo";
String s2 = "foo";

s == s2 = > true

+1
source

All Articles