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".