 ### I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE

## 1. Introduction

In this quick tutorial, we're going to implement a CLI program to calculate percentage in Java.

But first, let's define how to calculate percentage mathematically.

## 2. Mathematical Formula

In mathematics, a percentage is a number or ratio expressed as a fraction of 100. It's often denoted using the percent sign, “%”.

Let's consider a student that obtains x marks out of total y marks. The formula to calculate percentage marks obtained by that student would be:

percentage = (x/y)*100

## 3. Java Program

Now that we are clear on how to calculate percentage mathematically, let's build a program in Java to calculate it:

``````public class PercentageCalculator {

public double calculatePercentage(double obtained, double total) {
return obtained * 100 / total;
}

public static void main(String[] args) {
PercentageCalculator pc = new PercentageCalculator();
Scanner in = new Scanner(System.in);
System.out.println("Enter obtained marks:");
double obtained = in.nextDouble();
System.out.println("Enter total marks:");
double total = in.nextDouble();
System.out.println(
"Percentage obtained: " + pc.calculatePercentage(obtained, total));
}
}``````

This program takes the marks of the student (obtained marks and total marks) from CLI and then calls calculatePercentage() method to calculate the percentage out of it.

Here we've chosen double as a data type for input and output as it could store decimal numbers with up to 16 digits of precision. Hence, it should be adequate for our use case.

## 4. Output

Let's run this program and see the result:

``````Enter obtained marks:
87
Enter total marks:
100
Percentage obtained: 87.0

Process finished with exit code 0``````

## 5. Conclusion

In this article, we took a look at how to calculate percentage mathematically and then wrote a Java CLI program to calculate it.

Finally, as always, the code used in the example is available over on GitHub.

### I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE
Inline Feedbacks Ben
2 years ago

Next post, how to do a sum in Java! Your blog is gorgeous but sometimes you should filter these type of posts…

2 years ago

🙂 Some posts are addressed to more beginner developers, or just focused on a quick solution to a simple, yet common problem.

Thanks for the feedback. Ariana Venti
2 years ago

SEO phrases my friend. It’s all about getting that Google search traffic. I see why it’s done. But please note that you lose repeat visitors as tradeoff.

2 years ago