How to find the max value in int array with Java

4 Answers

0 votes
public class MyClass {
    public static int max(int[] arr) {
        int maxval = arr[0];   
        for (int i = 1; i < arr.length; i++) {
            if (arr[i] > maxval) {
                maxval = arr[i]; 
            }
        }
        return maxval;
    }
    public static void main(String args[]) {
       int[] arr = new int [] {3, 0, 9, 7, 8, 5};   

        System.out.println(max(arr));
    }
}



/*
run:
   
9
   
*/

 



answered Aug 3, 2021 by avibootz
0 votes
import java.util.Arrays;

public class MyClass {
    public static void main(String args[]) {
        int[] values = { 7, 3, 9, 0, 8, 4};
        
        int max = Arrays.stream(values).max().getAsInt();
        
        System.out.println(max);  
    }
}
   
   
   
   
/*
run:
   
9
   
*/

 



answered Aug 3, 2021 by avibootz
edited Nov 13, 2023 by avibootz
0 votes
import java.util.Arrays;
 
public class MyClass {
    public static void main(String args[]) {
        int[] arr = new int [] {3, 0, 9, 7, 8, 5};   
 
        Arrays.sort(arr); 
        
        int min = arr[arr.length - 1];
         
        System.out.println(min);
    }
}
 
 
 
 
/*
run:
    
9
    
*/

 

 



answered Aug 3, 2021 by avibootz
edited Aug 4, 2022 by avibootz
0 votes
public class MyClass {
    public static int max(int[] arr) {
        int maxval = arr[0];   
        for (int i = 1; i < arr.length; i++) {
            maxval = Math.max(maxval, arr[i]);
        }
        
        return maxval;
    }
    public static void main(String args[]) {
        int[] arr = { 7, 3, 9, 0, 8, 4};
 
        System.out.println(max(arr));
    }
}
 
 
  
   
   
/*
run:
   
9
   
*/

 



answered Nov 13, 2023 by avibootz

Related questions

1 answer 124 views
124 views asked Nov 5, 2021 by avibootz
1 answer 160 views
1 answer 204 views
2 answers 170 views
1 answer 178 views
1 answer 215 views
...