CodeGym /Java Blog /Methods in Java /Java Object getClass() Method
Author
Oleksandr Miadelets
Head of Developers Team at CodeGym

Java Object getClass() Method

Published in the Methods in Java group

What is Java Object getClass() Method?

Java uses a method called getClass() provided by the class Object to get the class of any object used.

Method Header


public final Class<?> getClass()
The method does not take any parameter and is called upon the object whose class needs to be fetched.

Return Type

This method returns the class of the “object”.

Example


public class DriverClass {

	public static void main(String[] args) {
 
		Object myObject = 25;
		Class myObjectClass = myObject.getClass();
		System.out.println("Class of \"" + myObject + "\" = " + myObjectClass.getName());
		
		myObject = Float.NaN;
		myObjectClass = myObject.getClass();
		System.out.println("Class of \"" + myObject + "\" = " + myObjectClass.getName());

		myObject = Short.MIN_VALUE;
		myObjectClass = myObject.getClass();
		System.out.println("Class of \"" + myObject + "\" = " + myObjectClass.getName());
					
		myObject = 37.99999999000099990;
		myObjectClass = myObject.getClass();
		System.out.println("Class of \"" + myObject + "\" = " + myObjectClass.getName());
			
		myObject = Long.MAX_VALUE;
		myObjectClass = myObject.getClass();
		System.out.println("Class of \"" + myObject + "\" = " + myObjectClass.getName());
		
		myObject = "This is a String.";
		myObjectClass = myObject.getClass();
		System.out.println("Class of \"" + myObject + "\" = " + myObjectClass.getName());
	}
}

Output

Class of "25" = java.lang.Integer Class of "NaN" = java.lang.Float Class of "-32768" = java.lang.Short Class of "37.999999990001" = java.lang.Double Class of "9223372036854775807" = java.lang.Long Class of "This is a String." = java.lang.String
Java Object getClass() Method - 1

Conclusion

That’s how simply you can use the getClass() method of an Object class in Java. As a next learning step, define a customized class and call this method for custom objects to test. This post will always welcome you in case of any revisions or blockers. Till then, keep learning and keep growing!
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION