Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

min(a,b) and max(a,b) equivalent in Java?

Tags:

java

In C, there is a min() convenience macro that helps make the code more readable.

In java, the shortest equivalent I know of is:

(a > b ? b : a) 

But it's not as self-documenting as min() in my view.

Is there a built-in min() method in Java (and I just couldn't find it)? or my only recourse is to define a method like this myself?

like image 849
uTubeFan Avatar asked Sep 19 '11 19:09

uTubeFan


People also ask

Is there a min and max function in Java?

Collections. min() method return the minimum element in the specified collection and Collections. max () returns the maximum element in the specified collection, according to the natural ordering of its elements.

Is there a max method in Java?

Overview. The max() method is an inbuilt method of Math class which is present in java. lang package that is used to find the maximum of two numbers. The max() method takes two inputs that are of types numbers, i.e., int, float, double, and returns the maximum of the given numbers.

Is there MIN function in Java?

min() function is an inbuilt function in java that returns the minimum of two numbers. The arguments are taken in int, double, float and long. If a negative and a positive number is passed as an argument then the negative result is generated.


2 Answers

Math.min()? (Comes in several overloads for different types.)

like image 192
Oliver Charlesworth Avatar answered Sep 30 '22 20:09

Oliver Charlesworth


have a look at the javadoc of Math

you can use it like :

import static java.lang.Math.*;  public static void main(String[] args) {     System.out.println(min(1, 0)); } 
like image 30
kdabir Avatar answered Sep 30 '22 21:09

kdabir