Java toString() method

    toString() method

    Using toString() method you can easily represent any object as a string. It will provide you with the object’s string representation. This method will be internally invoked by the JVM whenever you print any object. You can override the toString() method to get the desired output.

    If we override the toString() method of any object class, the object value can be returned that will save you writing long lines of code.

    Example without toString() method-

    class Simple{  
    
     int rollno;  
     String name;   
     Simple(int rollno, String name){  
     this.rollno=rollno;  
     this.name=name;  
    
     }  
    
      
     public static void main(String args[]){  
       Simple s1=new Simple(101,"Raj");  
       Simple s2=new Simple(102,"Vijay");  
        
       System.out.println(s1); 
    
       System.out.println(s2);//compiler writes here s2.toString()  
     }  
    }  

    Output-

    Java tostring method

    Example with toString() method-

    class Simple{  
    
     int rollno;  
     String name;   
    
      
    
     Simple(int rollno, String name){  
       this.rollno=rollno;  
       this.name=name;  
     }  
    
     public String toString(){
       return rollno+" "+name;
     }
    
      
    
     public static void main(String args[]){  
    
       Simple s1=new Simple(101,"Raj");  
       Simple s2=new Simple(102,"Vijay");     
    
       System.out.println(s1); 
       System.out.println(s2);
     }  
    
    }  

    Output-