How to Accept a Number from User and Print it’s Square & Cube in Java

This a Java program designed to calculate both the square and cube of a number entered by the user. 

It provides a quick and convenient way to obtain the square (n^2) and cube (n^3) values of any numeric input.

How to Accept Values of Two Numbers and Print their Addition

In this program:

  1. Importing Required Libraries: The program starts by importing the necessary library java.util.Scanner to allow user input.
  2. Variable Declarations: It declares three integer variables: n, square, and cube.
    • n will store the number entered by the user.
    • square will store the square (n^2) of the input.
    • cube will store the cube (n^3) of the input.
  3. Creating a Scanner Object: The program creates a Scanner object named scanner to read input from the user.
  4. User Input: The program prompts the user to enter a number by displaying the message "Enter Number: ". It waits for the user to input an integer, which is then read and stored in the n variable using scanner.nextInt().
  5. Closing the Scanner: After obtaining the user's input, the program closes the Scanner object using scanner.close() to release the resources associated with it.
  6. Calculating Square and Cube: The program calculates the square of the entered number by multiplying n by itself and stores it in the square variable. Similarly, it calculates the cube of the number by multiplying n by itself twice and stores it in the cube variable.
  7. Displaying Results: Finally, the program displays the results. It prints the square value with the message "Square: " and the cube value with the message "Cube: ". The calculated square and cube values are shown on separate lines for clarity.


import java.util.Scanner;

public class SquareAndCube {
    public static void main(String[] args) {
        int n, square, cube;
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter Number: ");
        n = scanner.nextInt();

        scanner.close();

        square = n * n;
        cube = n * n * n;

        System.out.println("\nSquare: " + square);
        System.out.println("Cube: " + cube);
    }
}
Join Now


Previous Year Questions Now to Boost Your Exam Performance

LOADS OF LOGIC