greatest element in array in java

h‮w//:sptt‬ww.lautturi.com
greatest element in array in java

To find the greatest element in an array in Java, you can iterate through the array and keep track of the maximum value that you encounter.

Here's an example of how you can do this:

int[] numbers = {5, 10, 15, 20, 25};

int max = numbers[0];
for (int i = 1; i < numbers.length; i++) {
    if (numbers[i] > max) {
        max = numbers[i];
    }
}

System.out.println("The greatest element in the array is " + max);

This code will print "The greatest element in the array is 25".

You can also use the Arrays.stream() method and the max() method from the java.util.OptionalInt class to find the maximum element in the array:

int[] numbers = {5, 10, 15, 20, 25};

int max = Arrays.stream(numbers).max().getAsInt();

System.out.println("The greatest element in the array is " + max);

This code will also print "The greatest element in the array is 25".

Note that these examples assume that the array contains elements of type int. If the array contains elements of a different type, such as double or String, you will need to use a different approach to compare the elements. For example, you can use the compareTo() method for String objects comparation.

Created Time:2017-11-01 12:05:04  Author:lautturi