Java Program to Convert Object to String
The first byte needs to be converted into an object byte which can easily be dealt with to convert to strings. Convert Object to String in java using toString() method of Object class or String.valueOf(object) method. Since there are mainly two types of class in java, i.e. user-defined class and predefined class such as StringBuilder or StringBuffer of whose objects can be converted into the string.
Approaches:
- Converting User-defined class object to String
- Converting StringBuilder(Predefined class) object to String
Method 1: Using toString() method or String.valueOf(object_name) method.
Java
class GFG {
public static void main(String[] args)
{
Helper help = new Helper();
String s1 = help.toString();
String s2 = String.valueOf(help);
System.out.println(
"Converted string object || using toString() Method: " + s1);
System.out.println(
"Converted string object || using valueOf() Method: " + s2);
}
}
class Helper {
}
|
Output
Converted string object || using toString() Method: Helper@214c265e
Converted string object || using valueOf() Method: Helper@214c265e
Method 2: Converting StringBuilder(Predefined class) object to String.
The StringBuilder in Java represents a mutable sequence of characters. Since the String Class in Java creates an immutable sequence of characters, the StringBuilder class provides an alternative to String Class, as it creates a mutable sequence of characters.
Class Hierarchy:
java.lang.Object
↳ java.lang
↳ Class StringBuilder
Example:
Java
class GFG {
public static void main(String[] args)
{
String s = "Geeks For Geeks" ;
StringBuilder sb = new StringBuilder(s);
String objToString = sb.toString();
System.out.println( "String: " + s);
System.out.println( "Converted String: "
+ objToString);
}
}
|
Output
String: Geeks For Geeks
Converted String: Geeks For Geeks
Last Updated :
08 Dec, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...