class Test {
public static void main() {
String s1 = null + null; //shows compile time error
String s1 = null;
String s2 = s1 + null; //runs fine
}
}
Can anybody please explain the reason for this behavior?
This code:
tries to perform addition operation on two while here:
You assigned
|
|||||||||||||||||||||
|
The This is defined in the Java Language Specification
In
the operands have the In
|
||||
|
In below case, you are performing operation on two
And in this one you are performing concatenation of
And another interesting case is,
That will be resulted in "nullnull" string as you are casting |
||||
|
From Javadoc:
Thus, at least the left operand must not be null since |
|||||||||||||||||||||
|
Basically this because you are dealing with literals, and because of that, the COMPILER is trying to perform an operation on those literal values. It's happening at compile time, and there's nothing to do with two null values. The compiler error you are getting is the equivalent of an exception -- the compiler doesn't know what to do with it, so it errors out and gives the types an explanation saying it doesn't work. |
||||
|
concat
would be invoked with a null. – Hot Licks 19 hours agos1
is declared twice. Maybe use different scopes by putting the two examples in different blocks? – Arlaud Pierre 4 hours ago