toString method in Java

toString is a method that is inherited by every object from the super class “Object” . This implementation can be over-ridden at the object level by defining a toString() method as shown below. If the toString() method is NOT over-ridden you get the object’s hash code

[java title=”HelloWorld.java” gutter=”true” highlight=”5″]
public class toStringMethod {

public static void main ( String[] args )
{

test1 t1 = new test1();
test2 t2 =  new test2();

System.out.println ("test1 contains " + t1);
System.out.println ("test2 contains "+ t2);
}

}

class test1
{
String fname = "Siva";

public String toString ()
{
return fname.toUpperCase();
}
}

class test2
{
String fname;
}
[/java]

Question 1 : For the following Class, override the toString() method to return the String “My first name is Bill, last name is Gates and my age is 60″

[java title=”HelloWorld.java” gutter=”true” highlight=”5″]
Class test
{
String first_name = "Bill";
String last_name = "Gates";
int age = "60";
}
[/java]

sadf

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