{Tips for Java} This doesn't give null reference? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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.

4th Mar 2017, 4:19 AM
Ram chandra Giri
Ram chandra Giri - avatar
3 Answers
+ 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.
4th Mar 2017, 1:39 PM
Ram chandra Giri
Ram chandra Giri - avatar
+ 8
How?? String and StringBuilder classes are different so I didn't get it, could you explain further.
4th Mar 2017, 5:01 AM
Saumya
Saumya - avatar
+ 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
4th Mar 2017, 7:07 AM
William La Flamme
William La Flamme - avatar