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 squre Math.pow(number, 2) // for cube Math.pow(number, 3) // for squre root Math.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 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)); } }
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.RELATED TAGS
CONTRIBUTOR
View all Courses