# Find second highest number in an integer Array

Java Interview Program to find second highest number in an integer array without sorting the elements.

1. package com.instanceofjava;
2. class SecondLargestNumber{
3.
4. public static void main(String args[])
5.
6. int numbers[] = {6,3,37,12,46,5,64,21};
7. int highest = 0;
8.  int second_highest = 0;
9.
10. for(int n:numbers){
11.
12. if(highest < n){
13.
14.       second_highest = highest;
15.       highest =n;
16.
17.  } else if(second_highest < n){
18.
19.                 second_highest = n;
20.
21. }
22.
23. }
24.         System.out.println("First Max Number: "+highest);
25.         System.out.println("Second Max Number: "+second_highest);

26.
27.  }
28.
29. }

Output:

1. First Max Number: 64
2. Second Max Number: 46

Java Interview Program to find second highest number in an integer array by sorting the elements.

1. package com.instanceofjava;
2. class SecondLargestNumber{
3.
4. public static void main(String args[])
5.
6. int numbers[] = {6,3,37,12,46,5,64,21};
7.
8.   Arrays.sort(numbers);
9.
10.   System.out.println("Largest Number: "+numbers[numbers.length-1]);
11.   System.out.println("Second Largest Number: "+numbers[numbers.length-2]);
12.  }
13.
14. }

Output:

1. Largest Number: 64
2. Second Largest Number: 46

#### 3 comments for Find second highest number in an integer Array

1. import java.io.*;
class Secondhigh
{
public static void main(String args[])throws IOException
{
int n;
System.out.println("enter size");
System.out.println("enter array");
int[] a;
a=new int[n];
for(int i=0;ia[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
for(int i=0;i<n;i++)
System.out.print(a[i]);
System.out.println();
System.out.println(a[n-2]);
}
}

2. //add the pair of array and find highest and second_higest number;
int hig,sec_hig, k, n,m=0;
int a[]= {4,6,8,9,2,6};//add {4+6=10,6+8=14...2+6=8} i.e{10,14,17,11,8} and find highest,Second_hig number;
for(int i=0;i<a.length-1;i++) {
m++;
k=a[n]+a[m];
// System.out.println(k);
if(hig < k){
sec_hig = hig;
hig =k;
} else if(sec_hig < k){
sec_hig = k;
}
n++;
}
System.out.println("highest="+hig);
System.out.println("Second_hig="+sec_hig);
}
public static void main(String[] args){
}
}

3. int max =0;
int secmax = 0;

for(int i : arr) {
if(i > max) {
secmax = max;
max = i;
}
else if(i > secmax && i != max) {
secmax = i;
}
}

int[] res = {max, secmax};
return res;