JAVA - Zero to Hero / Arrays and Strings

Introduction to Arrays

πŸ“˜ What is an Array?

An array is a collection of elements that are:

  • Stored in contiguous memory locations

  • Of the same data type

  • Accessed using a zero-based index

Arrays allow us to store multiple values under a single variable name.


βœ… Key Characteristics

  • Fixed Size: The size is set during array creation and cannot be changed.

  • Indexed Access: Elements are accessed using indices starting from 0.

  • Homogeneous Elements: All elements must be of the same data type.

  • Object in Java: Even primitive type arrays (like int[]) are objects.


πŸ“š Array Declaration

There are two ways to declare an array in Java:

int[] numbers;     // Recommended
int numbers[];     // Also valid

πŸ—οΈ Array Creation (Instantiation)

After declaration, we create the array using new:

numbers = new int[5];  // Creates an array to hold 5 integers

Elements will be automatically initialized (e.g., 0 for int, false for boolean, null for objects).


🧾 Declaration + Initialization Together

You can declare and initialize an array in one line:

int[] scores = {90, 85, 78, 92, 88};

Here, the array size is inferred automatically (5 in this case).


🧠 Array Memory Representation

Example:

int[] marks = {60, 70, 80};

Index

Value

0

60

1

70

2

80


πŸ“ Length of an Array

You can use .length to find the size of the array:

int[] marks = {95, 88, 76};

System.out.println(marks.length);  // Output:3
3

πŸ“ Note: .length is a property, not a method (so no parentheses like length()).


⚠️ ArrayIndexOutOfBoundsException

Trying to access an index outside the valid range will throw an exception:

int[] marks = {95, 88, 76};

System.out.println(marks[5]);  // ❌ Error: Index 5 out of bounds
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 3 at ArrayExample.main(ArrayExample.java:4)

πŸ§ͺ Sample Program

public class ArrayExample {
    public static void main(String[] args) {
        int[] ages = {18, 21, 24};

        System.out.println("First element: " + ages[0]);
        System.out.println("Array length: " + ages.length);
    }
}
First element: 18
Array length: 3