Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to find the second largest element of an array .

Java Code Example — Array Programs

ADVERTISEMENT

Java Program to find the second largest element of an array .

Objective

Write a Java program to find the second largest element of an array.

Algorithm / Approach

  1. Initialize a hardcoded array.
  2. First Pass: Loop through the array to find the maximum element (max) and store its index (m).
  3. Initialize smax with an element from a different index.
  4. Second Pass: Loop through the array to find the maximum element again, but ignore the index m by checking m != i.
  5. Update smax whenever a larger valid element is found.
  6. Print smax.
Test.java
class Test {
 void max() {
  int[] a = new int[]{2,3,4,5,6};
  int max = a[0], m = 0;
  for(int i =1; i< a.length; i++) {
   if(a[i]>max) {
    max = a[i];
    m = i;
   }
  }
  int smax = a[a.length-m-1];
  for(int i =0 ; i< a.length; i++) {
   if(smax< a[i] && m!= i) {
    smax = a[i];
   }
  }
   System.out.print("2nd Max = "+smax);
 }
 public static void main(String[] a)
 {
  Test t = new Test();
  t.max();
 }
}

Expected Output

2nd Max = 5

Explanation of the Program

  • This logic mirrors the second-smallest element problem.
  • By keeping track of the index of the largest element, we can effectively "mask" it out during our second scan.
  • The second scan then naturally finds the largest element out of the remaining numbers, which is by definition the second largest overall.

Complexity

Time Complexity O(n)
Space Complexity O(1)

Common Mistakes

  • Initializing the second max with 0 instead of a valid array element. If all array elements are negative numbers, 0 will incorrectly remain the maximum.
ADVERTISEMENT