Get the largest number in arraylist java

Java Program to find the Largest Number in an Array

In this tutorial, I am going to help you to build a Java code through which you can find out the largest number in an array. After you enter the numbers of the array as an input, the program will start comparing the numbers with each other and reach its conclusion.
The pointers to be discussed are as follows:

  • How to find the largest number in an array in Java
  • Java Program to find largest number in array

Let us see how it is done!

How to find largest number in an array in Java?

Its simple. You need to declare an array at the begging of the program. The program would scan the code using the for loop and would conclude its result[the largest number] from the array that has been declared initially. Refer the coed snippet below:

arr[]= {5, 45,20,80,4,160,90,86}

Output: 160

Java Program to find largest number in Array

Code:

public class Example { public static void main[String[] args] { int n, max; Scanner s = new Scanner[System.in]; System.out.print["Enter the number of elements in the array:"]; n = s.nextInt[]; int a[] = new int[n]; System.out.println["Enter the elements of array:"]; for[int i = 0; i < n; i++] { a[i] = s.nextInt[]; } max = a[0]; for[int i = 0; i < n; i++] { if[max < a[i]] { max = a[i]; } } System.out.println["Maximum value in the array is:"+max]; } }

Output:
Enter the number of elements in the array:5
Enter the elements of array:
10
4
8
1
3
Maximum value in the array is: 10

Code 2

Moving on with a simpler approach.

class LargestNumber { public static void main[String args[]] { int[] a = new int[] { 22, 3, 550, 4, 11, 100}; int max = a[0]; for[int i = 1; i < a.length;i++] { if[a[i] > max] { max = a[i]; } } System.out.println["The Given Array is:"]; for[int i = 0; i < a.length;i++] { System.out.println[a[i]]; } System.out.println["The Largest Number is:" + max]; } }

Output:
The given array is:
22
3
550
4
11
100
The largest number is: 550

In this example, we have used for loop to reach to our aim. I hope you have understood the usage by now!

This is how we can accomplish our goal through Java code. I hope you are clear with the concept. Keep reading, keep exploring!

Now that you have understood basics of Java, check out theJava Online Courseby Edureka,a trusted online learning companywith a network of more than250,000satisfied learnersspread acrossthe globe. Edurekas Java J2EE and SOA training and certification course is designed for students and professionals who want to be a Java Developer. The course is designed to give you a head start into Java programming and train you for both core and advanced Java concepts along with various Java frameworks like Hibernate & Spring.

Got a question for us? Please mention it in the comments section of this Java Program to find the Largest Number in an Array blog and we will get back to you as soon as possible.

Video liên quan

Chủ Đề