In this tutorial, we’ll create a Java program that calculates the square, cube, and square root of a given number. This exercise is designed for beginners and covers basic arithmetic operations and the use of mathematical functions in Java.

In this tutorial, we’ll create a Java program that calculates the square, cube, and square root of a given number. This exercise is designed for beginners and covers basic arithmetic operations and the use of mathematical functions in Java.

Before we proceed, let’s ensure that we have access to the mathematical functions required for calculating the square root. We’ll import the ‘Math’ library in Java.

```
import java.lang.Math;
```

To make our program versatile, let’s allow the user to input the number for which they want to find the square, cube, and square root. We’ll use the ‘Scanner’ class for this purpose.

```
import java.util.Scanner;
public class NumberOperations {
public static void main(String[] args) {
// Import the Math library
import java.lang.Math;
// Create a Scanner object for user input
Scanner scanner = new Scanner(System.in);
// Prompt the user to enter a number
System.out.print("Enter a number: ");
int userNumber = scanner.nextInt();
```

Now, let’s calculate the square and cube of the user-entered number using basic arithmetic operations.

```
// Calculate the square of the number
int square = userNumber * userNumber;
// Calculate the cube of the number
int cube = userNumber * userNumber * userNumber;
```

For calculating the square root, we’ll use the ‘Math.sqrt()’ function provided by the ‘Math’ library.

```
// Calculate the square root of the number
double squareRoot = Math.sqrt(userNumber);
```

Finally, let’s display the results of our calculations to the user.

```
// Display the square, cube, and square root
System.out.println("Square of " + userNumber + ": " + square);
System.out.println("Cube of " + userNumber + ": " + cube);
System.out.println("Square Root of " + userNumber + ": " + squareRoot);
// Close the scanner to prevent resource leak
scanner.close();
}
}
```

Save the file with a “.java” extension, compile it using a Java compiler, and run the compiled class file. Input a number when prompted, and observe the calculated square, cube, and square root displayed in the console.

You’ve successfully created a Java program to find the square, cube, and square root of a given number. This exercise introduced you to user input, basic arithmetic operations, and the use of the ‘Math’ library. As you continue your programming journey, you’ll encounter more advanced topics and build upon these foundational concepts.

Feel free to explore further by modifying the code, experimenting with different numbers, and enhancing the program based on your interests and learning goals.

Leave Your Comment