Java Array
Java Arrays :
- In Java, an array is a data structure that stores a fixed-size sequential collection of elements of the same type.
- Arrays are used to store multiple values in a single variable, allowing easy access to individual elements by an index.
- They provide a way to store and manipulate collections of data more efficiently than using individual variables.
Use of Arrays in real life :
- Databases
- Lists and Collections
- Image and Sound Processing
- Games and Graphics etc.
Declaring and Initializing Arrays:
Declaration :
To declare an array in Java, you specify the data type of the elements followed by square brackets [] and the array name.
Initialization:
There are a few ways to initialize an array in Java:
Using the new keyword:
With array literals:
Accessing Array Elements:
Elements in an array are accessed by their index, starting from 0 to the length of the array minus 1.
Array Length:
The length of an array can be obtained using the length attribute.
Iterating Through an Array:
You can loop through an array using various types of loops, like for loop or enhanced for loop.
Using a for loop:
Using an enhanced for loop (for-each loop):
Firstly we have to understand , What is for-each loop ?
- The "for-each" loop, also known as the enhanced for loop, is a concise way to iterate through elements of arrays or collections in Java.
- It simplifies the process of looping through each element without the need for explicit indexing or manually controlling the loop counter.
Here's a simple explanation of how the for-each loop works in Java:
Here's what's happening in this example:
- int num declares a variable num of type int to hold each element in the myArray array.
- myArray is the array that you want to traverse.
- The loop automatically goes through each element in the myArray array one by one, assigning each element's value to the num variable.
- Inside the loop, System.out.println(num); prints each element of the array.