Tldr: it depends.
Each time you create a String, you create a new object as well (but this also depends on the String pool). You can prove this by comparing two strings with ==
. ==
tests for reference equality (whether they are the same object), while .equals()
tests for content equality.
System.out.print("Enter a sentence : ");
final String mySentence = keyboard.next();
System.out.println("The original is : " + mySentence);
final String mySentence2 = mySentence.toUpperCase();
System.out.println("The same one is : " + mySentence);
final String mySentence3 = mySentence.toUpperCase();
System.out.println("The raised is : " + mySentence3);
System.out.println(mySentence == mySentence2);
System.out.println(mySentence3 == mySentence2);
System.out.println(mySentence3 == mySentence);
The output for input string "FOO" is (1 object created)
The original is : FOO
The same one is : FOO
The raised is : FOO
true
true
true
The output for input string "foo" is (3 objects created)
The original is : foo
The same one is : foo
The raised is : FOO
false
false
false
toUpperCase()
calls toUpperCase(Locale.getDefault())
, which creates a new String object only if it has to. If the input String is already in upper case, it returns the input String (see here).
(plus 7 objects if you count the Strings in println
)