Math.max
and minTwo numbers are different—one is larger and the other is smaller. With Math.max
we get the larger one, and with Math.min
we get the smaller one.
With these methods, we can restrict numbers to a valid range. We can avoid accessing an array out of range. We can keep track of the highest (or lowest) score.
Here we use Math.min
. We pass it two arguments and receive the argument back that is lower. We use Math.min
to avoid accessing an array at an index that is too high.
public class Program { public static void main(String[] args) { String[] animals = { "cat", "dog", "bird" }; // Use Math.min to keep index in range. // ... Try to get index 4. String result = animals[Math.min(animals.length - 1, 4)]; System.out.println(result); // Try to get index 1. result = animals[Math.min(animals.length - 1, 1)]; System.out.println(result); } }bird dog
for
-loopIn this example we have two arrays: one has 3 elements, the other 4. With Math.min
we get the count of common element indexes in both arrays.
Math.min
method returns 3 here. Both codes1 and codes2 have 3 elements.for
-loop. The fourth element in "codes2" is not printed.public class Program { public static void main(String[] args) { int[] codes1 = { 100, 200, 300 }; int[] codes2 = { 300, 400, 500, 600 }; // Use Math.min to get smallest length for both arrays. int commonLength = Math.min(codes1.length, codes2.length); // Display elements in each array at indexes. // ... All indexes have elements. for (int i = 0; i < commonLength; i++) { System.out.println(codes1[i] + "/" + codes2[i]); } } }100/300 200/400 300/500
Math.max
In this example we score words based on their letters. We use Math.max
to keep track of the highest-scoring word. We do not need if
-statements to track this value.
Math.max
that is passed (as one argument) that same value.Math.min
.public class Program { public static void main(String[] args) { String[] codes = { "abc", "def", "abcdef", "bc" }; // Loop over strings and score them on their letters. int maxScore = -1; for (String code : codes) { // Compute score for the string. int score = 0; for (int i = 0; i < code.length(); i++) { score += code.charAt(i); } System.out.println(score); // Keep track of highest score with Math.max. maxScore = Math.max(maxScore, score); } // Print highest score. System.out.println("Max score: " + maxScore); } }294 303 597 197 Max score: 597
With Math.max
and Math.min
we compare two numbers in a method call. We can avoid writing many if
-statements. This leads to clearer, more correct, more declarative code.