You can find the largest number in an array by looping through its elements and keeping track of the largest value found so far.
In this example, you will compare integers in an array and print the largest number.
Source code
public class LargestNumberExample {
void main() {
int[] numbers = {12, -5, 38, 7, 24};
if (numbers.length == 0) {
IO.println("The array is empty.");
return;
}
int largest = numbers[0];
for (int index = 1; index < numbers.length; index++) {
if (numbers[index] > largest) {
largest = numbers[index];
}
}
IO.println("Largest number: " + largest);
}
}
Explanation
The following statement creates an array of integers:
int[] numbers = {12, -5, 38, 7, 24};
Before accessing an element, the program checks whether the array is empty:
if (numbers.length == 0) {
IO.println("The array is empty.");
return;
}
An empty array has no largest value. The return statement ends the main() method so the program does not try to access an element that does not exist.
Next, the program uses the first element as the initial largest value:
int largest = numbers[0];
Array indexes start at zero, so numbers[0] refers to the first element.
Starting with an actual element makes the calculation work even when every number in the array is negative. Starting with 0 would give an incorrect result in that case.
The loop begins at index 1 because the first element is already stored in largest:
for (int index = 1; index < numbers.length; index++) {
if (numbers[index] > largest) {
largest = numbers[index];
}
}
On each iteration, the program compares the current element with largest. If the element is greater, it becomes the new largest value.
For this array, the comparisons work as follows:
| Current element | Largest value after comparison |
|---|---|
-5 |
12 |
38 |
38 |
7 |
38 |
24 |
38 |
After the loop finishes, largest contains 38.
Run the example
Compile and run the file:
javac LargestNumberExample.java
java LargestNumberExample
Output
Largest number: 38
If you change the array to contain only negative numbers:
int[] numbers = {-12, -5, -38, -7, -24};
The output becomes:
Largest number: -5
