bugl
bugl
HomeLearnPatternsPathsSearch
HomeLearnPatternsPathsSearch

Loading lesson path

Learn/Java/Java How To's
Java•Java How To's

Java How To - Second Largest Array Element

Flash cards

Review the key moves

1/4
Core idea

What is the main idea behind Java How To - Second Largest Array Element?

Lesson checks

Practice each idea before moving on

Short Mimo-style checks built from this lesson's code, terms, and sequence.

1Quick choice

Which statement best captures the main point of this lesson?

2Fill blank

Complete the missing token from the example code.

___[] nums = {12, 5, 9, 21, 21, 7};

How To Find the Second Largest Element in an Array

Find the second highest number without sorting the whole array:

Example

int[] nums = {12, 5, 9, 21, 21, 7};
Integer first = null, second = null;
for (int n : nums) {
  if (first == null || n > first) {
    second = first;
    first = n;
  } else if ((second == null || n > second) && n != first) {
  second = n;
}
}
if (second != null) {
  System.out.println("Second largest: " + second);
} else {
System.out.println("No distinct second largest value.");
}

Previous

Java How To - Largest Element in an Array

Next

Java How To Find Min and Max in Array