Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
The moose likes Mock Exam Errata and the fly likes Confusing code from JQ++  Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Mock Exam Errata
Bookmark "Confusing code from JQ++  " Watch "Confusing code from JQ++  " New topic

Confusing code from JQ++

Dee Reavis

Joined: Dec 13, 2000
Posts: 8
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);
raimondas zemaitis
Ranch Hand

Joined: Feb 23, 2001
Posts: 104
toString() method is defined in Object class. The purpose of it
is to get string representation of the object.
so when
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

Joined: Dec 13, 2000
Posts: 8
Thank you Raimondus for your reply.
My second question was why do I get a null pointer exception if the following line:
is changed to

Manfred Leonhardt
Ranch Hand

Joined: Jan 09, 2001
Posts: 1492
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:
The System.out.println method will try and call your toString method on null. Which results in a null pointer exception!
I agree. Here's the link:
subject: Confusing code from JQ++