Menu

How to Convert Object to String in Java?

How to convert Java Object to String

In Java, an object can be converted into a String by using the toString() and valueOf() method. Both the methods belong to String class. We can convert an object into a String irrespective of whether it is a user-defined class, StringBuffer, StringBuilder, etc.

Example 1:

Here, the object of the class Student which is a user-defined class that is converted into String.

package com.hclguvi;

class Student   // user-defined class
{
    String name;
    int id;
    
    public Student(String name, int id) {
        super();
        this.name = name;
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    @Override
    public String toString() {
        return "Name: "+name+" Id: "+id;
    }
}
public class hclguvi
{  
    public static void main(String args[])
    {  
        Student ob = new Student("Irfan",12); //object of user-defined class Student
        System.out.println(ob +" "+ob.getClass());
        String s1 = ob.toString();  
        System.out.println(s1+" "+s1.getClass());    
    }
}

Output:

Name: Irfan Id: 12 class com.hclguvi. Student Name: Irfan Id: 12 class java.lang.String

Example 2:

Here, the StringBuilder class object is converted into String.

public class StudyTonight
{  
    public static void main(String args[])
    {  
        String s = "Welcome to hclguvi";  
        StringBuilder sb = new StringBuilder(s);
        String sr = sb.toString();
        System.out.println("String is: "+sr);
    }
}

Output:

String is: welcome to hclguvi