← Back to all posts

15 Java Fundamentals

Arrays in Java

By Dummy for Dummies


Introduction

Imagine you have money, and you put it in a wallet. That's like putting data in a variable. Now imagine you have a bunch of wallets (definitely not stolen) and you put them all in one bag. That's an array, a variable full of variables.


Arrays

In an array, all the data you store must have the same datatype. Here is the magical spell to create an array:

int[] numbers = new int[5];

Let's break down the Java spell into our human language:

The array is now created, but it's actually empty. Its length is 5, meaning it can hold 5 pieces of data. Each slot has a specific index, think of it like a roll number.

Except in arrays, roll numbers start from 0, not 1. So this array's roll numbers are 0, 1, 2, 3, and 4.

You also can't print the whole array at once like a regular variable. You access one slot at a time through its index, like numbers[index], swapping in the roll number you want.


Code:

Java
public class Main {
    public static void main(String[] args) {
        // 1) Create an array that can store 5 integers (5 wallets in the bag)
        int[] numbers = new int[5];

        // length tells how many "wallets" we have (roll numbers 0..4)
        System.out.println("Array length (roll count): " + numbers.length);
        System.out.println();

        // 2) Fill the array (put money in each wallet)
        numbers[0] = 10;
        numbers[1] = 20;
        numbers[2] = 30;
        numbers[3] = 40;
        numbers[4] = 50;

        // 3) Access a single element using its index (roll no)
        System.out.println("First wallet (index 0) has: " + numbers[0]);
        System.out.println("Second wallet (index 1) has: " + numbers[1]);
        System.out.println("Third wallet (index 2) has: " + numbers[2]);
        System.out.println("Fourth wallet (index 3) has: " + numbers[3]);
        System.out.println("Fifth wallet (index 4) has: " + numbers[4]);
    }
}
Console Output
Array length (roll count): 5 First wallet (index 0) has: 10 Second wallet (index 1) has: 20 Third wallet (index 2) has: 30 Fourth wallet (index 3) has: 40 Fifth wallet (index 4) has: 50

Direct Initialization & Printing Using Loop

Instead of creating an empty array and filling it after, we can load the data in directly. Here's the spell for that:

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

We just write the data straight in without setting a size. It's not that useful in practice since most real code needs flexible sizing, but it's worth knowing this exists.

To print an array's contents, a for loop beats printing each index by hand. You could hardcode it to start at 0 and stop before 5 for this specific array, but a better approach is to never hardcode the size at all. Java gives you the length through arrayName.length, so the loop always matches the array, no matter how big it is. Here's a demonstration:

Java
public class Main {
    public static void main(String[] args) {
        int[] numbers = {10, 20, 30, 40, 50};

        System.out.println("Printing array using loop:");
        for (int i = 0; i < numbers.length; i++) {
            System.out.println("Index " + i + " has: " + numbers[i]);
        }
    }
}
Console Output
Printing array using loop: Index 0 has: 10 Index 1 has: 20 Index 2 has: 30 Index 3 has: 40 Index 4 has: 50

Updating Data in Arrays

We can even update the data inside arrays just like we replace it in variables. You can either access each data using a for loop and update them or change data on just a specific index.

Java
public class Main {
    public static void main(String[] args) {
        int[] numbers = {10, 20, 30, 40, 50};

        System.out.println("Before updating: ");
        for (int i = 0; i < numbers.length; i++) {
            System.out.println("Index " + i + " has: " + numbers[i]);
        }

        numbers[2] = 99;
        numbers[4] = 77;

        System.out.println("\nAfter updating: ");
        for (int i = 0; i < numbers.length; i++) {
            System.out.println("Index " + i + " has: " + numbers[i]);
        }
    }
}
Console Output
Before updating: Index 0 has: 10 Index 1 has: 20 Index 2 has: 30 Index 3 has: 40 Index 4 has: 50 After updating: Index 0 has: 10 Index 1 has: 20 Index 2 has: 99 Index 3 has: 40 Index 4 has: 77

Input in Arrays

Just like simple variables, we can take input from the user into an array. It can be either on a specific index, or on all indexes using a for loop. Let's ask the user for the length of the array, then start from index 0 and take input in all of them using a for loop.

Java
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter number of elements: ");
        int size = sc.nextInt();

        int[] numbers = new int[size];

        System.out.println("Enter " + size + " numbers:");
        for (int i = 0; i < numbers.length; i++) {
            System.out.print("Enter number at index " + i + ": ");
            numbers[i] = sc.nextInt();
        }

        System.out.println("\nYou entered:");
        for (int i = 0; i < numbers.length; i++) {
            System.out.println("Index " + i + " has: " + numbers[i]);
        }
        sc.close();
    }
}
Console Output
Enter number of elements: 3 Enter 3 numbers: Enter number at index 0: 11 Enter number at index 1: 22 Enter number at index 2: 33 You entered: Index 0 has: 11 Index 1 has: 22 Index 2 has: 33

Find Data in an Array

We can do multiple operations on an array. One of the simplest is finding data inside an array. For that, we will use a for loop to search through all indexes, compare the data with the target, save the index at which the target matches, and return it. The variable inside which we will store the index will be given a value "-1", so in case no index matches, it will remain negative. Since real indexes cannot be negative, we can easily know if the data is not found. Here is a demo:

Java
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

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

        System.out.print("Enter a number to search: ");
        int target = sc.nextInt();

        int foundIndex = -1;
        for (int i = 0; i < numbers.length; i++) {
            if (numbers[i] == target) {
                foundIndex = i;
                break;
            }
        }

        if (foundIndex != -1) {
            System.out.println("Number " + target + " found at index " + foundIndex);
        } else {
            System.out.println("Number " + target + " not found in array.");
        }
        sc.close();
    }
}
Console Output (Number found)
Enter a number to search: 30 Number 30 found at index 2
Console Output (Number not found)
Enter a number to search: 99 Number 99 not found in array.

Other Operations on Arrays

Just like searching for data, we can find the largest or smallest data in an array. Also, we can find the sum or average of the data inside an array. There are multiple more operations that can be applied to arrays for different purposes.


Exercise

Let's do an exercise for what we studied in this post. Study this code, break it down, analyze it and identify the concepts used here. It would be even better if you write down your observations and make a mini report on it.

Java
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter size of array: ");
        int size = sc.nextInt();

        int[] numbers = new int[size];

        System.out.println("Enter " + size + " numbers:");
        for (int i = 0; i < numbers.length; i++) {
            System.out.print("Enter number at index " + i + ": ");
            numbers[i] = sc.nextInt();
        }

        int largest = numbers[0];
        int smallest = numbers[0];

        for (int i = 1; i < numbers.length; i++) {
            if (numbers[i] > largest) {
                largest = numbers[i];
            }
            if (numbers[i] < smallest) {
                smallest = numbers[i];
            }
        }

        System.out.println("\nLargest number = " + largest);
        System.out.println("Smallest number = " + smallest);
        sc.close();
    }
}
Console Output
Enter size of array: 5 Enter 5 numbers: Enter number at index 0: 12 Enter number at index 1: 45 Enter number at index 2: 7 Enter number at index 3: 89 Enter number at index 4: 23 Largest number = 89 Smallest number = 7

Mini Project: Monkey's Banana Weights

Boss Monkey has collected bananas of different weights. He wants to find out which banana is the heaviest and which one is the lightest. You will create a program that solves this problem using arrays.


Tasks


Example Output

Console Output
Enter number of bananas: 5 Enter weight of banana 0: 2 Enter weight of banana 1: 5 Enter weight of banana 2: 3 Enter weight of banana 3: 6 Enter weight of banana 4: 4 Heaviest banana = 6 Lightest banana = 2 Total weight = 20 Average weight = 4.0

Closing

That's it for Arrays in Java. Arrays are like "Variables of variables" where we can store multiple data of the same type and run many operations on them.

← Previous 14 - Recursion in Java Next → 16 - Multidimensional Arrays in Java