Edi
Edi

Reputation: 73

return value of this, further explanation

I wrote the following code:

class samplethis {

    int a = 6;
    int b = 7;
    String c = "i am";

    public void sample() {
        System.out.println(this);
    }
}

public class thiss {

    public static void main(String[] args) {
        samplethis cal = new samplethis();
        cal.sample();// return samplethis@1718c21
    }
}

Does anyone know why it returns samplethis@1718c21?

Upvotes: 0

Views: 72

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1502446

Your code doesn't return anything - it prints the result of calling this.toString().

Unless you've overridden Object.toString(), you get the default implementation:

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:

getClass().getName() + '@' + Integer.toHexString(hashCode())

Having the hash code there makes it easier to spot probably equal references to the same object. If you write:

Foo foo1 = getFooFromSomewhere();
Foo foo2 = getFooFromSomewhere();
System.out.println("foo1 = " + foo1);
System.out.println("foo2 = " + foo2);

and the results are the same, then foo1 and foo2 probably refer to the same object. It's not guaranteed, but it's at least a good indicator - and this string form is really only useful for diagnostics anyway.

If you want to make your code print something more useful, you need to override toString, e.g. (in samplethis)

@Override
public String toString() {
    return String.format("samplethis {a=%d; b=%d; c=%s}", a, b, c);
}

Upvotes: 7

Related Questions