Thursday, 17 April 2014

String representation of Undefined (class) types :

The toString() method

It is a good programming practice to provide the toString method for the class so that whenever the String representation of the object of the class is required, Java automatically looks foe the toString methods inside the class & invokes it.
The toString method specifies the conversion policy for the information of the class into String.
Take a look at this example :

//program without toString() class Record
{
private String name;
private int age;
private float basic;
Record(){}
Record(String name,int age , double basic)
{
this.name = name;
this.age = age;
this.basic = (float)basic;
}
void print()
{
System.out.printf(“\n %-15s %2d %8.2f”,name,age,basic);
}
}
class Main
{
public static void main(String arg[])
{
Record r1,r2;
r1=new Record(“vivek warde”,20,3800.75);
r2=new Record(“kapil”,21,3535.55);
r1.print();
r2.print();
System.out.println(“\n”);
System.out.println(“\n r1 : “+r1);
System.out.println(“\n r2 : “+r2);
}
}

///////////////////////////// v/s ////////////////////////
 
//program with toString()

class Record
{
private String name;
private int age;
private float basic;
Record(){}
Record(String name,int age , double basic)
{
this.name = name;
this.age = age;
this.basic = (float)basic;
}
void print()
{
System.out.printf(“\n %-15s %2d %8.2f”,name,age,basic);
}
public String toString()
{
//      return name+” “+age+” “+basic;
String s = String.format(“%-15s %2d %8.2f”,name,age,basic);
return s;
}
}
class Main
{
public static void main(String arg[])
{
Record r1,r2;
r1=new Record(“vivek warde”,20,3800.75);
r2=new Record(“kapil”,21,3535.55);
r1.print();
r2.print();
System.out.println(“\n”);
System.out.println(“\n r1 : “+r1);
System.out.println(“\n r2 : “+r2);
}
}
//Just copy paste the code in ur compiler , & u can see the outputs

No comments:

Post a Comment