Below code tests if the Strings myStr and newStr contain the same values. I expected the result to be equal, but to my surprise the line String newStr = null seems to result in newStr taking in 'null' as actual text. Is this correct?
I expected it just to be assigned a reference to nothing, resulting in no value at that point.
String myStr = "java";
char[] myCharArr = {'j', 'a', 'v', 'a'};
String newStr = null; // not an empty reference but assigning the text "null"?
for (char value : myCharArr) {
newStr = newStr + value;
}
System.out.println(newStr == myStr); // results in false: newStr is 'nulljava' and myStr 'java'
Note that when changing "String newStr = null" to String newStr = new String() you do get an empty reference and newStr will end up just being "java".
newStr + valueto evaluate to at the very first iteration of the loop, while yournewStris stillnull? I.e. what do you expectnull + 'j'to be?String newStr = null;will result innewStrhaving the valuenull(or more precisely it references nothing). However, in string concatenation Java has special handling fornull, i.e. it turns it into"null"and that's whynewStr + "java"results in"nulljava". InitializenewStrto an empty string instead, e.g.newStr = "".