Thursday, October 2, 2025
HomeLanguagesJavaClass toString() method in Java with Examples

Class toString() method in Java with Examples

The toString() method of java.lang.Class class is used to convert the instance of this Class to a string representation. This method returns the formed string representation.

Syntax:

public String toString()

Parameter: This method does not accept any parameter.

Return Value: This method returns the String representation of this object.

Below programs demonstrate the toString() method.

Example 1:




// Java program to demonstrate toString() method
  
public class Test {
    public static void main(String[] args)
        throws ClassNotFoundException
    {
        // returns the Class object for the class
        // with the specified name
        Class c1 = Class.forName("java.lang.String");
  
        System.out.print("Class represented by c1: ");
  
        // toString method on c1
        System.out.println(c1.toString());
    }
}


Output:

Class represented by c1: class java.lang.String

Example 2:




// Java program to demonstrate toString() method
  
public class Test {
    public static void main(String[] args)
        throws ClassNotFoundException
    {
        // returns the Class object for the class
        // with the specified name
        Class c2 = int.class;
        Class c3 = void.class;
  
        System.out.print("Class represented by c2: ");
  
        // toString method on c2
        System.out.println(c2.toString());
  
        System.out.print("Class represented by c3: ");
  
        // toString method on c3
        System.out.println(c3.toString());
    }
}


Output:

Class represented by c2: int
Class represented by c3: void

Reference: https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html#toString–

Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32331 POSTS0 COMMENTS
Milvus
85 POSTS0 COMMENTS
Nango Kala
6703 POSTS0 COMMENTS
Nicole Veronica
11867 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11927 POSTS0 COMMENTS
Shaida Kate Naidoo
6818 POSTS0 COMMENTS
Ted Musemwa
7080 POSTS0 COMMENTS
Thapelo Manthata
6775 POSTS0 COMMENTS
Umr Jansen
6776 POSTS0 COMMENTS