Ad

How to use toString() method

toString() Method in object class:


Object class contains toString method that may be overridden by other classes.
If you pass an object to print*method, toString method is called implicitly.
•When you override toString method, it must return a string, that usually contain fields name with their values.
•Its good practice to override this method

Syntax and with Example:


//Student class

/**
 *
 * @author usman
 */
public class Student {
      int id;
     String name;

    @Override
    public String toString() {
        return "Student{" + "id=" + id + ", name=" + name + '}';
    }
    
    
}

//TestClass


/**
 *
 * @author usman
 */
public class TestClass {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Student student = new Student();
        student.id = 10;
        student.name = "Hashmi";
        System.out.println(student);
        System.out.println(student.toString());
    }
    
}


Post a Comment

0 Comments