+ 23
{Tips for Java} This doesn't give null reference?
Look at this code this doesn't give null reference: String s = null; System.out.println(s + "hello"); Instead output: nullhello This is because all the + operations are automatically compiled to StringBuilder.
3 Antworten
+ 18
@Saumya these paragraph are from JLS which will explain it:
1.If only one operand expression is of type String, then string conversion is performed on the other operand to produce a string at run time.
The result of string concatenation is a reference to a String object that is the concatenation of the two operand strings. The characters of the left-hand operand precede the characters of the right-hand operand in the newly created string.
2.Now only reference values need to be considered:
If the reference is null, it is converted to the string "null" (four ASCII characters n, u, l, l).
Otherwise, the conversion is performed as if by an invocation of the toString method of the referenced object with no arguments; but if the result of invoking the toString method is null, then the string "null" is used instead.
+ 8
How?? String and StringBuilder classes are different so I didn't get it, could you explain further.
+ 5
realistically you shouldn't define a string with null anyways, String s =""; would be the better method or declare the variable without assignment like String s; or declare it in the instance when first assigned. Anyone of those methods > assigning null