Convert Object to String in Java

Converting an object to a string in Java is a fundamental operation often required in programming, especially for logging, concatenation, or processing data. Java provides several ways to achieve this. In this blog post, we'll explore different methods to convert an object to a string, along with examples and their outputs. 

Method 1: Using toString() Method 

Every class in Java inherits from the Object class, which includes the toString() method. You can override this method in your class to provide a meaningful string representation. 

Code Example

public class Fruit {
    private String name;
    private int quantity;

    public Fruit(String name, int quantity) {
        this.name = name;
        this.quantity = quantity;
    }

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

    public static void main(String[] args) {
        Fruit apple = new Fruit("Apple", 10);
        String str = apple.toString();
        System.out.println(str); // Output: Fruit{name='Apple', quantity=10}
    }
}

Output:

Fruit{name='Apple', quantity=10}

Method 2: Using String.valueOf() 

The String.valueOf() method can be used to convert any object to a string. If the object is null, it returns the string "null". 

Code Example

public class Fruit {
    private String name;
    private int quantity;

    // Constructors, getters, setters

    public static void main(String[] args) {
        Fruit apple = new Fruit("Apple", 10);
        String str = String.valueOf(apple); // Calls apple.toString() internally
        System.out.println(str); // Output: Fruit@hashcode (or custom toString() output)
    }
}

Output:

Fruit{name='Apple', quantity=10}

Method 3: Using + Operator with an Empty String 

Concatenating an object with an empty string implicitly calls the object's toString() method. 

Code Example

public class Fruit {
    private String name;
    private int quantity;

    // Constructors, getters, setters

    public static void main(String[] args) {
        Fruit apple = new Fruit("Apple", 10);
        String str = apple + ""; // Implicitly calls toString()
        System.out.println(str); // Output: Fruit@hashcode (or custom toString() output)
    }
}

Output:

Fruit{name='Apple', quantity=10}

Comments