• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Confusing code from JQ++

 
Dee Reavis
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is code from a question on language fundamentals from JQ+. I don't understand how this works. I know it does work, because I have executed it. How and why is there a call to the toString) method? Why would a 0 call to the constructor give a null pointer exception? Gurus please help!

class TestClass
{
int i;
public TestClass(int i) { this.i = i; }
public String toString()
{
if(i == 0) return null;
else return ""+i;
}
public static void main(String[ ] args)
{
TestClass t1 = new TestClass(0);
TestClass t2 = new TestClass(2);
System.out.println(t2);
System.out.println(""+t1);
}
}
 
raimondas zemaitis
Ranch Hand
Posts: 104
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
toString() method is defined in Object class. The purpose of it
is to get string representation of the object.
so when
System.out.println(t2);
is being executed, in fact toString() of TectClass object is called and appropriate value is returned.
I do not understand the second part of the question
"Why would a 0 call to the constructor
give a null pointer exception?"
 
Dee Reavis
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Raimondus for your reply.
My second question was why do I get a null pointer exception if the following line:
System.out.println(""+t1);
is changed to
System.out.println(t1);
???

 
Manfred Leonhardt
Ranch Hand
Posts: 1492
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Dee,
Your last example runs up against the special handling of null and Strings by Java. In your first example:
"" + t1
you will actually get the result "null" inside your System.out.println method after the string concatenation. The JVM replaces your null reference with "null" and then add nothing to the front of it!
In your second example:
t1
The System.out.println method will try and call your toString method on null. Which results in a null pointer exception!
Regards,
Manfred.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic