Arrays are fundamental structures in Java that allow us to store multiple values of the same type in a single variable. They are useful for storing and managing collections of data.Arrays are index based.
Basics of Arrays in Java
There are some basic operations we can start with as mentioned below:
- Array Declaration
To declare an array in Java, use the following syntax:
type[] arrayName;
type: The data type of the array elements (e.g., int, String).
arrayName: The name of the array.
Note: The array is not yet initialized.
- Create an Array
To create an array, you need to allocate memory for it using the new keyword:
// Creating an array of 5 integers
int[] numbers = new int[5];
This statement initializes the numbers array to hold 5 integers. The default value for each element is 0.
- Access an Element of an Array
We can access array elements using their index, which starts from 0:
// Setting the first element of the array
numbers[0] = 10;
// Accessing the first element
int firstElement = numbers[0];
The first line sets the value of the first element to 10. The second line retrieves the value of the first element.
- Change an Array Element
To change an element, assign a new value to a specific index:
// Changing the first element to 20
numbers[0] = 20;
- Array Length
We can get the length of an array using the length property:
// Getting the length of the array
int length = numbers.length;
REFERENCE:https://www.geeksforgeeks.org/arrays-in-java/
PROGRAM:
public class Marks
{
public static void main(String args[])
{
int[] marks={96,92,65,89,93};
System.out.println(marks.length);
int i=0;
int total=0;
while(i<marks.length)
{
System.out.println(marks[i]);
total=total+marks[i];
i++;
}
System.out.println(total);
System.out.println(total/marks.length);
}
}
OUTPUT:
length:5
mark:96
mark:92
mark:65
mark:89
mark:93
Total:435
percentage:87