## DEV Community π©βπ»π¨βπ» is a community of 963,274 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Edwin Torres

Posted on

# Calculate the Volume of a Cube in Java

The volume of a cube with side s is: s x s x s or s to the 3rd power.

In Java, the Math.pow(x,y) function raises x to the power y. Both variables are double values, and the function returns a double result.

Letβs write a Java program to calculate the volume of a cube. The first three lines import the Scanner class (needed for user input), declare the Java program class, and declare the main method:

import java.util.Scanner;
public class Volume {
public static void main(String[] args) {

Declare two variables in the main method to store the side of the cube and the volume:

double s;  // side
double v;  // volume

Create a Scanner object that scans standard input. Store the object in the variable in:

Scanner in = new Scanner(System.in);

Ask the user to input a value for the side:

System.out.println("Please enter the side of the cube: ");

Use the nextDouble() method of the Scanner object to accept the side from the user and store it in the variable s. Note that the program will wait on this line until the user presses the Enter key to input a value:

s = in.nextDouble();

Use the Math.pow() function to raise s to the power 3. Store the result in the variable v:

v = Math.pow(s,3);

Output the result:

System.out.println("The volume of cube with side " + s + " is " + v + ".");

Finally, close the main method and Java program:

}
}

Here is the complete program:

import java.util.Scanner;
public class Volume {
public static void main(String[] args) {
double s;  // side
double v;  // volume
Scanner in = new Scanner(System.in);
System.out.println("Please enter the side of the cube: ");
s = in.nextDouble();
v = Math.pow(s,3);
System.out.println("The volume of cube with side " + s + " is " + v + ".");
}
}