wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Jiris Mock 1, Q1 Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Jiris Mock 1, Q1" Watch "Jiris Mock 1, Q1" New topic
Author

Jiris Mock 1, Q1

Cathy Song
Ranch Hand

Joined: Aug 24, 2003
Posts: 270

Why does this code throw an exception at runtime?
Thomas Paul
mister krabs
Ranch Hand

Joined: May 05, 2000
Posts: 13974
Originally posted by Cathy Song:
Why does this code throw an exception at runtime?
Ultimately this null String gets passed into the write method of Writer which assumes that the String is not null. It runs the getChars method of the String which is where the exception occurs. Again, this is another case where reading through the source and following the stack trace can help you understand the API better.


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

Joined: Jul 28, 2003
Posts: 64
Originally posted by Cathy Song:

Why does this code throw an exception at runtime?

hello,
I suppose that the return type String is expected and null is returned if we return "null" it works - no runtime exception is thrown.
just make few changes in toString method and it works....
public String toString(){
if(i==0)
return "null";
else
return ""+i;
}
pls correct me am wrong....


Mona(Varijasmom)
Lakshmi Saradha
Ranch Hand

Joined: Oct 21, 2003
Posts: 170
The following code did not throw any exception for me and the output was 2 and null.
I compiled with jdk1.4
class Class2
{
int i;
public Class2(int i) { this.i = i; }
public String toString()
{
if(i == 0) return null;
else return ""+i;
}
public static void main(String[ ] args)
{
Class2 t1 = new Class2(0);
Class2 t2 = new Class2(2);
System.out.println(t2);
System.out.println(""+t1);
}
}
Any thoughts?


Thanks,<br />Lakshmi.
Vad Fogel
Ranch Hand

Joined: Aug 25, 2003
Posts: 504
This is a known JVM bug ID=4339222 (Synopsis: System.out.println throws NullPointerException when toString() returns null).
Workaround: Subclass and override toString, avoid to System.out.println.
Login to Bug Database for a full description.
PJ Pillai
Greenhorn

Joined: Nov 19, 2003
Posts: 1
Hi,
Following expression works as well.
public String toString()
{
if(i == 0)
return "" + null;
else
return "" + i;
}

Thanks,
PJ
dennis zined
Ranch Hand

Joined: Mar 07, 2003
Posts: 330

But explicitly calling "toString()" method works (jdk1.4). Wierd.


SCJP 1.4<br />SCWCD 1.4
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Jiris Mock 1, Q1