Calculate Percentage in Java

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.

Leave a Reply

Your email address will not be published.