using this as String reference

Hi friends,

Can anybody help find my mistake in the following code.?

_

public class ThisCheck

{ public ThisCheck()

{System.out.printf("%s",this);

}

public String str()

{return "shiva";

}

public static void main(String a[])

{ ThisCheck the=new ThisCheck();

}

}

__

the output I am expecting is Shiva.

But the output Iam getting is the address of the object ThisCheck

as ThisCheck@7d772e

What's going wrong?

I appreciate ur help.

[550 byte] By [shiva7a] at [2007-10-3 4:15:07]
# 1

Where do you think you're invoking the "str" method?

When you invoke printf, it is implicitly invoking the toString method, which you haven't supplied, so it's using the original implementation of that method.

What made you think it would magically invoke your homemade "str" method?

warnerjaa at 2007-7-14 22:16:34 > top of Java-index,Java Essentials,New To Java...
# 2

Try:public class ThisCheck {

public ThisCheck() {

System.out.printf("%s", this);

}

public String toString() {

return "shiva";

}

public static void main(String a[]) {

ThisCheck the = new ThisCheck();

}

}

The %s flag in printf() looks for the toString() method of the corresponding

argument. (Details here: http://java.sun.com/j2se/1.5.0/docs/api/java/util/Formatter.html)

When you post it's a good idea to use the Formatting tips

http://forum.java.sun.com/help.jspa?sec=formatting

Basically it means putting [code] at the start of your code and [/code] at

the end.

pbrockway2a at 2007-7-14 22:16:34 > top of Java-index,Java Essentials,New To Java...
# 3
> I appreciate ur help.Are you sure you do? Common sense would lead me to believe you would actually say something like "Thank you" after receiving the help.
warnerjaa at 2007-7-14 22:16:34 > top of Java-index,Java Essentials,New To Java...
# 4
Thank you for your help sir.I didn't know that it should strictly be toString() method.I thought any method name that returns a string .thanks again.
7shivaa at 2007-7-14 22:16:34 > top of Java-index,Java Essentials,New To Java...
# 5

> I didn't know that it should strictly be toString()

> method.

> I thought any method name that returns a string .

You can certainly provide any method you want that returns a String, and use it however you want. But if you're doing this: System.out.println(myObject);

then how can it know which of your methods it should call? The reason you use toString here is because println calls toString.

jverda at 2007-7-14 22:16:34 > top of Java-index,Java Essentials,New To Java...