0

I am doing this program to find 2nd largest element in array, but in method an exception occurs that secondMax is not initialized.... what is wrong in this code .....

import java. util.*;

public class largest_inArraya {
    
    public static int second_largest(int num[]) {
        int secondMax = 0;  
        int a = Integer.MIN_VALUE;
        for (int i = 0; i < num.length; i++) {
           
              if (a > num[i]) {
                secondMax = a;
                a = num[i];
            }
        }
        return secondMax;
    }

    public static void main(String[] args) {
        int num[] = { 12, 25, 83, 27, 17, 51, 32, 94, 30 };
        System.out.println("second largest element is "+second_largest(num));
    }

}

if second.Max initialized with any valu (0 , num[0] ) it gets assign that value and returns it..... the problem is secondMax is not get updated in loop..... any suggestion for this....

  • 5
    What if you pass an empty array? What will `secondMax`'s value be? Whatever you think it should be, you should explicitly assign `secondMax` that value before doing anything else. – Federico klez Culloca Oct 10 '22 at 08:56
  • 1
    you can give secondMax a default value. Keep in mind that it's possible that that if statement never returns true. or the array could be empty – Stultuske Oct 10 '22 at 08:56
  • The code you have shown does not produce the error you have. Please [edit] your question to include the source code you have and add the complete error message you get to your question as well. – Progman Oct 10 '22 at 12:13

0 Answers0