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.

Syntax:

    public String toString();

Parameter(s):

  • It does not accept any parameter.

Return value:

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

Example:

// 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);

 }
}

Output

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



Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.