Java program to find second largest number in an array

Java programing interview question to check your logic like how to print repeated numbers in an array here and how to balanced your parentheses. In my previous post, I have shared small list of java 7 features with practical example here and in this post going to show you simple program to find the second largest number in an array using two different approach one is traditional way and another one is using one of the collection api.

ArrayUtils .java
package com.javamakeuse.poc;

import java.util.Set;
import java.util.TreeSet;

public class ArrayUtils {

 // without using collection framework
 public static int getSecondLargestNum(int[] numbers) {
  int largestNum = numbers[0];
  int secondLargest = numbers[0];
  for (int i = 0; i < numbers.length; i++) {
   if (numbers[i] > largestNum) {
    secondLargest = largestNum;
    largestNum = numbers[i];
   } else if (numbers[i] > secondLargest) {
    secondLargest = numbers[i];
   }
  }
  return secondLargest;

 }

 // using collection framework
 public static int getSecondLargestNumber(int[] numbers) {
  Set<Integer> numSet = new TreeSet<>();
  for (int i : numbers) {
   numSet.add(i);
  }
  Object[] numArray = numSet.toArray();
  return (int) numArray[numArray.length - 2];
 }

 public static void main(String[] args) {
  int[] numbers = { 1, 3, 4, 5, 6, 7, 8 };
  System.out.println("Second largest number is - "
    + getSecondLargestNum(numbers));
  System.out.println("Second largest number is - "
    + getSecondLargestNumber(numbers));
 }
}


OUT PUT:
Second largest number is - 7
Second largest number is - 7

Comments

Popular posts from this blog

JSP Servlet Interview Questions For Freshers Series 1

What are the core classes and interfaces of hibernate 4

Java Banking Finance Services and Insurance (BFSI) domain interview questions