You can sort the array and fetch second last element which executes in O(nlogn), but this works only if you are sure that there are no duplicates in the array else this method is unreliable.
You can iterate through the array maintain counters for highest and second highest and return 2nd highest. This executes in O(n)
Example:
int highest = Integer.MIN_VALUE+1;
int sec_highest = Integer.MIN_VALUE;
for(int i : b) //b is array of integers
{
if(i>highest)
{
sec_highest = highest; //make current highest to second highest
highest = i; //make current value to highest
}
else if(i>sec_highest && i != highest)
{
sec_highest = i;
}
}
Another solution is:
int b[] = {1, 2, 31,22,12,12};
Arrays.sort(b);
System.out.println(b[b.length-2]);