This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
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


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Mock Exam Errata
Bookmark "Confusing code from JQ++  " Watch "Confusing code from JQ++  " New topic
Author

Confusing code from JQ++

Dee Reavis
Greenhorn

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);
System.out.println(t2);
System.out.println(""+t1);
}
}
raimondas zemaitis
Ranch Hand

Joined: Feb 23, 2001
Posts: 104
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

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:
System.out.println(""+t1);
is changed to
System.out.println(t1);
???

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:
t1
The System.out.println method will try and call your toString method on null. Which results in a null pointer exception!
Regards,
Manfred.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Confusing code from JQ++
 
Similar Threads
toString() and null
language fundamentals
a question
null
srange null..!