Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to find the cube of a number.

Java Code Example — Basic Programs

ADVERTISEMENT

Java Program to find the cube of a number.

Objective

Write a Java program to calculate the cube of a number.

Algorithm / Approach

  1. Prompt the user to enter an integer.
  2. Calculate the cube by multiplying the number by itself three times (x * x * x).
  3. Store the result and print it.
Test.java
import java.util.Scanner;
class Test {
 public static void main(String[] a)
 {
  Scanner s=new Scanner(System.in);
  System.out.print("Enter Num: ");
  int x = s.nextInt();
  int y = x*x*x;
  System.out.print("Cube = "+y);
 }
}

Expected Output

Enter Num: 5
Cube = 125

Explanation of the Program

  • The user inputs a number which is stored in variable x.
  • The cube is calculated by multiplying the number by itself three times: x * x * x.
  • The result is stored in variable y and printed to the user.

Complexity

Time Complexity O(1)
Space Complexity O(1)

Common Mistakes

  • Multiplying the number by 3 instead of cubing it.
  • Integer overflow if the input number is too large.
ADVERTISEMENT