• Lets see an example program to get largest element in an integer array. and also find second largest element in the same array.


  1. package com.instanceofjava; 
  2. public class Array {
  3.  
  4. public static void main(String[] args) {
  5.  
  6. int arr[]={1,120,56,78,87};
  7. int largest=arr[0];
  8. int smallest=arr[0];
  9. int small=0;
  10. int index=0;
  11.  
  12. for(int i=1;i<arr.length;i++){
  13.  
  14. if(arr[i]>largest){
  15.  
  16. largest=arr[i];
  17. index=i;
  18.  
  19. }
  20. else if(smallest>arr[i]){
  21.  
  22. smallest=arr[i];
  23. small=i;
  24.  
  25. }
  26. }
  27.  
  28. System.out.println(largest);
  29. System.out.println(index);
  30. System.out.println(smallest);
  31. System.out.println(small);
  32.  

  33. }


Output:
  1. 120
  2. 1
  3. 87
  4. 4


Instance Of Java

We are here to help you learn! Feel free to leave your comments and suggestions in the comment section. If you have any doubts, use the search box on the right to find answers. Thank you! 😊
«
Next
Sort integer array using Bubble Sort in java
»
Previous
How to Add elements to hash map and Display?

No comments

Leave a Reply

Select Menu