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

What is cr keyboard?

661


How to pass arraylist to stored procedure in java?

552


What is api in java?

543


What are the differences between the constructors and methods?

590


Is 0 true or is 1 true?

522






Will minecraft java be discontinued?

660


Can we force garbage collector to run ?

575


What is module with example?

516


Why map is used in java?

586


What is Java Reflection API? Why it’s so important to have?

610


What is the base class in java from which all classes are derived?

523


List some important characteristics on jre

600


What is the difference between Java Program Constructor and Java Program Method, What is the purpose of Java Program constructor Please Explain it Breafily?

605


Can static method access instance variables ?

609


What is java english?

498