Arrays in Java

1. Introduction to Arrays

1.1 What is an Array

An array is a collection of elements of the same data type stored in contiguous memory locations.

1.2 Need for Arrays

Instead of creating multiple variables:

int a = 10, b = 20, c = 30;

We use:

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

1.3 Characteristics

  • Fixed size
  • Same data type
  • Indexed (starts from 0)

1.4 Advantages

  • Easy data management
  • Faster access using index

1.5 Limitations

  • Fixed size
  • Cannot store different data types

2. Declaring and Initializing Arrays

2.1 Declaration

int[] arr;

2.2 Initialization

arr = new int[5];

2.3 Declaration + Initialization

int[] arr = {1, 2, 3, 4, 5};

2.4 Default Values

  • int → 0
  • float → 0.0
  • boolean → false
  • object → null

2.5 Example

int[] marks = new int[3];

3. Accessing Array Elements

3.1 Indexing

Array index starts from 0.

3.2 Accessing

int[] arr = {10, 20, 30};
System.out.println(arr[0]); // 10

3.3 Updating

arr[1] = 50;

3.4 Looping

for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}

3.5 Common Error

Accessing invalid index:

arr[5]; // Error

4. Multidimensional Arrays

4.1 Definition

Array of arrays.

4.2 Declaration

int[][] matrix;

4.3 Initialization

int[][] matrix = {
{1, 2},
{3, 4}
};

4.4 Accessing Elements

System.out.println(matrix[0][1]); // 2

4.5 Using Nested Loops

for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
}

4.6 Jagged Arrays

Arrays with different column sizes:

int[][] jagged = new int[2][];
jagged[0] = new int[2];
jagged[1] = new int[3];

5. Array Operations

5.1 Traversing

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

5.2 Searching

int key = 20;
for (int num : arr) {
if (num == key) {
System.out.println("Found");
}
}

5.3 Sorting

java.util.Arrays.sort(arr);

5.4 Copying

int[] copy = java.util.Arrays.copyOf(arr, arr.length);

5.5 Reversing

for (int i = arr.length - 1; i >= 0; i--) {
System.out.println(arr[i]);
}

5.6 Max and Min

int max = arr[0];
for (int num : arr) {
if (num > max) max = num;
}

5.7 Adding/Removing (Concept)

Arrays are fixed, so we create a new array.


6. Array Utility Methods

6.1 Arrays Class

Java provides Arrays class in java.util package.

6.2 Sorting

import java.util.Arrays;
Arrays.sort(arr);

6.3 Searching

Arrays.binarySearch(arr, 20);

6.4 Comparing

Arrays.equals(arr1, arr2);

6.5 Filling

Arrays.fill(arr, 0);

6.6 Convert to String

System.out.println(Arrays.toString(arr));

Conclusion

Arrays are a powerful and essential concept in Java that allow efficient data storage and manipulation. By understanding how to create, access, and perform operations on arrays, beginners can handle large amounts of data effectively and build more complex applications.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *