15 Java Fundamentals | Arrays in Java | By Dummy for Dummies

Java Arrays | Hassan Bukhari
Java Notes

15 Java Fundamentals | Arrays in Java | By Dummy for Dummies

Java Beginner Guide Arrays Indexing Collections

INTRODUCTION

Imagine you have money, you put the money in a wallet. It is like putting data in a variable. Now if you have a lot of wallets (definitely not stolen), and you put them all in a bag. That will be like putting all variables in another variable. That is exactly what Arrays are, variable 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:

  • int → It tells the program about the datatype of the array we want to create. Just like we did in making simple variables.
  • [] → It tells the program that the datatype is actually Array of Integers rather than just a variable of integer.
  • new int[5] → Think of it as just another magical spell you don't need to explore more right now. Just the datatype must match what we want to create. The important thing here is the number inside square brackets [5]. It tells the program the number of data the array will keep. It is also called the length of the array.

The array is now created but it is actually empty. Its length is 5, which means it can store 5 variables or data inside itself. Each data has a specific index; think of index as a roll number. But instead of 1, roll numbers in Arrays start from 0. Therefore this array we created can store 5 variables, and their roll numbers will be 0, 1, 2, 3 and 4. We cannot print the whole array at once like other variables; we must access each data specifically through their index (roll no). It will be like numbers[index]. Replace the index with the roll number you want to access.

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 then putting data in, we can put data directly into the array. Here is the Java magical spell for that:

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

Here we just write the data directly without telling any size for it. But it isn't that much useful since most of the time we require flexible code rather than hard-coded data. Still, you should know about its existence.

We can print the data inside an array using a for loop rather than printing data on each index manually. In that case, we will start from the first index and reach the last index using a for loop. For this program, you could just start from 1 and end it before 6, but we have a more flexible method. Why not somehow know the exact length of any array and stop at the last index (length - 1)? Fortunately, we can know the length through arrayName.length and make use of it. Here is 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

  • Create a class BananaWeights.
  • In the main method:
  • 1. Ask the user how many bananas there are.
  • 2. Take input for each banana's weight and store it in an array.
  • 3. Write logic to find the total and average weight from the array.
  • 4. Print the results neatly.

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.