BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Java Object to String Conversion

Last Updated: November 13, 2022 by Chaitanya Singh | Filed Under: java

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: