Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
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

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Diff b/w "this" & "toString"" Watch "Diff b/w "this" & "toString"" New topic

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();
public Test() {
System.out.println(" In test ");
int temp =;
if(temp >5) {
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.
Ajith Kallambella

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!

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: 3635
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.
Get Certified, Guaranteed!
(Now Revised for the new Pattern)

Enthuware - Best Mock Exams and Questions for Oracle Java Certifications
Quality Guaranteed - Pass or Full Refund!
I agree. Here's the link:
subject: Diff b/w "this" & "toString"
It's not a secret anymore!