-3

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?

kalenpw
  • 695
  • 3
  • 10
  • 34

1 Answers1

1

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.

Jerry101
  • 12,157
  • 5
  • 44
  • 63
  • 1
    as a side note, a String actually consists of a String container object and a private char[] which contains the characters. When you use the copy constructor, it will create a new String object but internally reference the same char array. this can be done safely as String are immutable. – slipperyseal Mar 15 '17 at 01:07