DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

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.

Create account Log in
Edwin Torres
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) {
Enter fullscreen mode Exit fullscreen mode

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

double s;  // side
double v;  // volume
Enter fullscreen mode Exit fullscreen mode

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

Scanner in = new Scanner(System.in);
Enter fullscreen mode Exit fullscreen mode

Ask the user to input a value for the side:

System.out.println("Please enter the side of the cube: ");
Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode

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

v = Math.pow(s,3);
Enter fullscreen mode Exit fullscreen mode

Output the result:

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

Finally, close the main method and Java program:

  }
}
Enter fullscreen mode Exit fullscreen mode

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 + ".");
  }
}
Enter fullscreen mode Exit fullscreen mode

Thanks for reading. πŸ˜ƒ

Follow me on Twitter @realEdwinTorres for more programming tips and help.

Top comments (0)

Take a look at this:

Settings

Go to your customization settings to nudge your home feed to show content more relevant to your developer experience level. πŸ›