Java Arrays
Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.
To declare an array, define the variable type with square brackets
Example
String[ ] phones; String[] phones = {"Vivo", "Samsung", "Apple", "Nokia"}; Output: Vivo
-Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element is stored on 1st index and so on.
-We can store only a fixed set of elements in a Java array.
Types of Array in java:-
- Single Dimensional Array
- Multidimensional Array
Single Dimensional Array:-
-A single dimensional array in Java is a collection of elements of the same type that are stored in a sequential manner.
Here are some of the things you can do with single dimensional arrays:
- Store data.
- Access data.
- Sort data.
- Search data.
- Loop through data.
- Manipulate data.
Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
cars[0] = "Opel";
System.out.println(cars[0]);
// Now outputs Opel instead of Volvo
Multidimensional Array:-
In such case, data is stored in row and column based index (also known as matrix form).
Example
int[ ][ ] array = new int[3][4];
This code declares a multidimensional array of 3 rows and 4 columns. Each element in the array is an integer.
Example
public class Main { public static void main(String[] args) { int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} }; System.out.println(myNumbers[1][2]); } } Output: 7
Java Array Using for-each loop Java Array Using for-each loop
The Java for-each loop prints the array elements one by one. It holds an array element in a variable, then executes the body of the loop.
Example
int[] numbers = {1, 2, 3, 4, 5};
for (int number : numbers) {
System.out.println(number);
}
Output:
1
2
3
4
5