How to get the square, cube, and square root of a number in Java

Overview

In Java, we can get the square, cube, and square root of a number using the Math class. With the Math.pow() method, we can get the cube and square of the number. With Math.sqrt(), we can get the square root of the number.

Syntax

// for squre
Math.pow(number, 2)
// for cube
Math.pow(number, 3)
// for squre root
Math.sqrt(number)
The syntax for getting the square, cube and square root of a number

Parameter

number: This is the number whose cube, square, and square root we want to get.

Return value

The square, cube, and square root of the number value are returned.

Example

class HelloWorld {
public static void main( String args[] ) {
// create some numbers
int no1 = 4;
int no2 = 100;
int no3 = 9;
int no4 = 0;
// get their square, square roots and cube
getResults(no1);
getResults(no2);
getResults(no3);
getResults(no4);
}
// create a method to get the square, square root and cube of a numbet
static void getResults(int number){
System.out.println("\nFor "+number);
// the square
System.out.println("The square is "+Math.pow(number, 2));
// the cube
System.out.println("The cube is "+Math.pow(number, 3));
// the squre root
System.out.println("The square root is "+Math.sqrt(number));
}
}

Explanation

  • Lines 4-7: We create some numbers.
  • Line 17: We create a function called getResults() that takes a number as an argument and prints the square, square root, and cube of that number.
  • Lines 10-13: We invoke the getResults() function on the numbers we create. This function displays the square, square root, and cube of each number to the console.