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?

An array in Java is a collection of elements of the same data type, stored in contiguous memory locations.
Each element in the array can be accessed using an index, which starts from 0.

Example:

int[] marks = new int[5];

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:

int m1 = 90; int m2 = 85; int m3 = 75; int m4 = 80; int m5 = 95;

That’s a lot of variables!
Using an array:

int[] marks = {90, 85, 75, 80, 95};

Now we have a single variable marks that stores all values neatly.


🔹 Declaring an Array

There are two valid ways to declare an array:

int[] numbers; // preferred way int numbers[]; // also valid

🔹 Creating an Array

After declaration, we must allocate memory using the new keyword:

numbers = new int[5];

Or we can combine both in one line:

int[] numbers = new int[5];

🔹 Initializing an Array

We can assign values individually:

numbers[0] = 10; numbers[1] = 20; numbers[2] = 30; numbers[3] = 40; numbers[4] = 50;

Or directly at declaration:

int[] numbers = {10, 20, 30, 40, 50};

🔹 Accessing Array Elements

Each element is accessed using its index:

System.out.println(numbers[0]); // prints 10 System.out.println(numbers[4]); // prints 50

⚠️ Accessing an invalid index (like numbers[5]) will throw an ArrayIndexOutOfBoundsException.


🔹 Example 1: Display Array Elements

public class ArrayExample { public static void main(String[] args) { int[] numbers = {10, 20, 30, 40, 50}; System.out.println("Array elements are:"); for (int i = 0; i < numbers.length; i++) { System.out.println(numbers[i]); } } }

Output:

Array elements are: 10 20 30 40 50

🔹 Enhanced For Loop (For-Each)

Java provides a simpler way to iterate through arrays:

for (int num : numbers) { System.out.println(num); }

This loop automatically goes through each element — no need to use an index!


🔹 Array Length

The array has a built-in length variable:

System.out.println("Length: " + numbers.length);

🔹 Example 2: Sum of Array Elements

public class SumArray { public static void main(String[] args) { int[] numbers = {5, 10, 15, 20, 25}; int sum = 0; for (int i = 0; i < numbers.length; i++) { sum += numbers[i]; } System.out.println("Sum of elements: " + sum); } }

Output:

Sum of elements: 75

🔹 Multidimensional Arrays

Java allows arrays of arrays (like a matrix).

Example – 2D Array:

int[][] matrix = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; System.out.println(matrix[1][2]); // prints 6

🔹 Example 3: Print 2D Array

public class MatrixExample { public static void main(String[] args) { int[][] matrix = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[i].length; j++) { System.out.print(matrix[i][j] + " "); } System.out.println(); } } }

Output:

1 2 3 4 5 6 7 8 9

🔹 Arrays of Strings

public class StringArrayExample { public static void main(String[] args) { String[] fruits = {"Apple", "Banana", "Cherry"}; for (String fruit : fruits) { System.out.println(fruit); } } }

Output:

Apple Banana Cherry

🔹 Arrays of Objects

You can even create arrays of user-defined classes.

class Student { String name; int age; } public class StudentArray { public static void main(String[] args) { Student[] students = new Student[2]; students[0] = new Student(); students[0].name = "Alice"; students[0].age = 20; students[1] = new Student(); students[1].name = "Bob"; students[1].age = 21; for (Student s : students) { System.out.println(s.name + " - " + s.age); } } }

Output:

Alice - 20 Bob - 21

🔹 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

Arrays are essential in Java programming because they help manage data efficiently.
They form the foundation for more advanced data structures such as ArrayLists, Stacks, and Queues. Understanding arrays thoroughly will make it easier to learn these higher-level concepts.

Example Programs

1️⃣ Program to Find the Largest Element in an Array

public class LargestElement { public static void main(String[] args) { int[] numbers = {25, 47, 12, 89, 63}; int largest = numbers[0]; for (int i = 1; i < numbers.length; i++) { if (numbers[i] > largest) { largest = numbers[i]; } } System.out.println("Largest element in the array: " + largest); } }

Output:

Largest element in the array: 89

2️⃣ Program to Reverse the Elements of an Array

public class ReverseArray { public static void main(String[] args) { int[] numbers = {10, 20, 30, 40, 50}; System.out.println("Original array:"); for (int i = 0; i < numbers.length; i++) { System.out.print(numbers[i] + " "); } System.out.println("\nReversed array:"); for (int i = numbers.length - 1; i >= 0; i--) { System.out.print(numbers[i] + " "); } } }

Output:

Original array: 10 20 30 40 50 Reversed array: 50 40 30 20 10

3️⃣ Program to Create a 2D Array and Print the Sum of Each Row

public class SumOfRows { public static void main(String[] args) { int[][] matrix = { {2, 4, 6}, {1, 3, 5}, {7, 8, 9} }; for (int i = 0; i < matrix.length; i++) { int sum = 0; for (int j = 0; j < matrix[i].length; j++) { sum += matrix[i][j]; } System.out.println("Sum of row " + (i + 1) + ": " + sum); } } }

Output:

Sum of row 1: 12 Sum of row 2: 9 Sum of row 3: 24

Comments

Popular posts from this blog

Object Oriented Programming PBCST304 KTU BTech CS Semester 3 2024 Scheme - Dr Binu V P

Introduction to Java Programming

Inheritance and Polymorphism