How to Convert Object to String in Java
How to Convert Object to String in Java
You can convert any Object to String in Java whether it is a user-defined class, StringBuilder or StringBuffer, etc. There are two methods to convert Object to String.
- Using String.valueOf(object) method
- Using toString() method
Example
In this example, we are going to convert the object of Student class into String using both the above methods. Here we have created a body of Student class. Inside the main() method, we have created an object of Student class. The toString() method converts the Object into String and the string stores into variable s. Another method String.valueOf() is used to convert Object to String. String.valueOf(), method parses the object of Student class as an argument and converts it into the String. The converted string stored in the variable s1. The first println statement prints the string s converted by toString() method. The second println statement prints the string s1 converted by String.valueOf() method.
class Student{} public class ObjectToStringExample { public static void main(String args[]) { Student stud= new Student(); //object of Student class String s=stud.toString(); //converts object to String using toString() method String s1=String.valueOf(stud); //converts object to String using String.valueOf() method System.out.println(s); System.out.println(s1); } }
Output
Student@15db9742 Student@15db9742
We get the reference id of the Student class as output.
Converting StringBuilder Object into String
StringBuilder objects are similar to String objects, except that they can be modified. It also used to create mutable string objects. StringBuilder is same as StringBuffer, but there is a slight difference. StringBuffer is synchronized while StringBuilder is not synchronized.
Example
In this example, we are going to convert StringBuilder Object into String. Here we have taken variable str of type String and initialized a string “Delhi” to it. In the next statement, we have created an object of StringBuilder class and parse a string into it as an argument. sb is an object of StringBuilder class. reverse() is the method that reverses the characters within a StringBuilder object. The toString() method converts the Object into String and stores into the variable rev. The first println statement prints the string which we have initialized. The second println statement prints the reverse string of the initialized string.
public class ObjectToStringExample1 { public static void main(String args[]) { String str="Delhi"; StringBuilder sb= new StringBuilder(str); sb.reverse(); //reverse the string String rev=sb.toString(); //converting StringBuilder Object into String System.out.println("The string is: "+str); System.out.println("Reverse string is: "+rev); } }
Output
The string is: Delhi Reverse String is: ihleD