public class Test{ static int total = 10; public static void main (String args[]) { Test t = new Test(); System.out.println(t.toString()); } public Test() { System.out.println(" In test "); System.out.println(this); int temp = this.total; if(temp >5) { System.out.println(temp); } } } Hi! The out for "System.out.println(this);" is same as the output for "System.out.println(t.toString())". Can Somebody please explain the difference b/t the two. Thanks Vineet
Ajith Kallambella
Sheriff
Joined: Mar 17, 2000
Posts: 5782
posted
0
Since your class 'Test' didnot override the toString() method, what you are observing is the default implementation of the toString() method defined in the Object class. Here is what the Object.toString() does
The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:
Any non-string argument that you pass to System.out.println() is converted to string representation. In order to convert the object to its string representation, the toString() method is called. Here, 'this' is an object of class Test and since Test doesnot override the toString() method, the default string representation is printed. It is important not to get confused between 'this' and toString. 'this' is an implied pointer to the current instance of the class whereas toString() is a method defined in the Object class. Hope that helps! Ajith
Open Group Certified Distinguished IT Architect. Open Group Certified Master IT Architect. Sun Certified Architect (SCEA).
Paul Anilprem
Enthuware Software Support
Ranch Hand
Joined: Sep 23, 2000
Posts: 2912
posted
0
When you call System.out.println(obj); it prints either null (if obj is null) or the string returned by calling toString() on obj. So in this case there is no difference. -Paul. ------------------ Get Certified, Guaranteed! (Now Revised for the new Pattern) www.enthuware.com/jqplus