ADVERTISEMENTS

How to find largest number in array in Java

An array in Java is a data structure that holds a fixed number of elements of the same data type. Arrays are useful for storing collections of data, such as a list of numbers, strings, or objects. In Java, there are several ways to find the largest number in an array. Here are a couple of examples:

Using a for loop

int[] numbers = {3, 6, 1, 8, 2, 9};
int largest = numbers[0];

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

System.out.println("The largest number is: " + largest);

In this example, we initialize the largest variable with the first element of the array. Then we use a for loop to iterate through the rest of the elements in the array, and compare each element to the largest variable. If the current element is larger than the largest variable, we update the largest variable with the current element.

Using the Arrays.sort()

int[] numbers = {3, 6, 1, 8, 2, 9};
Arrays.sort(numbers);
System.out.println("The largest number is: " + numbers[numbers.length-1]);

In this example, we use the Arrays.sort() method to sort the elements of the array in ascending order. Then, we access the last element of the array, which will be the largest number since the array is sorted.

Java is used for developing mobile apps, web applications, games, and other software. It is known for its "write once, run anywhere" (WORA) principle, which means that Java code can be run on any device that has a Java Virtual Machine (JVM) installed. You can learn java from our Java Tutorials and Java Examples

ADVERTISEMENTS