File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Jiris Mock 1, Q1

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

Why does this code throw an exception at runtime?
 
Thomas Paul
mister krabs
Ranch Hand
Posts: 13974
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Mona Gadkari
Ranch Hand
Posts: 64
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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....
 
Lakshmi Saradha
Ranch Hand
Posts: 170
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Vad Fogel
Ranch Hand
Posts: 504
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Following expression works as well.
public String toString()
{
if(i == 0)
return "" + null;
else
return "" + i;
}

Thanks,
PJ
 
dennis zined
Ranch Hand
Posts: 330
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

But explicitly calling "toString()" method works (jdk1.4). Wierd.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic