What is the difference between
String name1 = "some name";
and
String name1 = new String("some name")
Which is better and good for use?
thanks
What is the difference between
String name1 = "some name";
and
String name1 = new String("some name")
Which is better and good for use?
thanks
Generally use String name1 = "some name"; But, if you want that strings to has different references, use new initialization.
Java has some optimization about strings. = "" initilizations checks string pool if same value initialized before.
String s1 = "test";
String s2 = "test";
String s3 = new String("test");
s1 == s2 // this is true because of string pool
s1 == s3 // this is false because of s3 is new instance
In the above example, s1 and s2 placed at string pool s3 is outside of java string pool.
Using new String causes creation new instances and more memory consuption.
Take a look for more information about string pool : https://www.journaldev.com/797/what-is-java-string-pool