Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • toString() in java

    • 0
    • 1
    • 2
    • 2
    • 0
    • 0
    • 0
    • 0
    • 369
    Comment on it

    toString() method is very useful and frequently used by java developer. What is toString() ?

    As per java doc: 'toString() method returns the string representation of the object.'

    toString() method belongs to Object class, So each and every object in java has toString() method. When you print any object in java, java compiler by default return object.toString().

    example:-

    class Student{
    
            public static void main(String args[]){  
                Student s1=new Student(); 
                System.out.println(s1);//compiler prints it as  s1.toString()   
             }
            }
    

    output: Student@1fee8fc

    Out put divided in two parts one part before @ which represent Class name of object , and second part after @ represent unsigned hexadecimal code of the object.
    How to take advantages of toString() ? - Java developer can takes advantage of toString() method , By overriding the toString() method of the Object class, we can return values of the object, so we don't need to write much code.
    example:-

    class Student{  
    
             String info = "Developer" ;
    
              public String toString(){//overriding  
              return info;  
             }  
             public static void main(String args[]){ 
    
                Student s1=new Student(); 
                System.out.println(s1);//compiler prints it as  s1.toString()  
    
             }
            }       
    

    output: Developer

 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: