File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Value ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Value ?" Watch "Value ?" New topic

Value ?

Ranch Hand

Joined: Jul 20, 2000
Posts: 112
Hi All ,
In the code below, I thought the output would be 2,2
class Test{
int i;
public Test(int i) { this.i = i; }
public String toString() {
System.out.println(i==0) ;
if(i ==0 ) return null;
else return ""+i;
public static void main(String[ ] args) {
Test t1 = new Test(0); // i = 0
Test t2 = new Test(2); // the member variable i becomes 2
System.out.print(t2); // here it prints 2
System.out.print(" "+t1);
// here I thought would print 2 but it is null
Can anyone help ?
chetan nain
Ranch Hand

Joined: Jun 21, 2000
Posts: 159
read the code snippet :
System.out.print(t2); // here it prints 2
System.out.print(" "+t1);
" "+t1 is equivalent to
new StringBuffer().append("").append(t1).toString()
however, you have overridden the toString() method.
this will provide functionality of your method.
Test t1=new Test(0);
hence, t1.i=0;
follow up on your method.....i think you should get it
(gosh, this ones difficult to put in words)

Joined: Oct 02, 2000
Posts: 17
Hi Aruna,
The statement,
System.out.print(" "+t1);
is like concatenation of the return value with null string and printing it. So if you pass '0' to the constructor, the 'if' condition get satisfies and null value is getting printed.
Hope this clarifies
I agree. Here's the link:
subject: Value ?
jQuery in Action, 3rd edition