LAST UPDATED: DECEMBER 1, 2020
How to convert Java Object to String
In Java, an object can be converted into a String by using the toString()
and valueOf()
method. Both the methods belong to String class. We can convert an object into a String
irrespective of whether it is a user-defined class, StringBuffer
, StringBuilder
, etc.
Example 1:
Here, the object of the class Student
which is a user-defined class that is converted into String.
package com.studytonight;
class Student // user-defined class
{
String name;
int id;
public Student(String name, int id) {
super();
this.name = name;
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public String toString() {
return "Name: "+name+" Id: "+id;
}
}
public class StudyTonight
{
public static void main(String args[])
{
Student ob = new Student("Irfan",12); //object of user-defined class Student
System.out.println(ob +" "+ob.getClass());
String s1 = ob.toString();
System.out.println(s1+" "+s1.getClass());
}
}
Name: Irfan Id: 12 class com.studytonight.Student
Name: Irfan Id: 12 class java.lang.String
Example 2:
Here, the StringBuilder
class object is converted into String.
public class StudyTonight
{
public static void main(String args[])
{
String s = "Welcome to studytonight";
StringBuilder sb = new StringBuilder(s);
String sr = sb.toString();
System.out.println("String is: "+sr);
}
}
String is: welcome to studytonight