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.
// for squreMath.pow(number, 2)// for cubeMath.pow(number, 3)// for squre rootMath.sqrt(number)
number
: This is the number whose cube, square, and square root we want to get.
The square, cube, and square root of the number value are returned.
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));}}
getResults()
that takes a number as an argument and prints the square, square root, and cube of that number.getResults()
function on the numbers we create. This function displays the square, square root, and cube of each number to the console.