Here below is the code snippet...
String a = null;
String b = null;
String c = a+b;
The above snippet will print "nullnull" as the output.
Can somebody explain me the scenario and why this is happening this way???
Thanks in advance
Aditya, When there is no string existing for the two given variables (a and b), how come null and null are getting concatenated???
ok... though I did not get the complete meaning of the replies... May I know whats the difference between the code snippet that I pasted earlier and the one here below?
String a = "null";
String b = "null";
String c = a+b;
This also prints "nullnull" only as the output.
I strongly believe that there is something to do with the way the string variable/object are allocated the memory.
char data = null;
String a = new String(data);
The above two lines will throw null pointer. That being the case, how is "nullnull" a resulting value???!!!
I am totally lost/confused!
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 is a reference to a String object (newly created, unless the expression is a compile-time constant expression (§15.28))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. If an operand of type String is null, then the string "null" is used instead of that operand.
Sriram Sharma wrote:Manish, Thanks for your reply... Still I am not able to get a clear understanding as why this is happening so.
What does System.out.println actually do?
Prints an Object and then terminate the line. This method calls at first String.valueOf(x) to get the printed object's string value,...
What does String.valueOf(x) actually do?
Returns the string representation of the Object argument.if the argument is null, then a string equal to "null"; otherwise, the value of obj.toString() is returned.