C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Argument 1: In this example we use the last valid index of the "animals" array. We can never go higher than the last index.
Argument 2: This is the element we want to access. If this is too high, we will instead access the last valid index of the array.
Java program that uses Math.min
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);
}
}
Output
bird
dog
So: The Math.min method returns 3 here. Both codes1 and codes2 have 3 elements.
Finally: We print the common elements in a for-loop. The fourth element in "codes2" is not printed.
Java program that uses Math.min, arrays
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]);
}
}
}
Output
100/300
200/400
300/500
Tip: Often we assign a variable to the result of Math.max that is passed (as one argument) that same value.
And: This helps us modify a variable based on local maximums and minimums for Math.min.
Java program that uses Math.max
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);
}
}
Output
294
303
597
197
Max score: 597