Java.lang Package Classes

Java Class - isPrimitive() Method



The java.lang.Class.isPrimitive() method is used to determine if the specified Class object represents a primitive type. There are nine predefined Class objects to represent the eight primitive types and void. These are created by the Java Virtual Machine, and have the same names as the primitive types that they represent, namely boolean, byte, char, short, int, long, float, and double.

These objects may only be accessed via the following public static final variables, and are the only Class objects for which this method returns true.

Syntax

public boolean isPrimitive()

Parameters

No parameter is required.

Return Value

Returns true if and only if this class represents a primitive type.

Exception

NA.

Example:

In the example below, the java.lang.Class.isPrimitive() method is used to check if the given class object is a primitive type or not.

import java.lang.*;

public class MyClass {
  public static void main(String[] args) {
    //creating class object associated 
    //with this class
    MyClass x = new MyClass();
    Class xcls = x.getClass();

    //creating class object associated 
    //with float class
    float y = 10.5f;
    Class ycls = float.class;

    //check if xcls is a primitive class
    Boolean result1 = xcls.isPrimitive();
    System.out.println("Is x primitive type?: " + result1);
    
    //check if ycls is a primitive class
    Boolean result2 = ycls.isPrimitive();
    System.out.println("Is y primitive type?: " + result2);
  }
}

The output of the above code will be:

Is x primitive type?: false
Is y primitive type?: true

❮ Java.lang - Class