Code: Select all
String s = null + 'g';
Code: Select all
String s = null;
s += 'g';
Code: Select all
Integer i = null;
i += 1;
Code: Select all
String s = (String)(Object)new Integer(0);
s += 'g';
Moderator: admin
Code: Select all
String s = null + 'g';
Code: Select all
String s = null;
s += 'g';
Code: Select all
Integer i = null;
i += 1;
Code: Select all
String s = (String)(Object)new Integer(0);
s += 'g';
In this case, during type checking the compiler decides that one of the arguments is of type String. Runtime, however, s instanceof String does not hold. JLS does not say what happens in this situation, but apparently it does not only convert the other operand, but all operands not of type String.If only one operand expression is of type String, then string conversion (§5.1.11) is performed on the other operand to produce a string at run time.
Why do you think so?scranen wrote:Okay, so the result is due to the type checker selecting the string concatenation semantics for the + operator. JLS is (in my opinion) unclear about the behaviour of that operator, though:In this case, during type checking the compiler decides that one of the arguments is of type String. Runtime, however, s instanceof String does not hold.If only one operand expression is of type String, then string conversion (§5.1.11) is performed on the other operand to produce a string at run time.
Take the following code:Why do you think so?
Code: Select all
String s = null;
assert(!(s instanceof String));
s = s + 'c';
Code: Select all
String s = null;
assert(!(s instanceof String));
s = s + 'c'.toString();
Code: Select all
String add(String x, Object y)
{
StringBuilder sb = new StringBuilder();
sb.append(x);
sb.append(y);
return sb.toString();
}
Code: Select all
String add(String x, Object y)
{
StringBuilder sb = new StringBuilder(x);
sb.append(y);
return sb.toString();
}
Code: Select all
String s = null;
s = s + 'c';
The explanation indeed is correct somehow, but without the details of Agoosen it sounds like null == "null". In my opinion it would help a lot to include those details in the explanation.admin wrote:Actually, the given explanation is correct but it skipped the details that you've mentioned. These details are covered in other questions.
thanks a lot. Much easier to accept it that wayIf the reference is null, it is converted to the string "null" (four ASCII characters n, u, l, l).
and true for newStr.equals(myStr)
Users browsing this forum: No registered users and 17 guests