toString

Whenever we are using the constructor to initalise the value without using any method we need to use toString method to print the value of the parametes. In this example we shall see what will happen if we don't use  toString() and then when we use it.


A. Without toString()


CODE OF ROTI CLASS


public class roti {
     private int age;
     private String name;
    
     roti (int age, String name){
         this.age = age;
         this.name= name;
     }
}



CODE OF SABZI CLASS


public class sabzi {
    
    public static void main (String args[]) {
       
       
    roti rotiObject = new roti(4, "Dheeraj");
System.out.println(rotiObject);   
    
}
}


OUTPUT



WHEN USING toString


public class roti {
     private int age;
     private String name;
    
     roti (int age, String name){
         this.age = age;
         this.name= name;
     }
    
     public String toString() {
         return age + " " + name;
     }
}


Sabzi CLASS

public class sabzi {
    
    public static void main (String args[]) {
       
       
    roti rotiObject = new roti(4, "Dheeraj");
System.out.printf("Details : %s", rotiObject);   
System.out.println(rotiObject);
}
}


OUTPUT




REFERENCE LINKS

  • https://www.youtube.com/watch?v=d08oJlwVgyo
  • https://www.youtube.com/watch?v=l0N6WvIVoUI
  • https://www.youtube.com/watch?v=aRxZ4jw5YPk



NOTES

  1.  As you can see I have used two types of print in actual output. This is because we get a better insight on how many ways we can print the output.




Comments

Popular posts from this blog

Finding index of an Array Element

Array Elements as Counters

Question Practice on Random Number and Loops