The issue of the documentation has been addressed by the accepted answer.
I just want to respond to this comment ... which is probably the root of your problem.
But that assumes it doesn't make sense to pass null. Suppose you are copying some Object that has many data member fields, some of which are Strings, and which may or may not be null. In that case I want String(String) to return null, specifically, I want it to copy the null value.
That is not possible. The JLS specifically states that the new
operation yields a new object and not a null
.
If you want to be able to "create and return an object or null
" you have to embed this logic in a factory method of some kind; e.g.
String myNewString(String s) {
return s == null ? s : new String(s);
}
But it is also worth noting that in most circumstances copying a String
in Java is unnecessary and wasteful. You should only do this if your application is specifically making use of the object identity of the strings; i.e. that it uses ==
to compare string objects and depends on strings with the same characters comparing as false
. (Applications that require that are pretty rare ...)