Languages
[Edit]
EN

Java - max value in array

0 points
Created by:
Evie-Grace-Noble
621

This article will show you how to find the maximum value in an array in Java.

Quick solution:

Integer[] numbersArray = { 1, 5, 2, 16, -5};

int max = Collections.max(Arrays.asList(numbersArray)); 
System.out.println( max ); // 16

 

Practical examples

1. With Collections.max method

public class MathExample {
    
    public static void main(String[] args) {
        Integer[] numbersArray = { 1, 5, 2, 16, -5};

        int max = Collections.max(Arrays.asList(numbersArray)); 
        System.out.println( max ); // 16
    }
}

2. By comparing all the elements in the array

public class MathExample {

    static double max(double[] array) {
        double result = Double.NEGATIVE_INFINITY;
        for (double currentNumber : array) {
            if (result < currentNumber) result = currentNumber;
        }
        return result;
    }

    public static void main(String[] args) {
        double[] numbersArray = {1.4, 5.0, 2.2, 16.0, -5.0};

        System.out.println(  max(numbersArray) ); // 16.0
    }
}

See also

  1. Java - Math.max() method example

  2. Maxima and minima - Wikipedia

Alternative titles

  1. Java - how to find maximum value in an array
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Java - Arrays (popular problems)

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join