The array taking one subscript is known as one-dimensional array.
Declaration
The general form to declare an array is:
Type[ ] var-name;
here type declares the element type of the array. The element type determines the data type of each element. For example, the following declares an array named silan will the type array of int :
Example;
int[ ] arr;
here arr is an array(variable), but no array actually exists. That means the value of array is set to null which represents an array having no value. So java concept is saying that to link arr with an actual, physical array of integers, you must allocate using new operator(special operator for allocating memory) and assign it to arr. The general form of new for allocating one-dimensional array is :
Syntax:
array-name=new type[size];
where,
Example:
int[]=arr=new int[5];
when this statement is executed, 20(4bytes*5) of memory will be allocated dynamically named as arr having capability to contain maximum 5 integer data items.
Array Initialization
When the values are assigned to an array is known as array initialization,
Example:
int[] arr={10,20,30,40,50};
here, arr[0]=10;
arr[1]=20;
arr[2]=30;
arr[3]=40;
arr[4]=50;
Let’s see a simple array program:
Average.java
import java.util.Scanner; class Average { public static void main(String[] args) { int sum = 0, size; double avg; Scanner s = new Scanner(System.in); System.out.println("enter the size of the array:"); size = s.nextInt(); int a[] = new int[size]; System.out.println("enter the elements the array elements:"); for (int i = 0; i < a.length; i++) { a[i] = s.nextInt(); sum = sum + a[i]; } avg = (double)(sum / a.length); System.out.println("sum is: " + sum); System.out.println("average is: " + avg); } }
Output:
enter the size of the array
5
enter the array elements
1
2
3
4
5
sum is 15
average is 3.0
Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.
We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc