aspose file tools*
The moose likes Beginning Java and the fly likes calling toString method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "calling toString method" Watch "calling toString method" New topic
Author

calling toString method

srujana maredugu
Greenhorn

Joined: Jan 10, 2008
Posts: 8
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
Amir Alagic
Ranch Hand

Joined: Mar 21, 2006
Posts: 65
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
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14435
    
  23

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.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
srujana maredugu
Greenhorn

Joined: Jan 10, 2008
Posts: 8
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.
Arivazhagan Arutchelvam
Greenhorn

Joined: Feb 19, 2008
Posts: 10
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 ]
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14435
    
  23

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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: calling toString method