Meaningless Drivel is fun!*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Diff b/w 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 "Diff b/w "this" & "toString"" Watch "Diff b/w "this" & "toString"" New topic
Author

Diff b/w "this" & "toString"

Vineet Sharma
Ranch Hand

Joined: Dec 30, 2000
Posts: 51
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
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: 3254
    
    2
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


Enthuware - Best Mock Exams and Questions for Oracle/Sun Java Certifications
Quality Guaranteed - Pass or Full Refund!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Diff b/w "this" & "toString"
 
Similar Threads
what does this mean here?
can we able to refer a static variable using an object
John Hunt M.E Q17
inner class
Fill the code