object.toString();

July 5, 2007 at 3:20 pm Leave a comment

For people who dont know ,the toString() is one of the methods that are available for all objects in java .

Have you ever used this function??

If yes for what you have used this function??

Hmmm Where did i use this function??

In date functions to convert date into string ,when you want to assign an object to a string or if you want to print something which is not a string.Basically when you have a sop(System.out.println())it can print only string values and by default it calls the toString() method for all objects.
Calling a toString() method to convert a date to string is ok and even to convert integer or a boolean to string is ok because in both cases the value of the object is returned as a string without any damage .

What happens when you call it for a user-created-class object.?
When you do this you would get an output like this

classname@a47e0

And do we get any idea about the object and its values???
No , we just know that it is not null.
I had used this to check if the value is not null . I was wondering why we have this function for all objects until i knew about the “overridding toString()”.

Every class is supposed to override the toString() method
Overriding toString() is when you want to be able to read something meaningful about the objects of your class. Code can call toString() on your object when it wants to read useful details about your object.

if you have a class name

class Biodata
{
String name;
String age;
// all functions goes here

public String toString()
{
return “this is biodata class and my name is “+name+ my age is “+age;
}
}

Now if you try to print the object of this class you will get a detailed idea of this object rather than “@&%$%^!###” .
I guess it is one rule that should be followed.Every class should override toString() method.

Powered by ScribeFire.

Entry filed under: life. Tags: .

Dont Quit Official announcement of the new seven wonders of the world

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Trackback this post  |  Subscribe to the comments via RSS Feed


July 2007
S M T W T F S
« Jun   Aug »
1234567
891011121314
15161718192021
22232425262728
293031  

Blog Stats

  • 225,814 hits

Java software

Flickr Photos

Morning Silence

Puffy

Emerald Damselfly ♀

More Photos

%d bloggers like this: