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:
Java Program to convert object of StringBuilder/StringBuffer to String
StringBuilder and StringBuffer are used to represent mutable Strings, while the String is an immutable sequence of characters. In this example, we will see how to convert StringBuilder/StringBuffer object to String.
Methods used in this program:
class JavaExample { public static void main(String[] args) { //sb1 is an object of StringBuilder class StringBuilder sb1 = new StringBuilder("BeginnersBook"); //sb2 is an object of StringBuffer class StringBuilder sb2 = new StringBuilder("Best Tutorial Website"); //Conversion using toString() method String str1 = sb1.toString(); String str2 = sb2.toString(); // Prints Strings after conversion System.out.println("StringBuilder to String: " + str1); System.out.println("StringBuffer to String: " + str2); } }
Output: