Home >Java >javaTutorial >How to find the largest element in an array in java

How to find the largest element in an array in java

PHPz
PHPzforward
2023-05-04 18:07:071251browse

Find the largest element in the array

public static int maxNum(int[] array){
        if(array == null) return -1;
        if (array.length == 0) return -1;
        int max = array[0];
        for (int i = 1; i <array.length ; i++) {
            if(max < array[i]){
                max = array[i];
 
            }
        }
        return max;
    }
 
    public static void main(String[] args) {
        int[] array = {12,8,14,26,5,7,8};
        int max = maxNum(array);
        System.out.println(max);
    }

Print result:

How to find the largest element in an array in java

The above is the detailed content of How to find the largest element in an array in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete