Arrays in Java
🌟 Arrays in Java
Arrays are one of the most fundamental data structures in Java. They allow us to store multiple values of the same type in a single variable, making data management much easier and more efficient.
🔹 What is an Array?
Example:
This line creates an array named marks
that can store 5 integers.
🔹 Why Do We Need Arrays?
Without arrays, if we want to store the marks of 5 students, we might do this:
That’s a lot of variables!
Using an array:
Now we have a single variable marks
that stores all values neatly.
🔹 Declaring an Array
There are two valid ways to declare an array:
🔹 Creating an Array
After declaration, we must allocate memory using the new
keyword:
Or we can combine both in one line:
🔹 Initializing an Array
We can assign values individually:
Or directly at declaration:
🔹 Accessing Array Elements
Each element is accessed using its index:
⚠️ Accessing an invalid index (like numbers[5]
) will throw an ArrayIndexOutOfBoundsException
.
🔹 Example 1: Display Array Elements
Output:
🔹 Enhanced For Loop (For-Each)
Java provides a simpler way to iterate through arrays:
This loop automatically goes through each element — no need to use an index!
🔹 Array Length
The array has a built-in length variable:
🔹 Example 2: Sum of Array Elements
Output:
🔹 Multidimensional Arrays
Java allows arrays of arrays (like a matrix).
Example – 2D Array:
🔹 Example 3: Print 2D Array
Output:
🔹 Arrays of Strings
Output:
🔹 Arrays of Objects
You can even create arrays of user-defined classes.
Output:
🔹 Key Points to Remember
✅ Arrays in Java are objects.
✅ The index starts at 0.
✅ The length of an array is fixed once created.
✅ Can store primitive data types and objects.
✅ Accessing invalid indices causes exceptions.
💡 Summary
Example Programs
1️⃣ Program to Find the Largest Element in an Array
Output:
2️⃣ Program to Reverse the Elements of an Array
Output:
3️⃣ Program to Create a 2D Array and Print the Sum of Each Row
Output:
Comments
Post a Comment