Could somebody explains why "null" string is put in result of following line (why not an exception?) :
public class Test{
int[] ia = new int[1];
Object oA[] = new Object[1];
boolean bool;
public static void main(String args[]){
Test test = new Test();
System.out.println(test.ia[0] + " " + test.oA[0]+" "+test.bool);
}
}
Why not NullPointerException?
Moderator: admin
-
- Posts: 2
- Joined: Wed May 03, 2017 8:25 pm
- Contact:
-
- Site Admin
- Posts: 10388
- Joined: Fri Sep 10, 2010 9:26 pm
- Contact:
Re: Why not NullPointerException?
In general, "accessing" a null reference always causes a NPE to be thrown. And access basically means the use of dot operator on a reference.
But the + operator is a special case. It does not throw a NullPointerException during string concatenation, because it is overloaded in a way that when one operand is a String and another is null reference, then it appends the string "null" instead of calling toString on the null reference. You can think of it as if the + operator checks whether the reference is null or not and if it is null, it appends "null" and if it is not null then it appends the string returned by calling toString on that reference.
This is given here: https://docs.oracle.com/javase/specs/jl ... jls-5.1.11
HTH,
Paul.
But the + operator is a special case. It does not throw a NullPointerException during string concatenation, because it is overloaded in a way that when one operand is a String and another is null reference, then it appends the string "null" instead of calling toString on the null reference. You can think of it as if the + operator checks whether the reference is null or not and if it is null, it appends "null" and if it is not null then it appends the string returned by calling toString on that reference.
This is given here: https://docs.oracle.com/javase/specs/jl ... jls-5.1.11
HTH,
Paul.
Who is online
Users browsing this forum: No registered users and 27 guests