IntelliJ Java IDE
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Value ? Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Professional Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "Value ?" Watch "Value ?" New topic
Author

Value ?

Aru
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 ?
Aruna
chetan nain
Ranch Hand

Joined: Jun 21, 2000
Posts: 159
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
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
 
 
subject: Value ?
 
Threads others viewed
Unable to detect null behaviour
The way to compare HashCodes == or equals?
a highly recommended mock site: http://www.jiris.com/mock
Basic Round Up question
Strings
IntelliJ Java IDE

cast iron skillet 49er

more from paul wheaton's glorious empire of web junk: cast iron skillet diatomaceous earth rocket mass heater sepp holzer raised garden beds raising chickens lawn care CFL flea control missoula heat permaculture