Method Class | getName() Method in Java

Last Updated : 31 Mar, 2026

The getName() method of the Thread class is used to retrieve the name of a thread. It helps in identifying threads during execution, especially useful for debugging and logging in multithreaded applications.

  • Returns the name of the current thread
  • Commonly used for debugging and logging
  • Default thread names are like Thread-0, Thread-1, etc.
Java
class MyThread extends Thread {
    public void run() {
        System.out.println("Thread name: " + getName());
    }

    public static void main(String[] args) {
        MyThread t1 = new MyThread();
        t1.start();
    }
}

Output
Thread name: Thread-0

Explanation: The getName() method fetches and prints the name of the thread. If no custom name is set, it displays the default thread name.

Syntax

public final String getName()

Example: Program to check whether class contains a certain specific method.

Java
import java.lang.reflect.Method;

public class GFG {

    // Main method
    public static void main(String[] args)
    {

        String checkMethod = "method1";

        try {
            // create class object
            Class classobj = democlass.class;

            // get list of methods
            Method[] methods = classobj.getMethods();

            // get the name of every method present in the list
            for (Method method : methods) {

                String MethodName = method.getName();
                if (MethodName.equals(checkMethod)) {
                    System.out.println("Class Object Contains"
                                       + " Method whose name is "
                                       + MethodName);
                }
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}
// a simple class
class democlass {

    public int method1()
    {
        return 24;
    }

    public String method2()
    {
        return "Happy hours";
    }

    public void method3()
    {
        System.out.println("Happy hours");
    }
}

Output
Class Object Contains Method whose name is method1

Explanation: Above program uses Java Reflection (Class and Method) to retrieve all methods of a class at runtime. It then checks whether a method with the name "method1" exists and prints a message if found.

Comment