How To Find the Largest and Smallest Value in Java



This is one of the articles from our Java Tutorial for Beginners.

The package java.lang has the class Math, which includes two methods that allow us to find the smallest value and the largest value of two values:



As you see, the Math class has several methods: min(), max(), round(), etc.

  • If you need to find the largest number of 2 numbers, you have to use Math.max().
  • If you need the find the smallest number of 2 numbers, you have to use Math.min().
  • Please note that with the help of Math.max() and Math.min(), you can compare numbers of any variable type (int, float, etc.), but the result is always of the double type.

Let's see how it works in practice.

If you run this code on your computer, you will see the following in the console:

The largest number of the two numbers is 5.0
The smallest number of the two numbers is 4.25


1. As you can see, this method

finds the largest number of the two numbers. As a result, we got 5.0, instead of 5, because Math.min() and Math.max() always give results in double type.

2. As you can see, this method

finds the smallest number of the two numbers, which is 4.25.

You should also learn other methods like Math.random(), Math.round (), Math.floor(), Math.ceil(). You can read about them in the articles below:

1.Random number generation in Java

2.Rounding of numbers in Java

You can find more articles in our Java Tutorial for Beginners. 


Самоучители--узнать детальнее--