Home » Java programming language

Java Class class toString() method with example

Class class toString() method: Here, we are going to learn about the toString() method of Class class with its syntax and example.
Submitted by Preeti Jain, on November 22, 2019

Class class toString() method

  • toString() method is available in java.lang package.
  • toString() method is used to represent the string of an object or in other words, we can say this method is used to convert an object to a string.
  • toString() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
  • toString() method does not throw an exception at the time of conversion an object to a string.


    public String toString();


  • It does not accept any parameter.

Return value:

The return type of this method is String, it returns a string representation of an object.


// Java program to demonstrate the example 
// of String toString() method of Class 

public class ToStringOfClass {
 public static void main(String[] args) {
  // Create and Return StringBuilder class
  StringBuilder s1 = new StringBuilder();
  Class cl1 = s1.getClass();

  // Create and Return String class
  String s2 = new String();
  Class cl2 = s2.getClass();

  // It returns string representation of an 
  // object of class StringBuilder and String
  String str1 = cl1.toString();
  String str2 = cl2.toString();

  System.out.println("cl1.toString(): " + str1);
  System.out.println("cl2.toString(): " + str2);



cl1.toString(): class java.lang.StringBuilder
cl2.toString(): class java.lang.String


Comments and Discussions



Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© some rights reserved.