Re: Newbie question
ejohnson10@charter.net wrote:
Please help me understand the ourput from this program:
[...]
class Main {
public static void main(String[] args) {
A a[]=new A[9];
You now have an array of nine references to A objects,
all of those references being null.
for(A b:a){
The loop will fetch a[0],a[1],...,a[8] in turn, assigning
each fetched value to the reference variable `b'. As it happens,
this means `b' will be null at the start of each loop.
b=new A();
Creates a new A object and makes `b' refer to it. Note that
`b' is not part of the array `a', but a free-standing variable in
its own right. By assigning a new non-null value to `b', you
have not done anything to any element of `a'.
System.out.println(b.get());
}
System.out.println(a[0].get());
Since `a[0]' has not been changed since the array was created,
it still holds a null value. So this line has the same effect as
System.out.println( ((A)null).get() );
.... which is an effect not usually desired ...
}
}
Here is the output:
99
100
101
102
103
104
105
106
Exception in thread "main" java.lang.NullPointerException
107
[...]
2nd question: I do not understand why the error comes between 106 and 107
instead of after 107. I have seen it come after 103.
The numbers are being printed to the System.out stream, but the
error messages go to System.err. It happens that both streams are
directed to the same output device, but they are not coordinated.
When you and your cousin Ignatz go through the same revolving door
at the Hotel Pretentious, either one of you might be the first to
arrive in the lobby.
--
Eric.Sosman@sun.com