How to Convert Object to String in Java

Facebooktwitterredditpinterestlinkedinmailby feather

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.

Output

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.

Output

Facebooktwitterredditpinterestlinkedinmailby feather