Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java ternary operator can be replaced with Math.max call

Tags:

java

I have the following code delay = (delay>200) ? delay : 200;
Java issues a warning message Can be replaced with 'Math.max' call for this.
Here I see that Math.max(a, b) is actually the same as (a > b) ? a : b so ternary operator is not worse than Math.max
So why Java issues this warning message if there are no advantages replacing the ternary operator by Math.max method call?

like image 209
Prophet Avatar asked May 09 '26 02:05

Prophet


1 Answers

I doubt that this is a real compiler warning, probably some IDE inspection/warning.

Nonetheless, you are correct, there are no hard technical reasons to prefer one over the other.

But: from the point of a human reader, using Math.max() has one major advantage: it is easier to read and understand. That simple.

Besides: do not duplicate code unless you have to.

Always remember: you write your code for your human readers. Compilers accept anything that is syntactically correct. But for your human readers, there is a difference between a condition and an assignment vs a very telling "take the maximum of two numbers".

like image 129
GhostCat Avatar answered May 10 '26 16:05

GhostCat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!