• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Jiris, Mock 1, Q9

 
Cathy Song
Ranch Hand
Posts: 270
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
Posts: 13974
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Cathy Song
Ranch Hand
Posts: 270
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Thomas.
The Jiris mock exam 1 was tricky :-)
 
Adam Altmann
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is up with the parenthesis here?
T tt = (T)t;
I've never seen that before, what does it mean?
 
Simon Klaiber
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
(T) casts t (type Test009) to type T. this is possible, because Test009 is a subclass of T.
Simon
 
Mona Gadkari
Ranch Hand
Posts: 64
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Adam Altmann
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Bah. I always forget about casting. Always. It's like I've been hypnotized to believe it doesn't exist.
 
Cathy Song
Ranch Hand
Posts: 270
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic