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
Joined: Jun 21, 2000
Posts: 159
posted
0
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
Joined: Oct 02, 2000
Posts: 17
posted
0
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