0

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

Pieter
  • 69
  • 1
  • 2
  • First you should check this: https://stackoverflow.com/questions/4260723/concatenating-null-strings-in-java And second, you should use equals method to get the correct result of comparison of two string. Please check this link for example: https://stackoverflow.com/questions/7520432/what-is-the-difference-between-and-equals-in-java – Echoinacup Sep 07 '21 at 11:44
  • What do you expect `newStr + value` to evaluate to at the very first iteration of the loop, while your `newStr` is still `null`? I.e. what do you expect `null + 'j'` to be? – Ivar Sep 07 '21 at 11:44
  • 1
    `String newStr = null;` will result in `newStr` having the value `null` (or more precisely it references nothing). However, in string concatenation Java has special handling for `null`, i.e. it turns it into `"null"` and that's why `newStr + "java"` results in `"nulljava"`. Initialize `newStr` to an empty string instead, e.g. `newStr = ""`. – Thomas Sep 07 '21 at 11:44
  • It is "taking the value", only because you concatenate/print the "null-string" ...the (only) alternative would be an exception, right!? ...sorry that it doesn't behave as "empty string" (as you expect) – xerx593 Sep 07 '21 at 11:49
  • Okay so null is converted to "null" when you print the string or add some other value to it. And when you use a concat on it.. you would except it to concat to "null", but instead this time it will throw a NullPointerException. – Pieter Sep 07 '21 at 19:07

1 Answers1

5

When performing

newStr = newStr + value;

The null in newStr is converted to a string, being "null". Another thing you should keep in mind is that == compares references, and to compare Strings themselves, you should use str1.equals(str2) instead.

Pieter12345
  • 1,713
  • 1
  • 11
  • 18