Java April 2023 Solution 2nd semester
Q11: Find the Second Largest Integer in an Array
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
public class SecondLargest { public static void main(String[] args) { int[] arr = {12, 35, 1, 10, 34, 1}; int first = Integer.MIN_VALUE, second = Integer.MIN_VALUE; for (int num : arr) { if (num > first) { second = first; first = num; } else if (num > second && num != first) { second = num; } } if (second == Integer.MIN_VALUE) { System.out.println("No second largest element."); } else { System.out.println("The second largest element is: " + second); } } } |
Q12: Use of final Data Member, Method, and Class Final Data Member: Once assigned a value, it cannot be changed. Final Method: Prevents method overriding in subclasses. Final Class: Prevents inheritance of the class.
1 2 3 4 5 6 7 8 9 10 |
final class FinalClass { final int value = 100; final void display() { System.out.println("This is a final method."); } } // This would cause an error as FinalClass cannot be extended // class Child extends FinalClass {} |
Q13: Why Do We Need Wrapper Classes? Wrapper classes […]
Continue Reading