Page 1 of 1

About Question enthuware.ocajp.i.v7.2.1382 :

Posted: Thu Jul 02, 2015 6:44 pm
by evafang2008
For this question, int score2[] = null, but score.length will not compile because of NullPointerException. Compare to (args.length = 0) in main method if no arguments, it is different. Does args.length is a special case? Except args case, all other normal object, if they are equal to null, the object.length does not work. Is it right?
Thank you.

Updated:

Oh, String [] is defined as [0] by default? If it is defined as [0] by default, I see the difference.

Re: About Question enthuware.ocajp.i.v7.2.1382 :

Posted: Thu Jul 02, 2015 7:48 pm
by admin
evafang2008 wrote:For this question, int score2[] = null, but score.length will not compile because of NullPointerException.
This is a very wrong thing to say. Exceptions are thrown an run time, not at compile time. So your statement, " int score2[] = null, but score.length will not compile because of NullPointerException." makes no sense.
int score2[] = null; will certainly compile fine. score2.length will throw a NPE at run time.
Compare to (args.length = 0) in main method if no arguments, it is different. Does args.length is a special case? Except args case, all other normal object, if they are equal to null, the object.length does not work. Is it right?
Thank you.
No, args is not a special case, args.length does not throw NPE because the JVM initializes args to a String array of length 0 if no arguments are passed. So args is not null (unlike above).
Updated:

Oh, String [] is defined as [0] by default? If it is defined as [0] by default, I see the difference.
Not sure what you mean. args is a method parameter. It is passed to the main method by the JVM. The JVM initializes it to String[] of length 0 if no arguments were specified on the command line.
If you define String[] score = null; then score is null. It is not same as String[] of length 0.

I would suggest you to write some test programs to make sure you understand this concept.

HTH,
Paul.