# Java Program to Calculate Potential Energy

In this post, we will learn to code the Java Program to Calculate Potential Energy. Let’s understand Potential Energy and How to Calculate Potential Energy in Java Programming Language.

## What is Potential Energy ?

In Physics, Potential energy is the energy held by an object because of its position relative to other objects, stresses within itself, its electric charge, or other factors.

### Formula of Potential Energy

The formula for potential energy depends on the force acting on the two objects. The Formula of Potential Energy is as follows:

``Potential Energy or (P.E.) = m x g x h ``

m is the mass in kilograms.
g is the acceleration due to gravity
h is the height in meters.

We will use the same formula to code the Java Program to Calculate Potential Energy.

## Java Program to Calculate Potential Energy

```import java.util.*;

public class Main{

public static void main(String[] args){

Scanner sc = new Scanner(System.in);

System.out.println("Enter the mass (in kg): ");
float m = sc.nextFloat();

float g = 9.8f;

System.out.println("Enter the height (in meters): ");
float h = sc.nextFloat();

float PE = m * g * h;

System.out.printf("The Potential Energy is %.2f",PE);

}

}```

Output

``````Enter the mass (in kg): 5
Enter the height (in meters): 18
The Potential Energy is 882.00``````

## How Does This Program Work ?

```        Scanner sc = new Scanner(System.in);

System.out.println("Enter the mass (in kg): ");
float m = sc.nextFloat();

float g = 9.8f;

System.out.println("Enter the height (in meters): ");
float h = sc.nextFloat();```

In this program, we have declared four float data type variables named m, h, g, and PE. We have taken the input of mass and height from the user using the Scanner Class in Java. Then, we have assigned 9.8 which is the value of g (acceleration due to gravity).

`        float PE = m * g * h;`

Then, we calculated the Potential energy using the formula of Potential Energy discussed above.

`        System.out.printf("The Potential Energy is %.2f",PE);`

Then, we display the result using `System.out.printf() `function in Java, and to print the Potential energy to 2 decimal places, we used %.2f in the `System.out.printf() `function. This is the Java Program to Calculate the Potential Energy.

## Conclusion

I hope after going through this post, you understand Java Program to Calculate Potential Energy.
If you have any doubt regarding the topic, feel free to contact us in the Comment Section. We will be delighted to help you.