Java toString method

In this blog, we will see java toString method with example. Most of the developer use toString() method for program testing.

Statement of toString method

public String toString()

{

            return string_value;

}

  • Public is compulsory in this statement
  • Return type is String class

 

Let’s see example on java toString method

 

class Employee

{

                int No;

                String name;

                String address;

                Employee(int No,String name,String address)

                {

                                this.No = No;

                                this.name = name;

                                this.address = address;

                }

                public String toString()

                {

                                String str = “”;

                                str+= “No = ” + No + “\n”;

                                str+= “Name = ” + name + “\n”;

                                str+= “Address = ” + address + “\n”;

                                return str;

                }

}

class str6

{

                public static void main(String args[])

                {

                                Employee obj1 = new Employee(101,”Dipak Shah”,”Sector-12″);              

// call to constructor

                                // toString() function automatically call when we write object

                                System.out.println(obj1);           

// toString() automatically called by obj1

                }

}

 

Output:

No = 101

Name = Dipak Shah

Address = Sector-12

 

Video on tostring() method


[sbscrbr_form]

If you have any query on blog example, you can directly comment us or subscribe our website


Earn Money Online

Share and Enjoy

  • Facebook
  • Twitter
  • Delicious
  • LinkedIn
  • StumbleUpon
  • Add to favorites
  • Email
  • RSS

186total visits,1visits today


mayank

Hello, I am Maddy a Java blogger, trainer and developer

Related articles

Leave a Reply

EmailEmail
PrintPrint