Arrays

Loading concept...

📦 Java Arrays: Your Super Organized Toy Box!

Imagine you have a magical toy box with numbered compartments. Instead of throwing all your toys in a messy pile, each toy gets its own little numbered slot. That’s exactly what an array is in Java!


🎯 What is an Array?

An array is like a row of lockers at school. Each locker:

  • Has a number (starting from 0, not 1!)
  • Can hold one thing of the same type
  • Is right next to the other lockers
// A row of 5 lockers for numbers
int[] lockers = new int[5];

Why start at 0? Think of it like measuring from the wall. The first locker is 0 steps away, the second is 1 step away, and so on!


📏 Single-Dimensional Arrays

This is the simplest array—just one row of boxes, like a train with numbered cars.

Creating Your First Array

Method 1: Empty boxes, fill later

// Make 5 empty boxes for whole numbers
int[] scores = new int[5];

// Put something in box 0
scores[0] = 100;
// Put something in box 1
scores[1] = 95;

Method 2: Create and fill at once

// Make boxes with toys already inside!
String[] friends = {"Ana", "Bob", "Cat"};

Accessing Items (Peeking Inside Boxes)

String[] colors = {"Red", "Blue", "Green"};

// Get the FIRST color (index 0)
System.out.println(colors[0]); // Red

// Get the THIRD color (index 2)
System.out.println(colors[2]); // Green

🚨 Watch Out! The Fence Post Error

graph TD A["Array: 3 items"] --> B["Index 0: First"] A --> C["Index 1: Second"] A --> D["Index 2: Third"] A --> E["Index 3: ❌ CRASH!"] style E fill:#ff6b6b

If your array has 3 items, valid indexes are 0, 1, 2. Asking for index 3 is like asking for a 4th car on a 3-car train—it doesn’t exist!

The Length Property

int[] nums = {10, 20, 30, 40, 50};
System.out.println(nums.length); // 5

Pro Tip: .length tells you how many boxes you have. The last valid index is always length - 1.

Walking Through All Boxes (Loops!)

String[] pets = {"Dog", "Cat", "Fish"};

// Visit each pet
for (int i = 0; i < pets.length; i++) {
    System.out.println(pets[i]);
}

Or use the simpler for-each loop:

for (String pet : pets) {
    System.out.println(pet);
}

🎲 Multi-Dimensional Arrays

What if you need a grid instead of just a row? Like a chess board or a seating chart!

2D Arrays: Rows and Columns

Think of a movie theater:

  • Rows go across (horizontal)
  • Seats in each row go down (vertical)
// 3 rows, 4 seats per row
int[][] theater = new int[3][4];

// Seat in row 0, seat 2
theater[0][2] = 1; // Someone sat here!

Creating with Values

int[][] grid = {
    {1, 2, 3},    // Row 0
    {4, 5, 6},    // Row 1
    {7, 8, 9}     // Row 2
};

// Get the number 5 (row 1, column 1)
System.out.println(grid[1][1]); // 5
graph TD A["2D Array Grid"] --> B["Row 0: 1, 2, 3"] A --> C["Row 1: 4, 5, 6"] A --> D["Row 2: 7, 8, 9"]

Walking Through a 2D Array

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

for (int row = 0; row < grid.length; row++) {
    for (int col = 0; col < grid[row].length; col++) {
        System.out.print(grid[row][col] + " ");
    }
    System.out.println(); // New line after each row
}

Output:

1 2 3
4 5 6

Jagged Arrays (Different Row Sizes!)

Unlike a perfect rectangle, Java lets you have rows of different lengths—like stairs!

int[][] stairs = {
    {1},           // 1 step
    {1, 2},        // 2 steps
    {1, 2, 3}      // 3 steps
};

🛠️ Array Operations and Utilities

Java gives you a toolbox full of helpful array tools in java.util.Arrays!

Printing Arrays Nicely

import java.util.Arrays;

int[] nums = {5, 2, 8, 1};
System.out.println(Arrays.toString(nums));
// Output: [5, 2, 8, 1]

For 2D arrays:

int[][] grid = {{1,2}, {3,4}};
System.out.println(Arrays.deepToString(grid));
// Output: [[1, 2], [3, 4]]

Sorting (Putting Things in Order)

int[] messy = {5, 2, 8, 1, 9};
Arrays.sort(messy);
System.out.println(Arrays.toString(messy));
// Output: [1, 2, 5, 8, 9]

Filling Arrays (Same Value Everywhere)

int[] all_fives = new int[5];
Arrays.fill(all_fives, 5);
// Result: [5, 5, 5, 5, 5]

Copying Arrays

int[] original = {1, 2, 3};
int[] copy = Arrays.copyOf(original, 3);
// copy is now [1, 2, 3]

// Make a bigger copy with extra space
int[] bigger = Arrays.copyOf(original, 5);
// Result: [1, 2, 3, 0, 0]

Comparing Arrays

int[] a = {1, 2, 3};
int[] b = {1, 2, 3};
int[] c = {1, 2, 4};

System.out.println(Arrays.equals(a, b)); // true
System.out.println(Arrays.equals(a, c)); // false

Searching in Sorted Arrays

int[] sorted = {10, 20, 30, 40, 50};
int index = Arrays.binarySearch(sorted, 30);
System.out.println(index); // 2

Important: The array MUST be sorted first!


🎮 Command Line Arguments

When you run a Java program, you can send it messages from outside—like giving instructions before the game starts!

How It Works

public class Greet {
    public static void main(String[] args) {
        // args holds the words you type
        if (args.length > 0) {
            System.out.println("Hello, " + args[0]);
        } else {
            System.out.println("Hello, stranger!");
        }
    }
}

Running it:

java Greet Alice

Output: Hello, Alice

Multiple Arguments

public class AddNumbers {
    public static void main(String[] args) {
        if (args.length >= 2) {
            int a = Integer.parseInt(args[0]);
            int b = Integer.parseInt(args[1]);
            System.out.println("Sum: " + (a + b));
        }
    }
}

Running it:

java AddNumbers 5 3

Output: Sum: 8

graph TD A["java MyApp Hello World 123"] --> B["args[0] = 'Hello'"] A --> C["args[1] = 'World'"] A --> D["args[2] = '123'"] A --> E["args.length = 3"]

Converting String Arguments

Remember: args is always String[]! Convert when needed:

String text = args[0];           // Already a String
int number = Integer.parseInt(args[1]);
double decimal = Double.parseDouble(args[2]);

🌟 Quick Summary

Concept Example
Create array int[] nums = new int[5];
Initialize with values int[] nums = {1, 2, 3};
Access element nums[0]
Get length nums.length
2D array int[][] grid = new int[3][4];
Sort Arrays.sort(nums);
Copy Arrays.copyOf(nums, 5);
Command args args[0] in main method

🎉 You Did It!

Arrays are like having superpowers for organizing data. Instead of creating 100 separate variables, you create ONE array with 100 slots. Neat, tidy, and super fast!

Remember the magic rules:

  1. Arrays start at index 0
  2. Last index is always length - 1
  3. Once created, arrays can’t grow or shrink
  4. All items must be the same type

Now go build something amazing with your new array powers! 🚀

Loading story...

No Story Available

This concept doesn't have a story yet.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

Interactive Preview

Interactive - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Interactive Content

This concept doesn't have interactive content yet.

Cheatsheet Preview

Cheatsheet - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Cheatsheet Available

This concept doesn't have a cheatsheet yet.

Quiz Preview

Quiz - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Quiz Available

This concept doesn't have a quiz yet.