Methods, Arrays, and Program Structure

Introduction to Arrays

ReadingPreview

আপনি একটি free preview lesson দেখছেন।

Lesson Overview

So far, when we needed multiple values, we often created multiple variables:

int firstScore =
        80;

int secondScore =
        90;

int thirdScore =
        75;

This works for a few values.

But what if we need:

10 scores
100 scores
1000 scores

Creating a separate variable for every value quickly becomes impractical।

This is where arrays become useful।

An array lets us store multiple values of the same type under one variable name।

Example:

int[] scores =
        new int[3];

Now one variable can hold three int values।

In this lesson, we will learn:

  • What an array is
  • Why arrays exist
  • Declaring arrays
  • Creating arrays
  • Array indexes
  • Reading elements
  • Updating elements
  • Default values
  • Array length
  • Array initializer syntax
  • Array references
  • Common indexing mistakes
  • Basic traversal
  • Arrays vs individual variables

What Is an Array?

An array is a fixed-size collection of values of the same type।

Example:

int[] scores =
        new int[3];

This creates space for:

3 integers

Conceptually:

scores
↓
+----+----+----+
| 0  | 0  | 0  |
+----+----+----+
  0    1    2

The numbers below are the indexes।


Arrays Store One Type

An int[] stores only values compatible with:

int

Example:

int[] numbers =
        new int[5];

You cannot store a String inside it:

numbers[0] =
        "Java";

This does not compile।

Java arrays are strongly typed।


Declaring an Array Variable

Basic syntax:

int[] numbers;

This declares a variable that can refer to an array of integers।

At this point, no array has been created yet।


Declaration vs Creation

These are separate operations।

Declaration:

int[] numbers;

Creation:

numbers =
        new int[5];

Together:

int[] numbers =
        new int[5];

This is the form you will use most often।


The new Keyword

new int[5]

creates a new array object capable of storing:

5 int values

The size is specified inside:

[5]

Array Size Is Fixed

Once created:

int[] numbers =
        new int[5];

the array always has five positions।

You cannot later make the same array object become:

10 elements

An array's size is fixed when it is created।

If you need a dynamically growing collection, Java collections such as:

ArrayList

will be more suitable later।


Array Indexes

Arrays use indexes to identify positions।

For:

int[] numbers =
        new int[5];

valid indexes are:

0
1
2
3
4

Notice:

The first index is 0.

Not:

1

Zero-Based Indexing

An array of length:

5

has indexes:

0 → first element
1 → second element
2 → third element
3 → fourth element
4 → fifth element

General rule:

Last valid index = length - 1

Setting Array Elements

Example:

int[] scores =
        new int[3];

scores[0] =
        80;

scores[1] =
        90;

scores[2] =
        75;

Conceptually:

+----+----+----+
| 80 | 90 | 75 |
+----+----+----+
  0    1    2

Reading an Element

To read the first value:

int firstScore =
        scores[0];

To print the second:

System.out.println(
        scores[1]
);

Output:

90

Updating an Element

Arrays are mutable।

Example:

scores[1] =
        95;

Before:

80 90 75

After:

80 95 75

The array object remains the same।

Its element at index 1 changed।


Complete Example

public class Main {

    public static void main(String[] args) {
        int[] scores =
                new int[3];

        scores[0] =
                80;

        scores[1] =
                90;

        scores[2] =
                75;

        System.out.println(
                scores[0]
        );

        System.out.println(
                scores[1]
        );

        System.out.println(
                scores[2]
        );
    }
}

Output:

80
90
75

Default Values

When Java creates an array, its elements receive default values।

Example:

int[] numbers =
        new int[3];

Before we assign anything:

numbers[0] = 0
numbers[1] = 0
numbers[2] = 0

Primitive Array Defaults

Common defaults:

byte     → 0
short    → 0
int      → 0
long     → 0
float    → 0.0
double   → 0.0
char     → '\u0000'
boolean  → false

Reference Array Defaults

For reference types:

String[] names =
        new String[3];

all elements initially contain:

null

Conceptually:

+------+------+
| null | null | null |
+------+------+

Example with Strings

String[] courses =
        new String[3];

System.out.println(
        courses[0]
);

Output:

null

Then:

courses[0] =
        "Java";

courses[1] =
        "Backend Development";

courses[2] =
        "System Design";

Now the array contains those references।


length

Every array has a:

length

field।

Example:

int[] numbers =
        new int[5];

System.out.println(
        numbers.length
);

Output:

5

Important:

numbers.length

not:

numbers.length()

Arrays use a field, not a method।


Last Valid Index

For:

int[] numbers =
        new int[5];

length:

5

last valid index:

numbers.length - 1

which is:

4

Common Index Error

This looks tempting:

numbers[numbers.length]

but it is invalid।

If length is:

5

then:

numbers[5]

is outside the array।

Valid indexes stop at:

4

ArrayIndexOutOfBoundsException

Example:

int[] numbers =
        new int[3];

System.out.println(
        numbers[3]
);

Valid indexes:

0
1
2

Index:

3

is invalid।

At runtime Java throws:

ArrayIndexOutOfBoundsException

Negative Indexes Are Also Invalid

This fails:

numbers[-1]

Java arrays do not support negative indexing।


Array Initializer Syntax

If you already know the values, you can create and initialize the array directly।

Example:

int[] scores = {
        80,
        90,
        75
};

Java automatically determines the length:

3

Equivalent Code

This:

int[] scores = {
        80,
        90,
        75
};

is conceptually similar to:

int[] scores =
        new int[3];

scores[0] =
        80;

scores[1] =
        90;

scores[2] =
        75;

The initializer is simply shorter and clearer when values are known upfront।


String Array Initializer

String[] courses = {
        "Java",
        "Backend Development",
        "System Design"
};

Length:

courses.length

is:

3

Alternative Explicit Initialization

You may also see:

int[] scores =
        new int[]{
                80,
                90,
                75
        };

This is valid।

When declaring the variable at the same time, the shorter form is usually clearer:

int[] scores = {
        80,
        90,
        75
};

You Cannot Specify Both Size and Values This Way

Invalid:

int[] numbers =
        new int[3]{
                1,
                2,
                3
        };

Choose either:

new int[3]

or:

new int[]{
        1,
        2,
        3
}

Array Variable Holds a Reference

Arrays are objects in Java।

This means:

int[] numbers =
        new int[3];

the variable:

numbers

holds a reference to the array object।

Conceptually:

numbers
   |
   v
+----+----+----+
| 0  | 0  | 0  |
+----+----+----+

Two Variables Can Reference the Same Array

Example:

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

int[] second =
        first;

Now both variables refer to the same array object।


Updating Through One Reference

second[0] =
        999;

Then:

System.out.println(
        first[0]
);

Output:

999

Why?

Because:

first

and:

second

refer to the same array।


Conceptually

Before:

first ----\
           → [10, 20, 30]
second ---/

After:

second[0] = 999;

both still point to:

[999, 20, 30]

No copy was created by:

int[] second =
        first;

Arrays Are Mutable Objects

This distinction is important:

The array reference can be copied.
The array object can still be changed.

Later we will study:

Defensive copying
Immutability
Reference semantics

in much more depth।


Comparing Array References with ==

Consider:

int[] first = {
        1,
        2,
        3
};

int[] second = {
        1,
        2,
        3
};

Then:

System.out.println(
        first == second
);

Output:

false

Why?

They are two different array objects।

== compares their references here।


Same Reference

int[] first = {
        1,
        2,
        3
};

int[] second =
        first;

Then:

first == second

is:

true

because both variables reference the same object।


Array Content Equality

To compare contents, Java provides utility methods such as:

Arrays.equals(
        first,
        second
);

We will cover the Arrays utility class in a later lesson।


Basic Array Traversal

Suppose:

int[] scores = {
        80,
        90,
        75
};

We can access each index manually:

System.out.println(
        scores[0]
);

System.out.println(
        scores[1]
);

System.out.println(
        scores[2]
);

But this does not scale well।

Loops are a better fit।


Traversing with for

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

Output:

80
90
75

Why Start at 0?

Because:

First array index = 0

Why i < scores.length?

Suppose:

length = 3

Then loop indexes are:

0
1
2

When:

i = 3

condition:

i < scores.length

becomes false।

So the loop stops before accessing invalid index 3


Classic Off-by-One Bug

Incorrect:

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

The condition:

i <= scores.length

eventually allows:

i == scores.length

which is not a valid index।

Correct:

i < scores.length

Enhanced for Loop Preview

Java also provides:

for (
        int score
        : scores
) {
    System.out.println(
            score
    );
}

This is called an:

enhanced for loop

or:

for-each loop

We will explore array traversal properly in the next lesson।


Index vs Value

In:

for (
        int i = 0;
        i < scores.length;
        i++
)

i represents:

index

In:

for (
        int score
        : scores
)

score represents:

element value

This distinction becomes important when you need to update positions।


Updating Every Element

Using indexes:

int[] numbers = {
        1,
        2,
        3
};

for (
        int i = 0;
        i < numbers.length;
        i++
) {
    numbers[i] =
            numbers[i] * 2;
}

Result:

2
4
6

Indexes let us modify specific array positions directly।


Array Size Can Come from a Variable

Example:

int size =
        5;

int[] numbers =
        new int[size];

This is valid।

The size is evaluated when the array is created।


Size Must Be an Integer-Compatible Value

Valid:

int size =
        10;

String[] names =
        new String[size];

Not:

double size =
        10.5;

String[] names =
        new String[size];

Array length must be an integer-compatible size।


Zero-Length Arrays

This is valid:

int[] numbers =
        new int[0];

Then:

numbers.length

is:

0

But there are no valid indexes।

Trying:

numbers[0]

fails।

Zero-length arrays can be useful to represent:

No values

without using null


Negative Array Size

This compiles:

int size =
        -1;

int[] numbers =
        new int[size];

but fails at runtime with:

NegativeArraySizeException

because array size cannot be negative।


Array Variables Can Be null

Because arrays are reference types:

int[] numbers =
        null;

is valid。

But then:

numbers.length

throws:

NullPointerException

because there is no array object to access।


Empty Array vs null

These are very different:

int[] first =
        new int[0];

and:

int[] second =
        null;

first refers to a valid array with zero elements।

second refers to no array at all।

Generally, an empty array is easier to work with than null when "no elements" is a valid state।


Arrays and Methods

Arrays can be passed to methods।

Example:

static void printFirst(
        int[] numbers
) {
    System.out.println(
            numbers[0]
    );
}

Call:

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

printFirst(
        values
);

Output:

10

Java Still Passes by Value

Remember:

Java is always pass-by-value.

For an array parameter, the copied value is the array reference।

Example:

static void changeFirst(
        int[] numbers
) {
    numbers[0] =
            999;
}

Caller:

int[] values = {
        10,
        20
};

changeFirst(
        values
);

System.out.println(
        values[0]
);

Output:

999

Why Did the Caller Change?

Because the method received a copy of the reference pointing to the same mutable array object।

Conceptually:

values --------\
                → [10, 20]
numbers -------/

Then:

numbers[0] = 999;

modifies that shared array object।


Reassigning the Parameter Is Different

Example:

static void replaceArray(
        int[] numbers
) {
    numbers =
            new int[]{
                    100,
                    200
            };
}

Caller:

int[] values = {
        10,
        20
};

replaceArray(
        values
);

System.out.println(
        values[0]
);

Output:

10

Why?

The local parameter variable:

numbers

was reassigned।

The caller variable:

values

still points to the original array।


Returning Arrays from Methods

A method can return an array।

Example:

static int[] createScores() {
    return new int[]{
            80,
            90,
            75
    };
}

Usage:

int[] scores =
        createScores();

Now scores references the returned array।


Example: Create Array with Size

static int[] createNumbers(
        int size
) {
    if (size < 0) {
        throw new IllegalArgumentException(
                "Size cannot be negative."
        );
    }

    return new int[size];
}

Usage:

int[] numbers =
        createNumbers(
                5
        );

Printing an Array Directly

A common surprise:

int[] numbers = {
        1,
        2,
        3
};

System.out.println(
        numbers
);

You may see something similar to:

[I@3fee733d

instead of:

[1, 2, 3]

Why?

Arrays do not override toString() to display their contents in the way beginners often expect।


Printing Contents Properly

Use:

Arrays.toString(
        numbers
);

Example:

import java.util.Arrays;

public class Main {

    public static void main(String[] args) {
        int[] numbers = {
                1,
                2,
                3
        };

        System.out.println(
                Arrays.toString(
                        numbers
                )
        );
    }
}

Output:

[1, 2, 3]

We'll study Arrays methods properly in a later lesson।


Individual Variables vs Array

Without array:

int score1 =
        80;

int score2 =
        90;

int score3 =
        75;

Calculating total:

int total =
        score1
        + score2
        + score3;

With array:

int[] scores = {
        80,
        90,
        75
};

Now the same program can use iteration।


Arrays Are Useful When

Use arrays when:

You have multiple values
All values share one element type
The number of positions is fixed or known
Index-based access matters
You want compact contiguous storage

Arrays Are Less Convenient When

Arrays become less convenient when:

Size changes frequently
You need frequent insertion/removal
You need key-value lookup
You need uniqueness semantics

Java Collections Framework gives better structures for those requirements।


Array Element Types

Arrays can contain primitives:

int[] numbers;
double[] prices;
boolean[] flags;
char[] letters;

or references:

String[] names;
Course[] courses;
Learner[] learners;

We will understand arrays of custom objects after learning classes and objects।


Array Syntax Style

Java technically permits:

int numbers[];

But preferred modern Java style is:

int[] numbers;

Why?

It communicates:

The type is int[]

more clearly।

Use:

int[] numbers;

consistently।


Multiple Variable Declaration Trap

Consider:

int[] first,
      second;

Both are arrays।

But:

int first[],
    second;

means:

first  → int[]
second → int

This style can be confusing।

Another reason to prefer:

int[] first;
int[] second;

Common Beginner Mistake 1: Starting at Index 1

Incorrect assumption:

scores[1]

is the first element।

Actually:

scores[0]

is first।


Common Beginner Mistake 2: Accessing length

Incorrect:

scores.length()

Correct:

scores.length

Common Beginner Mistake 3: Using <=

Incorrect traversal:

for (
        int i = 0;
        i <= scores.length;
        i++
)

Correct:

for (
        int i = 0;
        i < scores.length;
        i++
)

Common Beginner Mistake 4: Assuming Assignment Copies Contents

int[] second =
        first;

does not create a second independent array।

Both variables reference the same array object।


Common Beginner Mistake 5: Printing the Array Reference

System.out.println(
        numbers
);

does not normally print element contents।

Use traversal or:

Arrays.toString(
        numbers
);

Common Beginner Mistake 6: Forgetting Default Values

After:

boolean[] flags =
        new boolean[3];

the array does not contain undefined garbage।

It contains:

false
false
false

Common Beginner Mistake 7: Confusing Empty with null

new int[0]

is a valid array।

null

means no array object exists।


Practical Example: Student Scores

public class Main {

    public static void main(String[] args) {
        int[] scores = {
                82,
                91,
                76,
                88
        };

        System.out.println(
                "First score: "
                + scores[0]
        );

        System.out.println(
                "Last score: "
                + scores[
                        scores.length - 1
                ]
        );

        scores[2] =
                80;

        System.out.println(
                "Total students: "
                + scores.length
        );
    }
}

Practical Example: Course Names

public class Main {

    public static void main(String[] args) {
        String[] courses = {
                "Java and OOP Foundation",
                "Backend Development",
                "System Design"
        };

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

Output:

0: Java and OOP Foundation
1: Backend Development
2: System Design

Practice 1: Create an Array

Create an int array containing:

10
20
30
40
50

Then print the third element।


Solution

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

System.out.println(
        numbers[2]
);

Output:

30

Practice 2: Update an Element

Given:

String[] courses = {
        "Java",
        "Python",
        "Go"
};

replace:

Python

with:

Backend Development

Solution

courses[1] =
        "Backend Development";

Practice 3: Find the Last Element

Given:

int[] numbers = {
        5,
        10,
        15,
        20
};

print the last element without hard-coding index 3


Solution

System.out.println(
        numbers[
                numbers.length - 1
        ]
);

Practice 4: Predict the Output

int[] first = {
        10,
        20
};

int[] second =
        first;

second[1] =
        99;

System.out.println(
        first[1]
);

Answer

99

Both variables reference the same array।


Practice 5: Default Values

What does this print?

String[] names =
        new String[2];

System.out.println(
        names[0]
);

Answer

null

Practice 6: Identify the Bug

int[] numbers =
        new int[5];

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

Answer

The loop eventually accesses:

numbers[5]

which is outside the valid range।

Use:

i < numbers.length

Practice 7: Method and Array

Write:

static int first(
        int[] numbers
)

that returns the first element।


Possible Solution

static int first(
        int[] numbers
) {
    return numbers[0];
}

A production-quality version should also decide what should happen when:

numbers == null
numbers.length == 0

We'll improve validation later।


True or False

  1. Arrays can store multiple values under one variable.
  2. An array may contain values of unrelated types.
  3. Array indexes start at 0.
  4. An array of length 5 has a valid index 5.
  5. Array size is fixed after creation.
  6. numbers.length() returns array length.
  7. Primitive arrays receive default element values.
  8. String[] elements default to null.
  9. Assigning one array variable to another copies every element.
  10. Arrays are reference types.
  11. An array can be passed to a method.
  12. new int[0] is valid Java.

Answers

1. True
2. False
3. True
4. False
5. True
6. False
7. True
8. True
9. False
10. True
11. True
12. True

Knowledge Check

Question 1

What is an array?

Question 2

Why do array indexes start at 0 matter when writing loops?

Question 3

What is the last valid index of an array?

Question 4

What does new int[5] do?

Question 5

What are the initial values inside a newly created int[]?

Question 6

What are the initial values inside a newly created String[]?

Question 7

What is the difference between array length and last index?

Question 8

What happens if you access an invalid array index?

Question 9

Does assigning one array variable to another create a copy?

Question 10

Why can a method modify an array passed as an argument?

Question 11

What is the difference between an empty array and null?

Question 12

When might an array be preferable to a dynamically growing collection?


Knowledge Check Answers

Answer 1

An array is a fixed-size Java object that stores multiple values of one compatible element type।

Answer 2

The first element is index 0, so traversal normally begins at 0 and stops before length

Answer 3

length - 1

Answer 4

It creates a new array object containing space for five int elements।

Answer 5

Each element starts as:

0

Answer 6

Each element starts as:

null

Answer 7

If length is 5, there are five elements but the last index is 4 because indexing begins at zero।

Answer 8

Java throws:

ArrayIndexOutOfBoundsException

at runtime।

Answer 9

No. It copies the reference, so both variables normally refer to the same array object।

Answer 10

The method receives a copy of the reference to the same mutable array object, so element changes are visible through the caller's reference too।

Answer 11

An empty array is a valid object with length 0; null means no array object is referenced।

Answer 12

When the number of positions is fixed or known and efficient index-based access is useful।


Lesson Summary

এই lesson-এ আমরা Java arrays-এর foundation শিখেছি।

We learned:

  • An array stores multiple values of one element type
  • Arrays are fixed-size
  • Array variables are reference variables
  • Arrays are created using new
  • Array indexing starts at 0
  • Last valid index is length - 1
  • Elements can be read and updated through indexes
  • Primitive arrays receive default values
  • Reference arrays default to null
  • Arrays expose a length field
  • Initializer syntax can create arrays concisely
  • Invalid indexes cause ArrayIndexOutOfBoundsException
  • Negative sizes cause NegativeArraySizeException
  • Array variables can be null
  • Empty arrays and null are different
  • Assigning an array reference does not copy its elements
  • Multiple references can point to the same mutable array
  • Arrays can be passed to and returned from methods
  • Java remains pass-by-value even for arrays
  • Basic traversal normally uses i < array.length
  • Arrays are useful when size is fixed and index access matters

The central model is:

Array variable
↓
Reference
↓
Fixed-size sequence of indexed elements

Next Lesson

পরবর্তী lesson:

Traversing and Working with Arrays

আমরা শিখব:

  • Indexed for loops
  • Enhanced for loops
  • Reading vs modifying elements
  • Calculating sum and average
  • Finding minimum and maximum
  • Searching manually
  • Counting and filtering
  • Reversing an array
  • Copying arrays safely
  • Common traversal patterns