2

I have a really basic question about using new in java statement. For example, the return clause at the very end uses new for String. Why String here needs to be created? Under what kind of situations would people choose to use new?

public class A extends java.lang.Object {

    public int number;

    public String toString() {

        return new String("Value : " + number);

    }
}
Marcel Offermans
  • 3,313
  • 1
  • 15
  • 23
lovechillcool
  • 762
  • 2
  • 10
  • 32
  • possible duplicate of http://stackoverflow.com/questions/27519657/difference-between-creating-java-string-with-and-without-new-operator and http://stackoverflow.com/questions/6952581/what-is-the-difference-between-strings-allocated-using-new-operator-without-ne – Droidekas Feb 18 '15 at 05:43

2 Answers2

7

Under no circumstance, since String is immutable there is no purpose in explicitly creating a copy of a string unless you really need a copy, from Javadoc, about the constructor:

Initializes a newly created String object so that it represents the same sequence of characters as the argument; in other words, the newly created string is a copy of the argument string. Unless an explicit copy of original is needed, use of this constructor is unnecessary since Strings are immutable.

An expression "Value : " + number already evaluates as a new String so return new String("Value : " + number) is equivalent to

String tmp = "Value : " + number;
return new String(tmp);

Which you can see creates an useless copy.

Jack
  • 131,802
  • 30
  • 241
  • 343
1

new String("Value:" + number) is redundant.
You attempt to instantiate a new String object by copying an existing string.Constructing new String object in this way is rarely necessary, and may cause performance problems if done often enough. This is enough:

public class A extends java.lang.Object {

    public int number;

    public String toString() {
        return "Value : " + number;
    }

}
Vy Do
  • 46,709
  • 59
  • 215
  • 313