Array min / max value
In this chapter you will learn:
- Maximum value in a byte array
- Maximum value in a double-type array
- Returns the minimum value in a double-type array
Maximum value in a byte array
public class Main {
public static byte max(byte[] array) {
if (array == null) {
throw new IllegalArgumentException("The Array must not be null");
} else if (array.length == 0) {
throw new IllegalArgumentException("Array cannot be empty.");
}/* j a v a2 s.co m*/
byte max = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] > max) {
max = array[i];
}
}
return max;
}
}
Maximum value in a double-type array
public class Main {
public static double max(double[] array) {
if (array== null) {
throw new IllegalArgumentException("The Array must not be null");
} else if (array.length == 0) {
throw new IllegalArgumentException("Array cannot be empty.");
}/* j av a 2s. co m*/
// Finds and returns max
double max = array[0];
for (int j = 1; j < array.length; j++) {
if (Double.isNaN(array[j])) {
return Double.NaN;
}
if (array[j] > max) {
max = array[j];
}
}
return max;
}
}
Returns the minimum value in a double-type array
public class Main {
public static double min(double[] array) {
if (array == null) {
throw new IllegalArgumentException("The Array must not be null");
} else if (array.length == 0) {
throw new IllegalArgumentException("Array cannot be empty.");
}//j av a 2 s . com
// Finds and returns min
double min = array[0];
for (int i = 1; i < array.length; i++) {
if (Double.isNaN(array[i])) {
return Double.NaN;
}
if (array[i] < min) {
min = array[i];
}
}
return min;
}
}
Next chapter...
What you will learn in the next chapter:
Home » Java Tutorial » Array