I was expecting line l to throw a NullPointerException.
NullPointerException would have been thrown had one tried to access any method through the object reference a, which is not initialized. e.g. a.toString() //Error - NullPointerException! The declaration A a sets the reference variable a to null (just as int i would set i to zero). It is then printed out in System.out.println()
Hi Giselle. Let me see if I'm understanding my SCJP studies ;-). a is an instance variable, so it'll be initialized by null. since you're doing :
you're concatenating a string representation with the value of the instance variable, which is null (not pointing to anything), so the null value gets promoted to a String (the toString method is not invoked). So it prints: a = null please correct me if I'm wrong.
I'm not going to be a Rock Star. I'm going to be a LEGEND! --Freddie Mercury
The following is an excerpt from JLS(sect. 22.214.171.124) regarding String concatenation: "If the reference is null, it is converted to the string "null" (four ASCII characters n, u, l, l). Otherwise, the conversion is performed as if by an invocation of the toString method of the referenced object with no arguments..."
Joined: Apr 20, 2003
Thanks Alton, that�s the info I was looking for. I thought toString() was called no matter what... Andres, you are right. I was questioning the fact that toString is part of an object not yet created, so how could it be called ? [ June 03, 2003: Message edited by: Giselle Dazzi ]
I was a little confused about that myself, because you can pass a null reference to System.out.println and it's happy, yet if you try this, you get NullPointerException. String a=null; StringBuffer sbuffer = new StringBuffer(a); I guess in this case, toString() is being called by StringBuffer. Although: sbuffer.append(a); // Fine, prints "null". Forget about using null literals: sbuffer.append(null); // No good, because of overloaded methods, so you get a compile error of "ambiguous". Hope this helps more than straying from the topic at hand. [ June 03, 2003: Message edited by: Brian Joseph ]