Perfect Cube in Java with Explanation, Definition, Examples, and Program

A Perfect Cube is a number that can be expressed as the cube of an integer. This guide explains the concept with examples and provides a simple Java program to check if a number is a perfect cube.

Perfect Cube in Java

A Perfect Cube is a number that can be represented as the cube of an integer. In simple terms, a number N is a Perfect Cube if:

N = a³, for some integer a

For example, 8 = 2³ and 27 = 3³, so both are perfect cubes.


Examples

Example 1: 27

Example 2: 30


Java Program to Check Perfect Cube


public class PerfectCube {

    // Function to check if a number is a perfect cube
    static boolean isPerfectCube(int num) {
        int cubeRoot = (int) Math.round(Math.cbrt(num));
        return cubeRoot * cubeRoot * cubeRoot == num;
    }

    public static void main(String[] args) {
        int num = 27;

        if (isPerfectCube(num)) {
            System.out.println(num + " is a Perfect Cube");
        } else {
            System.out.println(num + " is NOT a Perfect Cube");
        }
    }
}

How the Program Works

We use Math.cbrt() to calculate the cube root of the number. Then we round it to the nearest integer and check if its cube equals the original number.


Practice Challenges

  1. Print all perfect cubes between 1 and 1000.
  2. Write a program to find the cube root of a number without using inbuilt functions.
  3. Given an array of numbers, print only those which are perfect cubes.