In Java , as we all know array is considered as object . Here in this post we want to find out the maximum value or largest value in the given array . Please note that here we are not using collection . It is even easier in collection to find the largest value in the array . I will provide you the logic for collection as well .
First we will find out the largest value in the array without using collection .
Pseudo code :
* We will store the first element in the array in the max variable .
* Every other number is compared with the max number , if greater than max then it is swapped with max value.
* Return the max value to the calling function .
* Display the max value in the array .
Demo :
Code :
To find out the largest value in array using Collection
PseudoCode :
* Convert array to List using asList() method .
* Then call the max method of the Collections class which will return the maximum value in the list .
First we will find out the largest value in the array without using collection .
Pseudo code :
* We will store the first element in the array in the max variable .
* Every other number is compared with the max number , if greater than max then it is swapped with max value.
* Return the max value to the calling function .
* Display the max value in the array .
Demo :
Code :
public class ArrayLargestValue { static int i,j,res,max,temp=0,a[]; public static void main(String args[]) { res=ArrayLargestValue.max(new int []{173,29,391,41}); System.out.println ("Largest value in the given array is : "+ res "); } static int max(int a[]) { max=0; for(i=0;i<a.length;i++) { if(a[i]>=a[max]) max=i; } return (a[max]); } }
To find out the largest value in array using Collection
PseudoCode :
* Convert array to List using asList() method .
* Then call the max method of the Collections class which will return the maximum value in the list .
import java.util.Arrays; import java.util.Collections; import java.util.List; public class ArrayLargestValue { public static void main(String[] args) { Integer[] arr = {33, 34, 112, 14, 23}; List<Integer> b = Arrays.asList(arr); System.out.println(Collections.max(b)); } }