String str = "Hello"+"World";
String str1 = str + "hello";
How many objects are created and how many references are created?
String str = "Hello"+"World";
String str1 = str + "hello";
How many objects are created and how many references are created?
String is an immutable object. Whenever you manipulate a String, the JVM creates (at least) a new String and assigns it the new (concatenated) value.
As you did not specify you only care about String objects and references, we need to talk about StringBuffers. StringBuffers are (beside StringBuilders) a class that tries to work around the immutable nature of Strings. We all know, many times we just need to add two or more Strings together.
Imagine this code:
String sentence = "the " + "quick " + "brown " + "fox ";
Often times, when that happens, the Java Compiler will not create these Strings, one at a time adding them together, then forgetting about all intermediary Strings. What happens is that a StringBuffer is created. Then, all single Strings are added by using StringBuffer.append(String), then at the end one String is returned.
What you can say for sure is that 3 String references are created, referencing the inlined (and pooled) Strings "Hello", "World" and "hello". Each reference references a different String. That would have changed if the third word would have been "Hello" as well (uppercase h).