Forums Register Login

calling toString method

+Pie Number of slices to send: Send
public class ExpImpl1 extends Object
{
public static void main(String argsd[])
{
ExpImpl1 exp=new ExpImpl1();
System.out.println("in main "+ exp);
}
}

I am trying to print ExpImpl1 object but it is calling Object toString() method.Can you please let me know how it is calling Object toString() method.

Thanks & Regards
Srujana
+Pie Number of slices to send: Send
Your class extends Object and it was not necessary to write that. Also you didn't override toString() method in you class (ExpImpl1) and therefore toString() method from Object is called. When you implement your own toString() method (public String toString()) in your class (ExpImpl1) you will override Object toString() method and your implementation will be called when you call toString() on ExpImpl1.

http://www.javabeginner.com/java-tostring.htm
+Pie Number of slices to send: Send
Your class doesn't have its own toString() method, so it inherits the toString() method of class Object.

Inheritance is a basic object-oriented programming concept. See the Inheritance lesson in Sun's Java Tutorial for more information.
+Pie Number of slices to send: Send
Yes you are correct.It is inheriting Objects toString() method so it is calling. what my doubt is,we are not explicitly calling Object's toString() method.How it is calling toString() method.
+Pie Number of slices to send: Send
When you use primitive data types such as int,float, double etc., in your System.out.println() statement the value of the data is printed. But when you use an object reference in the System.out.println() statement the object toString() method is called and output of the toString() method(String) is printed in the console.
[ February 19, 2008: Message edited by: Arivazhagan Arutchelvam ]
+Pie Number of slices to send: Send
When you use the + operator to concatenate a string and an object, like this: "in main " + exp
then the compiler translates this behind the scenes to something like this:

StringBuffer sb = new StringBuffer("in main ");
sb.append(String.valueOf(exp));
sb.toString();

Note that String.valueOf(exp) will call toString() if exp is not null.
what if we put solar panels on top of the semi truck trailer? That could power this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 2939 times.
Similar Threads
q from jiris.com
How do I covert on object into string
constructor question
wrapper class?
About String == String, please help.
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 04:49:32.