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 squreMath.pow(number, 2)// for cubeMath.pow(number, 3)// for squre rootMath.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 numbersint no1 = 4;int no2 = 100;int no3 = 9;int no4 = 0;// get their square, square roots and cubegetResults(no1);getResults(no2);getResults(no3);getResults(no4);}// create a method to get the square, square root and cube of a numbetstatic void getResults(int number){System.out.println("\nFor "+number);// the squareSystem.out.println("The square is "+Math.pow(number, 2));// the cubeSystem.out.println("The cube is "+Math.pow(number, 3));// the squre rootSystem.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.