The answer is a bit more complicated than some of the other answers suggest.
The String value that corresponds to a String literal in your source code gets created once, when the class is loaded. Furthermore, these Strings are automatically "interned", which means that if the same literal appears at more than one place in any class, only one copy of the String will be kept. (Any other copies, if they were created will get garbage collected.)
When the application calls new String(...)
, when it evaluates a String concatenation expression (i.e. the +
operator), or when it calls one of the many library methods that create Strings under the hood, a new String will be created.
So to answer your questions:
1 - The following will not actually create a String at all. Rather it will return a String that was created when the class was loaded:
return "some string";
2 - The following will create two Strings. First it will call someObject.toString(), then it will concatenate that with the literal to give another String.
return "The answer is :" + someObject;
3 - The following will not create a String; see 1.
throw new Exception("Some message");
4 - The following will create two Strings when it is executed; see 2.
throw new Exception(someObject + "is wrong");
(Actually, 3 and 4 gloss over the fact that creating an exception causes details of the current thread's call stack to be captured, and those details include a method name, class name and file name for each frame. It is not specified when the Strings that represent these things actually get created, or whether they are interned. So it is possible that the act of creating an Exception object triggers creation of a number of Strings.)