Java syntax: When declaring a string, what is the purpose of the new keyword in front of the string instead of just simply assigning it.
Example:
String str = new String ("Welcome!");
String strTwo = "Welcome!";
What is the difference?
Java syntax: When declaring a string, what is the purpose of the new keyword in front of the string instead of just simply assigning it.
Example:
String str = new String ("Welcome!");
String strTwo = "Welcome!";
What is the difference?
new String ("Welcome!") allocates a new string that's a copy of the given string.
This is almost never useful since Java strings are immutable.
The one case where it makes a difference is the new string will not be == to the given string. You should compare strings with .equals() in the first place.
Note that Java string literals are interned into a table of all the string literals. That way they share storage. It also makes == work for two string literals, but again you should only do that in very special cases.
Mostly, I think programmers coming from C++ use new because there it's needed to convert a C string literal into a std::string object.