In this post, we will write a Java program to find the largest element in an Array.
- Using Iterative Method
- Using Arrays.sort() Method
Using Iterative Method
public class LargestNumbersInArray {
public static void main(final String[] args) {
final int[] array = {12,34,56,12,13,454};
usingIterative(array);
}
private static int usingIterative(final int[] array){
// Initialize maximum element
int max = array[0];
// Traverse array elements from second and
// compare every element with current max
for (int i = 1; i < array.length; i++){
if (array[i] > max){
max = array[i];
}
}
System.out.println(max);
return max;
}
}
Output:
454
Using Arrays.sort() Method
public class LargestNumbersInArray {
public static void main(final String[] args) {
final int[] array = {12,34,56,12,13,454};
final int largest = usingLibrary(array);
System.out.println(largest);
}
private static int usingLibrary(final int[] array){
Arrays.sort(array);
return array[array.length - 1];
}
}
Output:
454
Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours
Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course
Comments
Post a Comment