How to find the second largest number in an array in Java?
To find the second largest number in an array in Java, you can follow these steps:
- Initialize two variables, 
largestandsecondLargest, to hold the largest and second largest numbers, respectively. Set both variables to a very small value, such asInteger.MIN_VALUE. - Iterate through the array, comparing each element with the 
largestandsecondLargestvariables. - If the current element is greater than the 
largestvalue, update bothlargestandsecondLargest. Set the currentlargestvalue tosecondLargest, and the current element as the newlargestvalue. - If the current element is smaller than the 
largestvalue but greater than thesecondLargestvalue, update only thesecondLargestvalue to the current element. - After iterating through the entire array, the 
secondLargestvariable will hold the second largest number. 
Here’s the Java code implementation:
<span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">SecondLargestNumber</span> {
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">main</span><span class="hljs-params">(String[] args)</span> {
        <span class="hljs-type">int</span>[] numbers = {<span class="hljs-number">5</span>, <span class="hljs-number">2</span>, <span class="hljs-number">10</span>, <span class="hljs-number">8</span>, <span class="hljs-number">1</span>, <span class="hljs-number">9</span>};
        <span class="hljs-type">int</span> <span class="hljs-variable">largest</span> <span class="hljs-operator">=</span> Integer.MIN_VALUE;
        <span class="hljs-type">int</span> <span class="hljs-variable">secondLargest</span> <span class="hljs-operator">=</span> Integer.MIN_VALUE;
        <span class="hljs-keyword">for</span> (<span class="hljs-type">int</span> <span class="hljs-variable">i</span> <span class="hljs-operator">=</span> <span class="hljs-number">0</span>; i < numbers.length; i++) {
            <span class="hljs-keyword">if</span> (numbers[i] > largest) {
                secondLargest = largest;
                largest = numbers[i];
            } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (numbers[i] > secondLargest && numbers[i] != largest) {
                secondLargest = numbers[i];
            }
        }
        System.out.println(<span class="hljs-string">"The second largest number is: "</span> + secondLargest);
    }
}
In this example, the array numbers contains six elements. The code iterates through each element and updates the largest and secondLargest variables accordingly. Finally, it prints the second largest number, which is 9 in this case.
