Opening Hours :7AM to 9PM
class Largest { public int findLargest(int[] arr) { int largest = arr[0]; for (int i = 1; i < arr.length; i++) { if (arr[i] > largest) { largest = arr[i]; } } return largest; } } public class Main { public static void main(String[] args) { Largest lr=new Largest(); int[] arr = {1, 5, 3, 8, 2, 9, 4}; int largest = lr.findLargest(arr); System.out.println("The largest element in the array is: " + largest); } }This program uses a for-loop to iterate through the array and compares each element with the current largest element. If an element is greater than the current largest, it becomes the new largest element. The first element of the array is assumed as the largest element before the loop starts.
public class Main { public static void main(String[] args) { int[] arr = {1, 5, 3, 8, 2, 9, 4}; Arrays.sort(arr); int largest = arr[arr.length-1]; System.out.println("The largest element in the array is: " + largest); } }In both examples, the output will be: