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 LargestElement { 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
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: Start with first element
We assume the first element is the largest to have a starting point for comparison.
Step 2: Compare each element
We check each element with the current largest using if (arr[i] > max) to find if there's a bigger number.
Step 3: Update largest value
When a bigger number is found, we update max to hold this new largest value.
Step 4: Result after loop
After checking all elements, max holds the largest element in the array.
Alternative Approaches
import java.util.Arrays; public class LargestElementStream { public static void main(String[] args) { int[] arr = {3, 5, 1, 9, 2}; int max = Arrays.stream(arr).max().orElse(Integer.MIN_VALUE); System.out.println("Largest element is: " + max); } }
import java.util.Arrays; public class LargestElementSort { public static void main(String[] args) { int[] arr = {3, 5, 1, 9, 2}; Arrays.sort(arr); System.out.println("Largest element is: " + arr[arr.length - 1]); } }
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 loop method is fastest and simplest. Sorting takes O(n log n) time, and streams add overhead but are concise.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Loop through array | O(n) | O(1) | Simple and efficient 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 |