write java code to print second max number in the array

Answer Posted / rajesh s

This is I tried.
public class SecondLargestNumber {
/**
* @param args
*/
public static void main(String[] args) {
int[] num = new int[]{-101,-105,-2,-7,-22,-
104,-8,-10,-100,-102,-102};
int big=-1;
int secbig=-1;
if(num.length == 1) {
big = num[0];
secbig = num[0];
} else {
if(num[0] > num[1]) {
big = num[0];
secbig = num[1];
} else {
big = num[1];
secbig = num[0];
}
}
if(num.length > 2){
for(int i=2;i<num.length;++i){
if(num[i] > secbig && num
[i] <big) {
secbig = num[i];
}
if(num[i]>=big){
secbig = big;
big = num[i];
}
}
}
System.out.println(big);
System.out.println(secbig);
}
}

Please check is it working and let me know. For removing
duplicates, we will have one more method to remove the
duplicate elements.

Is This Answer Correct ?    4 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

Why java is considered dynamic?

757


Which package has light weight components?

567


What is boolean logic?

562


Explain the difference between the public, private, final, protected, and default modifiers?

553


What is meant by anonymous class?

596






What is sleep method?

623


How do you end a program?

553


What is java argument list?

522


How do you ensure that n threads can access n resources without deadlock?

815


What is the difference between ArrayList and Vector? which one is better in Java

609


How do you check whether the list is empty or not in java?

516


How do you execute a thread in java?

505


What happens if an exception is not handled in a program?

626


Explain about abstract classes in java?

589


Which programming language is best in future?

527