• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Value ?

 
Aru
Ranch Hand
Posts: 112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ?
Aruna
 
chetan nain
Ranch Hand
Posts: 159
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Aruna,
read the code snippet :
System.out.print(t2); // here it prints 2
System.out.print(" "+t1);
carefully.
" "+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)
thus,
 
sankar
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic