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

5
  • First you should check this: stackoverflow.com/questions/4260723/… And second, you should use equals method to get the correct result of comparison of two string. Please check this link for example: stackoverflow.com/questions/7520432/… Commented Sep 7, 2021 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? Commented Sep 7, 2021 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 = "". Commented Sep 7, 2021 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) Commented Sep 7, 2021 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. Commented Sep 7, 2021 at 19:07

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.