Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
Node is saved as draft in My Content >> Draft
  • How to use 'toString' method ?

    • 0
    • 1
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 364
    Comment on it

    toString(); This method is used to convert any object in Java to String format. If we want to get object, Java Compiler automatically invokes 'toSting()' . Although we can override this method if required.

    Lets Consider following example if we don't use this method.

     

    package com.tech;
    public class Employee {
    
    	private int Salary;
    	private String name;
    
    	public Employee(String name,int Salary) {
    		this.name=name;
    		this.Salary=Salary;
    	}
    	public static void main(String[] args)
            {
    		Employee e1=new Employee("Ramesh",45000);
    		Employee e2=new Employee("Gaurav",25000);
    		System.out.println(e1); // compiler writes here e1.toString()   
    		System.out.println(e2); //// compiler writes here e2.toString()
    
    	}
    
    }

    The Output we obtain is :

    com.tech.Employee@20eb607d
    com.tech.Employee@3d0bbf6d

    But If we use toString() or Override this method like :

    package com.tech;
    
    public class Employee {
    
    	private int Salary;
    	private String name;
    
    	public Employee(String name,int Salary) {
    		this.name=name;
    		this.Salary=Salary;
    	}
    	public String toString(){return name+" "+Salary;} // over ride the toString()
    
    	public static void main(String[] args) {
    		Employee e1=new Employee("Ramesh",45000);
    		Employee e2=new Employee("Gaurav",25000);
    		System.out.println(e1);
    		System.out.println(e2);
    
    	}
    
    }
    

    Now we obtain the Output as:

    Ramesh 45000
    Gaurav 25000
    

     

    toString Method Java

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: