Arrays in Java
In Java, an array is a data structure that allows you to store multiple values of the same data type in a single variable. Arrays are widely used to work with collections of data. Arrays is a fundamental concept in Java programming.
Advantages of Arrays
- Represent multiple data items of the same type in a single variable.
- Arrays have a fixed size that is defined when they are created.
- Arrays can be easily iterated through using loops, making it convenient to perform operations on all elements in the array.
Accessing elements in Arrays
We can access elements in Arrays using indexes. Indexes start from zero. Zeroth element is the first element and n-1th element is the last element.
Changing elements in Arrays
We can reassign value to elements in arrays.
Length of Arrays
We can find the length of array using length function.
Iterating through Arrays
We can iterate through the elements of arrays using for loop and for each loop.
Arrays and For loop
We can iterate through elements of array using for loop.
Arrays and For each loop
We can also iterate through elements of array using for each loop.
Two Arrays
A 2D array in Java is essentially an array of arrays, where each element of the main array is itself an array. This creates a grid-like structure with rows and columns. You can think of a 2D array as a table or matrix.
Practice Exercises
Complete these exercises to reinforce your learning and earn XP
Array indexing starts from which number?
What will be printed?
int arr[] = {10, 20, 30};
System.out.print("%d", arr[1]);