How is this different from the following?
This line of code here:
String newString = new String(oldString.getBytes("UTF-8"), "UTF-8"));
constructs a new String object (i.e. a copy of oldString), while this line of code:
String newString = oldString;
declares a new variable of type java.lang.String and initializes it to refer to the same String object as the variable oldString.
Is there any scenario in which the two lines will have different outputs?
Absolutely:
String newString = oldString;
boolean isSameInstance = newString == oldString; // isSameInstance == true
vs.
String newString = new String(oldString.getBytes("UTF-8"), "UTF-8"));
// isSameInstance == false (in most cases)
boolean isSameInstance = newString == oldString;
a_horse_with_no_name (see comment) is right of course. The equivalent of
String newString = new String(oldString.getBytes("UTF-8"), "UTF-8"));
is
String newString = new String(oldString);
minus the subtle difference wrt the encoding that Peter Lawrey explains in his answer.
String newString = oldString;, you still only have one copy of the string (you're just pointing to it from two variables). The decode/encode makes a copy of the string. Not that it matters much, sinceStrings are immutable. This probably isn't why that old code is that way, though;Stringhas a much more direct way to clone itself (String(String)). I can't think of a good reason why you'd do the encoding/decoding, other than testing theStringclass's encoding/decoding methods.