*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Jiris, Mock 1, Q9 Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Jiris, Mock 1, Q9" Watch "Jiris, Mock 1, Q9" New topic
Author

Jiris, Mock 1, Q9

Cathy Song
Ranch Hand

Joined: Aug 24, 2003
Posts: 270

How come line 1/2 do not throws a null pointer exception. We are calling toString() on a null object..isnt it?
Thanks.
Thomas Paul
mister krabs
Ranch Hand

Joined: May 05, 2000
Posts: 13974
You should check the source code for these kind of questions. It will help you understand the API better.
The print(Object obj) method of PrintWriter runs the String.valueOf(Object obj) method. Whta does that method do? It has one instruction:
return (obj == null) ? "null" : obj.toString();
So if the passed in Object is null, it returns the String "null" otherwise it runs the toString method of the Object.


Associate Instructor - Hofstra University
Amazon Top 750 reviewer - Blog - Unresolved References - Book Review Blog
Cathy Song
Ranch Hand

Joined: Aug 24, 2003
Posts: 270
Thanks Thomas.
The Jiris mock exam 1 was tricky :-)
Adam Altmann
Greenhorn

Joined: Nov 15, 2003
Posts: 21
What is up with the parenthesis here?
T tt = (T)t;
I've never seen that before, what does it mean?


SCJP 1.4
Simon Klaiber
Greenhorn

Joined: Nov 13, 2003
Posts: 9
(T) casts t (type Test009) to type T. this is possible, because Test009 is a subclass of T.
Simon
Mona Gadkari
Ranch Hand

Joined: Jul 28, 2003
Posts: 64
Originally posted by Simon Klaiber:
(T) casts t (type Test009) to type T. this is possible, because Test009 is a subclass of T.
Simon

hello
T tt = (T)t;
i wonder if this cast is necessary


Mona(Varijasmom)
Adam Altmann
Greenhorn

Joined: Nov 15, 2003
Posts: 21
Bah. I always forget about casting. Always. It's like I've been hypnotized to believe it doesn't exist.
Cathy Song
Ranch Hand

Joined: Aug 24, 2003
Posts: 270
Consider the following code:

Okay..I am totally confused. Why does line 1 print null, and line 2 causes expection..
Here is what I think, please correct me if I am wrong.

Thomas posted:
The print(Object obj) method of PrintWriter runs the String.valueOf(Object obj) method. Whta does that method do? It has one instruction:
return (obj == null) ? "null" : obj.toString();
So if the passed in Object is null, it returns the String "null" otherwise it runs the toString method of the Object.

So, line 1 prints null.
But in line 2 we are forcefully calling toString() for the object. Since the object is null, an expection occurs, since we are calling a method on a null object.
Thanks.
 
 
subject: Jiris, Mock 1, Q9