Java Language Object Class Methods and Constructor toString() method

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

The toString() method is used to create a String representation of an object by using the object´s content. This method should be overridden when writing your class. toString() is called implicitly when an object is concatenated to a string as in "hello " + anObject.

Consider the following:

public class User {
    private String firstName;
    private String lastName;
    
    public User(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }
    
    @Override
    public String toString() {
        return firstName + " " + lastName;
    }
    
    public static void main(String[] args) {
        User user = new User("John", "Doe");
        System.out.println(user.toString()); // Prints "John Doe"
    }   
}

Here toString() from Object class is overridden in the User class to provide meaningful data regarding the object when printing it.

When using println(), the object's toString() method is implicitly called. Therefore, these statements do the same thing:

System.out.println(user); // toString() is implicitly called on `user`
System.out.println(user.toString());

If the toString() is not overridden in the above mentioned User class, System.out.println(user) may return User@659e0bfd or a similar String with almost no useful information except the class name. This will be because the call will use the toString() implementation of the base Java Object class which does not know anything about the User class's structure or business rules. If you want to change this functionality in your class, simply override the method.



Got any Java Language Question?