Java Program to Find Largest Element in Array
int max = arr[0]; for (int i = 1; i < arr.length; i++) { if (arr[i] > max) max = arr[i]; }.Examples
How to Think About It
Algorithm
Code
public class LargestInArray { public static void main(String[] args) { int[] arr = {3, 5, 1, 9, 2}; int max = arr[0]; for (int i = 1; i < arr.length; i++) { if (arr[i] > max) { max = arr[i]; } } System.out.println("Largest element is: " + max); } }
Dry Run
Let's trace the array [3, 5, 1, 9, 2] through the code to find the largest element.
Initialize max
max = 3 (first element)
Compare with second element
arr[1] = 5 > max (3), so max = 5
Compare with third element
arr[2] = 1 <= max (5), max stays 5
Compare with fourth element
arr[3] = 9 > max (5), so max = 9
Compare with fifth element
arr[4] = 2 <= max (9), max stays 9
End of loop
max = 9 is the largest element
| Iteration | Current Element | max Value |
|---|---|---|
| Start | 3 | 3 |
| 1 | 5 | 5 |
| 2 | 1 | 5 |
| 3 | 9 | 9 |
| 4 | 2 | 9 |
Why This Works
Step 1: Initialize max
We start by assuming the first element is the largest using int max = arr[0];.
Step 2: Compare each element
We check each element with if (arr[i] > max) to find if there is a bigger number.
Step 3: Update max
If a bigger number is found, we update max to that number to keep track of the largest.
Step 4: Result
After checking all elements, max holds the largest value in the array.
Alternative Approaches
import java.util.Arrays; public class LargestInArray { public static void main(String[] args) { int[] arr = {3, 5, 1, 9, 2}; int max = Arrays.stream(arr).max().getAsInt(); System.out.println("Largest element is: " + max); } }
import java.util.Arrays; public class LargestInArray { public static void main(String[] args) { int[] arr = {3, 5, 1, 9, 2}; Arrays.sort(arr); int max = arr[arr.length - 1]; System.out.println("Largest element is: " + max); } }
Complexity: O(n) time, O(1) space
Time Complexity
The program checks each element once, so the time grows linearly with the array size, making it O(n).
Space Complexity
Only a few variables are used regardless of input size, so space complexity is O(1).
Which Approach is Fastest?
The simple loop is fastest and uses least memory. Sorting is slower (O(n log n)) and streams add overhead but are concise.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Simple loop | O(n) | O(1) | Fastest and simplest for all arrays |
| Java Streams | O(n) | O(1) | Concise code, requires Java 8+ |
| Sorting array | O(n log n) | O(1) | When array needs sorting anyway |