Methods, Arrays, and Program Structure

Practice and Assessment

ReadingPreview

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

Module Overview

এই module-এ আমরা procedural Java programming-এর সবচেয়ে গুরুত্বপূর্ণ foundationগুলোর একটি তৈরি করেছি।

আমরা শিখেছি:

Methods
Parameters
Arguments
Return values
Scope
static
Method overloading
Arrays
Array traversal
2D arrays
Multidimensional arrays
java.util.Arrays
Recursion

এখন goal হলো শুধু syntax মনে রাখা নয়।

আপনাকে prove করতে হবে যে আপনি:

Problemকে ছোট methods-এ ভাঙতে পারেন
Data array-এ organize করতে পারেন
Loops দিয়ে array process করতে পারেন
Built-in APIs ব্যবহার করতে পারেন
Recursive execution reason করতে পারেন

এই assessment চারটি অংশে ভাগ করা হয়েছে:

  1. Concept Review
  2. Code Reading and Debugging
  3. Implementation Challenges
  4. Final Module Project

Part 1 — Concept Review

Question 1

Method declaration এবং method call-এর মধ্যে difference কী?


Question 2

এই code-এ parameter কোনটি এবং argument কোনটি?

static void greet(
        String name
) {
    System.out.println(
            name
    );
}

greet(
        "Sakib"
);

Question 3

void method এবং value-returning method-এর difference কী?


Question 4

এই method-এর return type কী?

static boolean isAdult(
        int age
) {
    return age >= 18;
}

Question 5

Java কি pass-by-reference ব্যবহার করে?


Question 6

এই variable কোথায় accessible?

static void calculate() {
    int total =
            100;
}

Question 7

static method-এর basic meaning কী?


Question 8

Method overloading কী?


Question 9

এই methods কি valid overload?

static void print(
        int value
) {
}

static void print(
        long value
) {
}

Question 10

এই methods কি valid overload?

static int value() {
    return 10;
}

static String value() {
    return "10";
}

Question 11

Array-এর first index কী?


Question 12

Length 10 হলে last valid index কত?


Question 13

Difference কী?

int[] first =
        new int[0];

int[] second =
        null;

Question 14

এই assignment কি array copy করে?

int[] second =
        first;

Question 15

Enhanced for loop কখন indexed for loop-এর চেয়ে ভালো choice?


Question 16

Primitive array element enhanced for loop দিয়ে এভাবে change করলে original array কেন change হয় না?

for (
        int value
        : numbers
) {
    value =
            0;
}

Question 17

2D array আসলে কী?


Question 18

Difference explain করুন:

matrix.length

and:

matrix[row].length

Question 19

Jagged array কী?


Question 20

Difference কী?

Arrays.toString(...)

and:

Arrays.deepToString(...)

Question 21

Arrays.sort() original array modify করে কি?


Question 22

Arrays.binarySearch() ব্যবহার করার আগে সবচেয়ে important requirement কী?


Question 23

Recursion-এর দুইটি essential component কী?


Question 24

Infinite recursion সাধারণত কী runtime failure তৈরি করতে পারে?


Question 25

সব loop-based problem recursion দিয়ে rewrite করা technically possible হলেও কেন সবসময় করা উচিত নয়?


Part 1 — Answers

Answer 1

Method declaration define করে method কী করবে।

Method call সেই method execute করে।


Answer 2

Parameter:

String name

Argument:

"Sakib"

Answer 3

void method কোনো result value caller-এর কাছে return করে না।

Value-returning method declared type-এর একটি result return করে।


Answer 4

boolean

Answer 5

না।

Java always uses:

pass-by-value

Object এবং array arguments-এর ক্ষেত্রে copied value হলো reference।


Answer 6

শুধু calculate() method-এর local scope-এর মধ্যে।


Answer 7

static member class-এর সঙ্গে associated, specific object instance-এর সঙ্গে নয়।


Answer 8

একই method name ব্যবহার করে different parameter lists-এর multiple methods define করা।


Answer 9

হ্যাঁ।

Signatures:

print(int)
print(long)

different।


Answer 10

না।

Return type alone overload distinguish করতে পারে না।


Answer 11

0

Answer 12

9

General rule:

length - 1

Answer 13

new int[0]

একটি valid empty array object।

null

মানে কোনো array object referenced নয়।


Answer 14

না।

এটি reference copy করে।

দুই variable একই array object reference করতে পারে।


Answer 15

যখন শুধু values process করতে হবে এবং index বা direct position update দরকার নেই।


Answer 16

value প্রতিটি primitive element-এর একটি local copy পায়।

Local variable reassign করলে array position replace হয় না।


Answer 17

একটি array যার elements নিজেরাই arrays।

Example:

int[][]

is conceptually:

array of int[]

Answer 18

matrix.length

outer array-এর length, সাধারণত row count।

matrix[row].length

specific row-এর element count।


Answer 19

যে multidimensional array-এ different rows-এর lengths different হতে পারে।


Answer 20

Arrays.toString() সাধারণত one-dimensional array-এর readable representation দেয়।

Arrays.deepToString() nested arrays recursively format করে।


Answer 21

হ্যাঁ।

Arrays.sort() array-কে in place sort করে।


Answer 22

Input data expected ordering অনুযায়ী sorted হতে হবে।


Answer 23

Base case
Recursive case

Answer 24

StackOverflowError

Answer 25

কারণ simple sequential work-এর জন্য loops সাধারণত:

Simpler
More readable
Constant stack depth
More operationally predictable

Recursion তখন বেশি natural যখন problem structure নিজেই recursive।


Part 2 — Code Reading and Debugging

Challenge 1 — Predict the Output

public class Main {

    public static void main(String[] args) {
        int result =
                calculate(
                        5
                );

        System.out.println(
                result
        );
    }

    static int calculate(
            int value
    ) {
        return value
                * 2;
    }
}

Answer

10

Challenge 2 — Find the Compilation Error

static int add(
        int first,
        int second
) {
    System.out.println(
            first + second
    );
}

Problem

Method declares:

int

but does not return an int

Fix

static int add(
        int first,
        int second
) {
    return first + second;
}

Challenge 3 — Predict Scope Behavior

static void first() {
    int number =
            10;

    System.out.println(
            number
    );
}

static void second() {
    int number =
            20;

    System.out.println(
            number
    );
}

Is this valid?

Answer

Yes।

Each number belongs to a different method scope।


Challenge 4 — Find the Scope Error

static void process() {
    if (true) {
        String message =
                "Done";
    }

    System.out.println(
            message
    );
}

Problem

message only exists inside the if block।


Challenge 5 — Valid Overload?

static void show(
        String value
) {
}

static void show(
        String text
) {
}

Answer

No।

Both signatures are:

show(String)

Parameter variable names do not matter।


Challenge 6 — Predict the Array Result

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

int[] second =
        first;

second[0] =
        99;

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

Answer

99

Both references point to the same array।


Challenge 7 — Find the Index Bug

int[] numbers =
        new int[5];

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

Problem

When:

i == 5

the loop attempts:

numbers[5]

which is invalid।

Fix

i < numbers.length

Challenge 8 — Predict the Output

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

for (
        int number
        : numbers
) {
    number +=
            100;
}

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

Answer

[10, 20, 30]

Challenge 9 — Fix the Maximum Algorithm

static int max(
        int[] numbers
) {
    int max =
            0;

    for (
            int number
            : numbers
    ) {
        if (
                number > max
        ) {
            max =
                    number;
        }
    }

    return max;
}

Why can this fail?

Answer

For:

{-10, -5, -20}

it returns:

0

even though 0 is not in the array।

Better:

static int max(
        int[] numbers
) {
    if (
            numbers.length == 0
    ) {
        throw new IllegalArgumentException(
                "Array cannot be empty."
        );
    }

    int max =
            numbers[0];

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

    return max;
}

Challenge 10 — 2D Array Output

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

System.out.println(
        values.length
);

System.out.println(
        values[1].length
);

Answer

2
3

Challenge 11 — Find the Jagged Array Bug

for (
        int row = 0;
        row < values.length;
        row++
) {
    for (
            int column = 0;
            column < values[0].length;
            column++
    ) {
        System.out.println(
                values[row][column]
        );
    }
}

Problem

It assumes every row has the same length as:

values[0]

Correct:

column < values[row].length

Challenge 12 — Array Equality

int[] first = {
        1,
        2
};

int[] second = {
        1,
        2
};

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

System.out.println(
        Arrays.equals(
                first,
                second
        )
);

Answer

false
true

Challenge 13 — Sorting Mutation

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

Arrays.sort(
        numbers
);

What is numbers now?

Answer

[1, 2, 3]

The original array was mutated।


Challenge 14 — Binary Search Bug

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

int result =
        Arrays.binarySearch(
                numbers,
                20
        );

What is wrong with the design?

Answer

The array is not sorted।

Binary search's ordering precondition is violated।


Challenge 15 — Recursive Output

static void show(
        int number
) {
    if (
            number == 0
    ) {
        return;
    }

    System.out.print(
            number
            + " "
    );

    show(
            number - 1
    );

    System.out.print(
            number
            + " "
    );
}

Call:

show(
        3
);

Answer

3 2 1 1 2 3

Challenge 16 — Infinite Recursion

static int sum(
        int number
) {
    if (
            number == 0
    ) {
        return 0;
    }

    return number
            + sum(
                    number
            );
}

Problem

The recursive argument does not become smaller।

Correct:

sum(
        number - 1
);

Part 3 — Implementation Challenges

Try each problem independently before reading the solution।


Challenge 1 — Calculate Total Price

Implement:

static long calculateTotal(
        long unitPrice,
        int quantity
)

Requirements:

unitPrice cannot be negative
quantity cannot be negative
return unitPrice × quantity

Solution

static long calculateTotal(
        long unitPrice,
        int quantity
) {
    if (
            unitPrice < 0
    ) {
        throw new IllegalArgumentException(
                "Unit price cannot be negative."
        );
    }

    if (
            quantity < 0
    ) {
        throw new IllegalArgumentException(
                "Quantity cannot be negative."
        );
    }

    return unitPrice
            * quantity;
}

Challenge 2 — Overloaded Greeting

Create:

greet()
greet(String name)

No-argument version should use:

Guest

Solution

static void greet() {
    greet(
            "Guest"
    );
}

static void greet(
        String name
) {
    System.out.println(
            "Hello, "
            + name
            + "!"
    );
}

Challenge 3 — Sum Positive Numbers

Given:

int[] numbers = {
        -5,
        10,
        20,
        -3,
        7
};

return the sum of positive values only।

Expected:

37

Solution

static int sumPositive(
        int[] numbers
) {
    int total =
            0;

    for (
            int number
            : numbers
    ) {
        if (
                number > 0
        ) {
            total +=
                    number;
        }
    }

    return total;
}

Challenge 4 — Count Values in Range

Implement:

static int countInRange(
        int[] numbers,
        int minimum,
        int maximum
)

Count values where:

minimum <= value <= maximum

Solution

static int countInRange(
        int[] numbers,
        int minimum,
        int maximum
) {
    if (
            minimum > maximum
    ) {
        throw new IllegalArgumentException(
                "Minimum cannot be greater than maximum."
        );
    }

    int count =
            0;

    for (
            int number
            : numbers
    ) {
        if (
                number >= minimum
                && number <= maximum
        ) {
            count++;
        }
    }

    return count;
}

Challenge 5 — Find First Index

Implement:

static int indexOf(
        String[] values,
        String target
)

Return:

-1

if not found।


Solution

static int indexOf(
        String[] values,
        String target
) {
    for (
            int i = 0;
            i < values.length;
            i++
    ) {
        if (
                values[i].equals(
                        target
                )
        ) {
            return i;
        }
    }

    return -1;
}

Challenge 6 — Reverse Copy

Implement:

static int[] reversedCopy(
        int[] values
)

The original array must remain unchanged।


Solution

static int[] reversedCopy(
        int[] values
) {
    int[] result =
            new int[
                    values.length
            ];

    for (
            int i = 0;
            i < values.length;
            i++
    ) {
        result[
                values.length
                - 1
                - i
        ] =
                values[i];
    }

    return result;
}

Challenge 7 — Check Palindrome Array

An array is a palindrome when it reads the same forwards and backwards।

Example:

1 2 3 2 1

Implement:

static boolean isPalindrome(
        int[] values
)

Solution

static boolean isPalindrome(
        int[] values
) {
    int left =
            0;

    int right =
            values.length - 1;

    while (
            left < right
    ) {
        if (
                values[left]
                != values[right]
        ) {
            return false;
        }

        left++;
        right--;
    }

    return true;
}

Challenge 8 — Find Second Row Average

Given:

int[][] scores = {
        {80, 90, 85},
        {70, 75, 80},
        {95, 88, 92}
};

calculate average of row 1


Solution

static double average(
        int[] values
) {
    if (
            values.length == 0
    ) {
        throw new IllegalArgumentException(
                "Values cannot be empty."
        );
    }

    int total =
            0;

    for (
            int value
            : values
    ) {
        total +=
                value;
    }

    return (double) total
            / values.length;
}

Call:

double result =
        average(
                scores[1]
        );

Result:

75.0

Challenge 9 — Count All Cells

Implement:

static int countElements(
        int[][] values
)

It must work for jagged arrays।


Solution

static int countElements(
        int[][] values
) {
    int count =
            0;

    for (
            int[] row
            : values
    ) {
        count +=
                row.length;
    }

    return count;
}

Challenge 10 — Maximum Across 2D Data

Implement:

static int max(
        int[][] values
)

Allow empty rows, but reject a structure containing no actual values।


Solution

static int max(
        int[][] values
) {
    boolean found =
            false;

    int max =
            0;

    for (
            int[] row
            : values
    ) {
        for (
                int value
                : row
        ) {
            if (
                    !found
                    || value > max
            ) {
                max =
                        value;

                found =
                        true;
            }
        }
    }

    if (!found) {
        throw new IllegalArgumentException(
                "No values available."
        );
    }

    return max;
}

Challenge 11 — Sorted Copy

Implement:

static int[] sortedCopy(
        int[] values
)

using java.util.Arrays

Original must remain unchanged।


Solution

static int[] sortedCopy(
        int[] values
) {
    int[] result =
            Arrays.copyOf(
                    values,
                    values.length
            );

    Arrays.sort(
            result
    );

    return result;
}

Challenge 12 — Binary Search Wrapper

Implement:

static boolean containsSorted(
        int[] sortedValues,
        int target
)

Assume input is already sorted।


Solution

static boolean containsSorted(
        int[] sortedValues,
        int target
) {
    return Arrays.binarySearch(
            sortedValues,
            target
    ) >= 0;
}

Challenge 13 — Recursive Sum

Implement recursively:

static int sumTo(
        int number
)

Expected:

sumTo(5) = 15

Solution

static int sumTo(
        int number
) {
    if (
            number < 0
    ) {
        throw new IllegalArgumentException(
                "Number cannot be negative."
        );
    }

    if (
            number == 0
    ) {
        return 0;
    }

    return number
            + sumTo(
                    number - 1
            );
}

Challenge 14 — Recursive Array Search

Implement:

static boolean containsRecursive(
        int[] values,
        int target
)

without exposing an index parameter to callers।


Solution

static boolean containsRecursive(
        int[] values,
        int target
) {
    return containsRecursive(
            values,
            target,
            0
    );
}

static boolean containsRecursive(
        int[] values,
        int target,
        int index
) {
    if (
            index == values.length
    ) {
        return false;
    }

    if (
            values[index] == target
    ) {
        return true;
    }

    return containsRecursive(
            values,
            target,
            index + 1
    );
}

Challenge 15 — Recursive Reverse Printing

Given:

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

print:

System Design
Backend
Java

using recursion without modifying the array।


Solution

static void printReverse(
        String[] values
) {
    printReverse(
            values,
            values.length - 1
    );
}

static void printReverse(
        String[] values,
        int index
) {
    if (
            index < 0
    ) {
        return;
    }

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

    printReverse(
            values,
            index - 1
    );
}

Part 4 — Final Module Project

Student Score Analyzer

Build a console-independent Java program that analyzes student scores।

Use this data:

String[] students = {
        "Sakib",
        "Subu",
        "Sumu",
        "Nur"
};

int[][] scores = {
        {82, 91, 78},
        {95, 88, 92},
        {76, 84, 80},
        {60, 72, 68}
};

Interpretation:

Each row belongs to one student.
Each column represents one exam score.

Required Features

Your program must:

  1. Print every student's name and scores
  2. Calculate each student's total
  3. Calculate each student's average
  4. Find each student's highest score
  5. Find the overall highest score
  6. Find the student with the highest average
  7. Count how many individual scores are 80 or higher
  8. Create a sorted copy of each student's scores
  9. Keep the original score arrays unchanged during sorting
  10. Search whether a student has a score of exactly 91
  11. Use multiple focused methods rather than one giant main()

Suggested Method Design

You may create methods such as:

static int sum(
        int[] scores
)

static double average(
        int[] scores
)

static int max(
        int[] scores
)

static int overallMax(
        int[][] scores
)

static int countAtLeast(
        int[][] scores,
        int threshold
)

static boolean contains(
        int[] scores,
        int target
)

static int[] sortedCopy(
        int[] scores
)

static int indexOfHighestAverage(
        int[][] scores
)

static void printStudentReport(
        String name,
        int[] scores
)

You do not have to follow these exact names, but responsibilities should remain clear।


One Possible Complete Solution

import java.util.Arrays;

public class Main {

    public static void main(String[] args) {
        String[] students = {
                "Sakib",
                "Subu",
                "Sumu",
                "Nur"
        };

        int[][] scores = {
                {82, 91, 78},
                {95, 88, 92},
                {76, 84, 80},
                {60, 72, 68}
        };

        for (
                int i = 0;
                i < students.length;
                i++
        ) {
            printStudentReport(
                    students[i],
                    scores[i]
            );
        }

        System.out.println(
                "Overall highest score: "
                + overallMax(
                        scores
                )
        );

        int bestStudentIndex =
                indexOfHighestAverage(
                        scores
                );

        System.out.println(
                "Highest average: "
                + students[
                        bestStudentIndex
                ]
        );

        System.out.println(
                "Scores >= 80: "
                + countAtLeast(
                        scores,
                        80
                )
        );

        System.out.println(
                "Sakib has 91: "
                + contains(
                        scores[0],
                        91
                )
        );
    }

    static void printStudentReport(
            String name,
            int[] scores
    ) {
        System.out.println(
                "Student: "
                + name
        );

        System.out.println(
                "Scores: "
                + Arrays.toString(
                        scores
                )
        );

        System.out.println(
                "Total: "
                + sum(
                        scores
                )
        );

        System.out.println(
                "Average: "
                + average(
                        scores
                )
        );

        System.out.println(
                "Highest: "
                + max(
                        scores
                )
        );

        int[] sorted =
                sortedCopy(
                        scores
                );

        System.out.println(
                "Sorted: "
                + Arrays.toString(
                        sorted
                )
        );

        System.out.println();
    }

    static int sum(
            int[] scores
    ) {
        int total =
                0;

        for (
                int score
                : scores
        ) {
            total +=
                    score;
        }

        return total;
    }

    static double average(
            int[] scores
    ) {
        if (
                scores.length == 0
        ) {
            throw new IllegalArgumentException(
                    "Scores cannot be empty."
            );
        }

        return (double) sum(
                scores
        ) / scores.length;
    }

    static int max(
            int[] scores
    ) {
        if (
                scores.length == 0
        ) {
            throw new IllegalArgumentException(
                    "Scores cannot be empty."
            );
        }

        int max =
                scores[0];

        for (
                int i = 1;
                i < scores.length;
                i++
        ) {
            if (
                    scores[i] > max
            ) {
                max =
                        scores[i];
            }
        }

        return max;
    }

    static int overallMax(
            int[][] scores
    ) {
        boolean found =
                false;

        int max =
                0;

        for (
                int[] studentScores
                : scores
        ) {
            for (
                    int score
                    : studentScores
            ) {
                if (
                        !found
                        || score > max
                ) {
                    max =
                            score;

                    found =
                            true;
                }
            }
        }

        if (!found) {
            throw new IllegalArgumentException(
                    "No scores available."
            );
        }

        return max;
    }

    static int countAtLeast(
            int[][] scores,
            int threshold
    ) {
        int count =
                0;

        for (
                int[] studentScores
                : scores
        ) {
            for (
                    int score
                    : studentScores
            ) {
                if (
                        score >= threshold
                ) {
                    count++;
                }
            }
        }

        return count;
    }

    static boolean contains(
            int[] scores,
            int target
    ) {
        for (
                int score
                : scores
        ) {
            if (
                    score == target
            ) {
                return true;
            }
        }

        return false;
    }

    static int[] sortedCopy(
            int[] scores
    ) {
        int[] copy =
                Arrays.copyOf(
                        scores,
                        scores.length
                );

        Arrays.sort(
                copy
        );

        return copy;
    }

    static int indexOfHighestAverage(
            int[][] scores
    ) {
        if (
                scores.length == 0
        ) {
            throw new IllegalArgumentException(
                    "Scores cannot be empty."
            );
        }

        int bestIndex =
                0;

        double bestAverage =
                average(
                        scores[0]
                );

        for (
                int i = 1;
                i < scores.length;
                i++
        ) {
            double currentAverage =
                    average(
                            scores[i]
                    );

            if (
                    currentAverage
                    > bestAverage
            ) {
                bestAverage =
                        currentAverage;

                bestIndex =
                        i;
            }
        }

        return bestIndex;
    }
}

What This Project Tests

This small project combines:

Methods
Parameters
Return values
Scope
Arrays
2D arrays
Traversal
Accumulation
Searching
Maximum selection
Array copying
Arrays.sort()
Method reuse
Separation of responsibilities

Notice that main() does not contain every algorithm directly।

Instead:

sum(...)
average(...)
max(...)
contains(...)
sortedCopy(...)

give meaningful names to separate operations।

That is the direction we want।


Bonus Challenge 1 — Subject Averages

For:

int[][] scores

calculate the average of each column।

Assume rectangular input।

Example:

Student 1 → 80 90 70
Student 2 → 60 80 90

Subject 0 average:

70

Subject 1 average:

85

Subject 2 average:

80

Bonus Challenge 2 — Transpose

Convert:

1 2 3
4 5 6

into:

1 4
2 5
3 6

using a new array।


Bonus Challenge 3 — Recursive Maximum

Implement array maximum using recursion rather than a loop।


Bonus Challenge 4 — Recursive Palindrome

Implement:

static boolean isPalindrome(
        int[] values
)

recursively using two indexes:

left
right

Possible Recursive Palindrome Solution

static boolean isPalindrome(
        int[] values
) {
    return isPalindrome(
            values,
            0,
            values.length - 1
    );
}

static boolean isPalindrome(
        int[] values,
        int left,
        int right
) {
    if (
            left >= right
    ) {
        return true;
    }

    if (
            values[left]
            != values[right]
    ) {
        return false;
    }

    return isPalindrome(
            values,
            left + 1,
            right - 1
    );
}

Final Debugging Checklist

Before considering your solution complete, ask:

Methods

  • Does each method have one clear responsibility?
  • Are method names meaningful?
  • Are parameter types appropriate?
  • Does every non-void path return a value?
  • Am I passing data explicitly rather than relying on unnecessary global state?

Scope

  • Are local variables declared close to where they are used?
  • Am I accidentally trying to access variables outside their scope?
  • Did I create unnecessary static mutable fields?

Arrays

  • Are indexes within 0 to length - 1?
  • Do loops use < array.length?
  • Am I accidentally sharing an array reference when I intended a copy?
  • Do empty arrays need special handling?

2D Arrays

  • Am I using values[row].length?
  • Can the data be jagged?
  • Are any rows possibly null?
  • Does a matrix-specific algorithm require rectangular or square input?

Arrays

  • Am I using Arrays.equals() for content equality?
  • Do I need deepEquals() for nested arrays?
  • Am I aware that Arrays.sort() mutates?
  • Is data sorted before binarySearch()?
  • Is my copy shallow or structurally independent enough for the requirement?

Recursion

  • Is there a base case?
  • Does each recursive call move toward it?
  • Are all input paths guaranteed to terminate?
  • Would a loop be simpler?
  • Could recursion depth become too large?

Final Assessment Questions

Try answering these without looking back.

Question 1

Why are methods important beyond reducing duplicate code?

Question 2

What makes a method signature clear?

Question 3

Why should local scope usually be kept small?

Question 4

What is the main danger of excessive static mutable state?

Question 5

How is an array different from an ArrayList conceptually?

Question 6

Why is index-based traversal necessary for some operations?

Question 7

Why is initializing maximum to 0 unsafe?

Question 8

Why can Java 2D arrays be jagged?

Question 9

Why is a 2D array copy potentially more complicated than an int[] copy?

Question 10

Why should Arrays.sort() be used in production even though we will later implement sorting ourselves?

Question 11

Why does binary search require sorted data?

Question 12

What makes recursion safe?


Final Assessment Answers

Answer 1

Methods provide named abstractions, organize behavior, isolate responsibilities, expose clear inputs/outputs, and make larger programs easier to reason about।

Answer 2

A clear method signature communicates:

What operation is performed
What input is required
What result is produced

through meaningful names and appropriate types।

Answer 3

Small scope reduces accidental access and mutation and makes it easier to understand where a variable matters।

Answer 4

Many unrelated methods can read and change the same state, making program behavior difficult to trace and reason about।

Answer 5

An array has fixed size after creation; an ArrayList is designed to manage dynamically changing collection size. Collections will be studied later।

Answer 6

Because some operations need:

Position
Direct replacement
Neighbor access
Reverse traversal

rather than just element values।

Answer 7

All actual values might be negative, making zero an invalid artificial result।

Answer 8

Because a Java 2D array is an outer array containing references to separate row arrays, and each row can have its own length।

Answer 9

The outer array contains references to row arrays, so copying only the outer structure can leave inner rows shared।

Answer 10

Standard library implementations are tested, optimized, familiar, and communicate intent clearly. Manual implementations are primarily useful for understanding algorithms and tradeoffs।

Answer 11

Binary search decides which half of the search space can be discarded based on ordering. Without sorted data, that decision is invalid।

Answer 12

A recursive design needs:

A correct base case
Progress toward that case
Guaranteed termination for supported inputs
Reasonable recursion depth

Module Completion Checklist

You should now be comfortable writing code like:

static double average(
        int[] values
)

and understand:

What the parameter means
What the return type means
Where locals exist
How the array reference behaves
How to traverse the data
How empty input affects the operation

You should also be able to read:

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

and immediately recognize:

Outer array with two rows
Jagged structure
Row 0 length = 2
Row 1 length = 3

You should know when:

Arrays.sort(...)

is useful and why:

Arrays.binarySearch(...)

requires sorted input।

And when you see:

return number
        + sumTo(
                number - 1
        );

you should be able to identify:

Recursive case
Smaller input
Need for a base case
Call-stack growth

Module Summary

এই module-এ আমরা simple Java statements থেকে reusable এবং structured procedural programs-এর দিকে এগিয়েছি।

We learned:

Methods
↓
Inputs and outputs
↓
Scope
↓
Reusable behavior
↓
Arrays
↓
Array processing
↓
Multidimensional data
↓
Standard array utilities
↓
Recursion

এই concepts সামনে প্রায় সব Java topic-এর foundation হিসেবে কাজ করবে।

Especially:

Classes will contain methods
Objects will own state
Collections will generalize many array use cases
Algorithms will build heavily on array traversal
Streams will transform data using higher-level operations
Exceptions will propagate through method calls

So Module 2 শুধু arrays বা methods শেখার module নয়।

এটি শেখায়:

How to break a program into operations
and how to process structured groups of data.

Next Module

পরবর্তী module:

Object-Oriented Programming Foundations

আমরা শিখব:

  • Classes and objects
  • Fields
  • Instance methods
  • Constructors
  • Object initialization
  • Encapsulation
  • Access modifiers
  • this
  • Object references
  • Object collaboration
  • Designing small domain models