In this guide, we will learn how to convert Object to String in Java. We will also see program for StringBuffer and StringBuilder object to String conversion.
Java Program to convert an object of a class to String
Here, we are using toString() and valueOf() methods to convert the object of Student class to a String.
class Student {
// A Student class
}
class JavaExample {
public static void main(String[] args)
{
// Object of Student class
Student obj = new Student();
// converting the object of Student class to String
// using toString() method
String str1 = obj.toString();
// converting object of Student class to String
// using valueOf() method
String str2 = String.valueOf(obj);
System.out.println("Conversion using toString() Method: "+str1);
System.out.println("Conversion using valueOf() Method: "+str2);
}
}
Output: