One-dimensional arrays

Five subjects, five variables? Fifty students, fifty variables? An array keeps many values of the same type under one name, numbered from 0. You'll see where an array lives in memory, why the last index is length − 1, what happens when you go past it, why copying an array variable doesn't copy the array, and then practise with 12 problems.

Module 4 · Arrays and Strings⏱ 24 minBeginner12 practice problems
1 The story

Riya's report card

Riya is writing a program for her report card. She starts with int m1, m2, m3, m4, m5; and five lines to read them, five to add them, five to find the highest. Then she learns next semester has eight subjects.

Before: 5 separate variables 7892658871 m1m2m3m4m5 8 subjects? Rewrite everything. After: one array marks 7892658871 [0][1][2][3][4] 8 subjects? Change one number: new int[8] myphatshala.in
Riya

Sir, my code is just the same line copied five times with different names. And now I need eight.

Arjun Sir

Use an array: one name, many numbered boxes. marks[0] is the first subject, marks[4] the fifth. A loop can walk through all of them, so the same five lines work for 5 subjects or 500.

Riya

Why does it start at 0 and not 1?

Arjun Sir

Because the number is really a distance from the start: the first box is 0 steps away. Remember that, and you'll never be confused about the last index being length − 1.

2 Definition

What is an array?

Formal definition (write this in exams)

An array is a fixed-size, ordered collection of elements of the same type, stored in one object and accessed by an integer index from 0 to length - 1. In Java an array is an object created on the heap with new; its size is fixed when it is created and is available through the length field.

In simple words

A row of numbered lockers with one name on the door. All lockers hold the same kind of thing, the count is decided once, and you open a locker by its number, starting from 0.

Words you'll meet in this lesson

ElementOne value stored in the array.
IndexThe position number of an element: 0, 1, 2 …
lengthThe number of elements. A field, so no brackets: marks.length.
InitializerValues in braces at declaration: {78, 92, 65}.
TraversalVisiting every element, usually with a loop.
AliasA second variable referring to the same array object.

Array facts at a glance

Declareint[] marks; (preferred) or int marks[];. No array exists yet.
Createmarks = new int[5]; → 5 elements, all set to default values
Declare + fillint[] marks = {78, 92, 65, 88, 71}; (size worked out from the values)
Valid indexes0 to length - 1. Anything else → ArrayIndexOutOfBoundsException
Default values0 for int/long, 0.0 for double, false for boolean, '\u0000' for char, null for objects
SizeFixed once created. Need to grow? Create a bigger array and copy, or use ArrayList (Module 11).

Exam tip: arrays use length (a field, no brackets); Strings use length() (a method). Writing marks.length() is a compile error, a favourite MCQ trap.

3 Types and ways to use it

Three ways to create an array, two ways to loop

Size now, values later

int[] marks = new int[5];
All elements start at 0. Fill them from input or a calculation.

new type[size]

Values known now

int[] marks = {78, 92, 65};
Only allowed in the declaration line.

Initializer

New values later

marks = new int[]{60, 70};
Use this form to assign or pass a fresh array after declaring.

new type[]{…}

Default values: what a new array holds

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        System.out.println(Arrays.toString(new int[3]));
        System.out.println(Arrays.toString(new double[2]));
        System.out.println(Arrays.toString(new boolean[2]));
        System.out.println(Arrays.toString(new String[2]));
    }
}
[0, 0, 0] [0.0, 0.0] [false, false] [null, null]

Looping: indexed for vs for-each

Indexed forEnhanced for (for-each)
Syntaxfor (int i = 0; i < a.length; i++)for (int x : a)
Knows the index?Yes, iNo
Can change elements?Yes: a[i] = …No: x is a copy of the value
Reverse / skip / compare neighboursYesNo
Best forUpdating, positions, two arrays at onceJust reading every value (sum, print, count)

Classic mistake: for (int i = 0; i <= a.length; i++). The <= makes the last turn use index a.length, which doesn't exist, and the program crashes. Use <.

4 Step by step

Working with an array, start to finish

  1. Declare the variable

    int[] marks;
    Only a reference variable is created on the stack. There is no array yet; as a local variable it can't be used until assigned.
  2. Create the array

    marks = new int[5];
    new asks the JVM for one object on the heap big enough for 5 ints, sets all of them to 0, records length = 5, and puts the object's address in marks.
  3. Store and read by index

    marks[2] = 65;
    System.out.println(marks[2]);
    Elements sit side by side, so the JVM finds marks[2] directly: start of the data + 2 × 4 bytes. That's why reading any index is equally fast.
  4. Traverse with a loop

    for (int i = 0; i < marks.length; i++) {
        total += marks[i];
    }
    Using marks.length instead of 5 means the loop still works when the size changes.
  5. Stay inside the bounds

    marks[5] or marks[-1] compiles, but crashes at run time.

    Every array access is checked by the JVM. A bad index throws ArrayIndexOutOfBoundsException instead of silently reading some other memory, which is one reason Java is considered safe.
5 See it happen

From declaration to crash: both views

Left: the line being run and what it gives you. Right: the stack variable, the array object on the heap and its indexes.

Life of the marks array 6 steps
What you see int[] marks; marks = new int[5]; marks[2] = 65; for (i = 0; i < marks.length; i++) … System.out.println(marks[5]); int[] copy = marks; copy[0] = 100; // no array yet: marks holds nothing marks.length → 5 marks[0] → 0 marks[2] → 65 [78, 92, 65, 88, 71] total 394, average 78.8 marks[0] → 100 (!) copy == marks → true Exception in thread "main" java.lang.ArrayIndexOutOfBounds Exception: Index 5 out of bounds for length 5 A variable that can refer to an int array. Five boxes, all 0, numbered 0 to 4. Index 2 is the third box. A loop fills and reads every box. Index 5 doesn't exist: the program stops. Changing copy changed marks too! myphatshala.in
Behind the screen Stack Heap marks (none) copy int[] length = 5 [0][1][2][3][4] 078100 092 065 088 071 ? [5] Just a reference variable; nothing on the heap. One object: 5 ints side by side + its length. Address of [2] = start + 2 × 4 bytes. i goes 0, 1, 2, 3, 4, then i < 5 is false. The JVM checks 0 ≤ 5 < length before every access. Two references, one array object. myphatshala.in
6 Real-world use

Arrays in real systems

Arrays are the simplest and fastest way to hold a fixed number of values. Many bigger structures (ArrayList, HashMap, String) are built on top of them.

Watch it with an example: a week of step counts

A fitness app stores 7 days of steps in one array. Watch a loop find the best day, and see what happens when the index goes one step too far.

int[] steps = new int[7] 6 steps
Animated example int[] steps = {4200, 8100, 6500, 9800, 3000, 7200, 5600}; int best = 0; // index of best day for (i = 1; i < 7; i++) if (steps[i] > steps[best]) best = i; for (i = 1; i < 7; i++) if (steps[i] > steps[best]) best = i; print(days[best] + ": " + steps[best]); steps[7] = 100; // 8th day? 4200 [0] Mon 8100 [1] Tue 6500 [2] Wed 9800 [3] Thu 3000 [4] Fri 7200 [5] Sat 5600 [6] Sun best ArrayIndexOutOfBoundsException: Index 7 out of bounds for length 7 Thu: 9800 steps ★ myphatshala.in

1. Daily or monthly figures

Seven days of sales, twelve months of expenses, 24 hours of website visits: the count is fixed, so an array indexed by day, month or hour is natural.

Sales per day→int[] sales = new int[7]→Weekly chart
String[] args--port 8080--env prod

2. Command-line arguments

Every Java program's main receives String[] args. Tools and server apps read options like --port 8080 from this array.

java App --port 8080→args[0], args[1]→Settings
buffer

3. Buffers for files and networks

Reading a file or a network response happens in chunks into a byte[] buffer, often 8 KB at a time. Images, PDFs and videos are all byte arrays in memory.

File / socket→byte[] buf = new byte[8192]→Processed data
[0] Silver[1] Gold[2] Platinum

4. Lookup tables

Tax slabs, discount tiers, GST rates or month names are stored in small arrays and looked up by index, which is faster than a long if-else chain.

Tier number→RATE[tier]→Discount

Examples are simplified. When the number of items changes at run time (orders in a cart, rows from a database), real code usually uses ArrayList, which is itself backed by an array.

7 Run the code

Riya's report card, the array way

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] marks = {78, 92, 65, 88, 71};
        int total = 0;
        for (int i = 0; i < marks.length; i++) {
            total += marks[i];
        }
        System.out.println("Subjects: " + marks.length);
        System.out.println("Total: " + total);
        System.out.println("Average: " + (double) total / marks.length);
        System.out.println("Marks: " + Arrays.toString(marks));
    }
}
Subjects: 5 Total: 394 Average: 78.8 Marks: [78, 92, 65, 88, 71]
  • int[] marks = {78, 92, 65, 88, 71};Declares, creates and fills a 5-element array in one line.
  • i < marks.lengthStops after index 4. Works unchanged if you add a sixth mark.
  • (double) total / marks.lengthCast first so the division keeps decimals (Lesson 2.4).
  • Arrays.toString(marks)Prints the contents. Printing marks directly shows something like [I@1b6d3586, the type and a hash code, not the values.
8 Line by line

Fill an array, then find the best day

Watch the array change on the heap while max and i change on the stack.

Worked examples: real problems, solved and traced in memory

Three everyday business problems solved with arrays. For each one: read the problem, run the solution, then step through it to see exactly what the JVM does in memory, line by line.

Example 1Retail · sales dashboard

Best day of the week

Problem statement

A small shop records its daily sales for Monday to Friday. The owner wants the total, the average per day, and which day sold the most.

Input
days  = {"Mon", "Tue", "Wed", "Thu", "Fri"}
sales = {1200, 950, 1800, 700, 1500}
Expected output
Total: Rs 6150
Average: Rs 1230
Best day: Wed (Rs 1800)

Approach

  1. Keep the day names and the sales in two parallel arrays: index i in both means the same day.
  2. Walk through sales once, adding each value to total.
  3. Remember the index of the best day (not just the amount), so we can also print its name.
  4. Average = total / number of days.

Solution: run it live

What happens in memory, step by step

Recorded from the real JVM: press Next to execute one line at a time. Watch method calls push and pop frames on the stack, and objects (numbered #1, #2 …) appear on the heap.

Example 2Banking · month-end job

Add interest to every account

Problem statement

At month end, a bank adds 4% interest to every savings balance. The balances are in an array. Write a method applyInterest that updates the balances, and print them afterwards.

Input
balances = {10000.0, 2500.0, 40000.0}, rate = 4%
Expected output
Rs 10400.0
Rs 2600.0
Rs 41600.0

Approach

  1. Write a method that receives the array and the rate (methods are covered fully in Module 5).
  2. Inside it, loop with an index and overwrite each element: bal[i] = bal[i] + bal[i] * rate / 100.
  3. The method returns nothing. Because it received a reference to the same array, main sees the new values.

Solution: run it live

What happens in memory, step by step

Recorded from the real JVM: press Next to execute one line at a time. Watch method calls push and pop frames on the stack, and objects (numbered #1, #2 …) appear on the heap.

Example 3Grocery · inventory

Low-stock reorder list

Problem statement

A grocery store reorders any item whose stock falls below 10 units. Produce an array containing only the names of the items to reorder, and print it.

Input
items = {"Rice", "Dal", "Oil", "Sugar"}
stock = {40, 6, 3, 25}, reorder level = 10
Expected output
2 items to reorder: [Dal, Oil]

Approach

  1. An array's size is fixed, so first count how many items are low.
  2. Create a new array of exactly that size.
  3. Loop again and copy each low item's name into the next free slot, tracked by k.

Solution: run it live

What happens in memory, step by step

Recorded from the real JVM: press Next to execute one line at a time. Watch method calls push and pop frames on the stack, and objects (numbered #1, #2 …) appear on the heap.

9 Quiz and revision

Check yourself

Quick revision

Lesson 4.1 in one screen

  • Array = fixed number of same-type values under one name; an object on the heap.
  • int[] a = new int[n]; (defaults) or int[] a = {…}; (values).
  • Indexes run 0 to length - 1; loop with i < a.length.
  • Defaults: 0, 0.0, false, '\u0000', null.
  • Bad index → ArrayIndexOutOfBoundsException at run time.
  • b = a shares one array; Arrays.copyOf makes a real copy.
  • Helpers: Arrays.toString, sort, binarySearch (sorted only), copyOf, equals, fill.

Interview and viva questions

Why do array indexes start at 0?

The index is an offset from the start of the array: the first element is 0 elements away. The address of element i is start + i × element size, which is simplest with 0-based indexes. Java follows C here.

Where are arrays stored in Java?

Arrays are objects, so they always live on the heap. A local array variable on the stack holds only a reference to it. This is why passing an array to a method lets the method change its elements.

Can you change the size of an array?

No. The size is fixed at creation. To “grow” one, create a bigger array and copy the elements (Arrays.copyOf), which is exactly what ArrayList does internally.

What is the difference between == and Arrays.equals() for arrays?

== checks whether two references point to the same array object. Arrays.equals(a, b) checks whether they have the same length and the same elements in the same order.

Array vs ArrayList: when would you use which?

Use an array when the size is fixed and known, or for primitives where performance and memory matter. Use ArrayList when items are added and removed at run time; it resizes itself and offers methods like add and remove, but stores objects (Integer, not int).

Practice problems

Array problems are the backbone of coding tests. Solve each one on paper with a small example first, then code it. The last three are real business tasks.

P1Easy

Sum and average

Find the sum and average of the numbers in an array.

Input
marks = {78, 85, 92, 66, 90}
Expected output
Sum: 411
Average: 82.2
Show solution and explanation
public class Main {
    public static void main(String[] args) {
        int[] marks = {78, 85, 92, 66, 90};
        int sum = 0;
        for (int m : marks) {
            sum += m;
        }
        double average = (double) sum / marks.length;
        System.out.println("Sum: " + sum);
        System.out.println("Average: " + average);
    }
}
Sum: 411 Average: 82.2

How it works: a for-each loop visits every element once. marks.length gives the count, so the code works for any size. The cast avoids integer division (Lesson 2.4).

P2Easy

Largest and smallest

Find the largest and smallest values in an array.

Input
temps = {31, 28, 35, 33, 26, 30}
Expected output
Highest: 35, Lowest: 26
Show solution and explanation
public class Main {
    public static void main(String[] args) {
        int[] temps = {31, 28, 35, 33, 26, 30};
        int max = temps[0], min = temps[0];
        for (int i = 1; i < temps.length; i++) {
            if (temps[i] > max) max = temps[i];
            if (temps[i] < min) min = temps[i];
        }
        System.out.println("Highest: " + max + ", Lowest: " + min);
    }
}
Highest: 35, Lowest: 26

How it works: start with the first element as both the best-so-far maximum and minimum, then compare the rest. Starting max at 0 would be a bug for arrays of negative numbers; starting from temps[0] works for any values.

P3Easy

Count even and odd numbers

Count how many numbers in the array are even and how many are odd.

Input
nums = {12, 7, 9, 20, 33, 18, 4}
Expected output
Even: 4, Odd: 3
Show solution and explanation
public class Main {
    public static void main(String[] args) {
        int[] nums = {12, 7, 9, 20, 33, 18, 4};
        int even = 0, odd = 0;
        for (int n : nums) {
            if (n % 2 == 0) even++;
            else odd++;
        }
        System.out.println("Even: " + even + ", Odd: " + odd);
    }
}
Even: 4, Odd: 3

How it works: two counters updated in one pass. Every number goes into exactly one bucket, so even + odd always equals nums.length, a quick self-check.

P4Easy

Reverse an array in place

Reverse the array without creating a second array.

Input
a = {1, 2, 3, 4, 5, 6}
Expected output
[6, 5, 4, 3, 2, 1]
Show solution and explanation
import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] a = {1, 2, 3, 4, 5, 6};
        for (int i = 0, j = a.length - 1; i < j; i++, j--) {
            int temp = a[i];
            a[i] = a[j];
            a[j] = temp;
        }
        System.out.println(Arrays.toString(a));
    }
}
[6, 5, 4, 3, 2, 1]

How it works: two indexes start at both ends and walk towards each other, swapping as they go. The loop stops when they meet (i < j), so each pair is swapped exactly once. Only one extra variable is needed, whatever the array size.

P5Medium

Find the position of a value

Search for a value and print its position (1-based), or “not found”.

Input
rollNos = {1021, 1044, 1007, 1093, 1050}
search = 1093
Expected output
1093 found at position 4
Show solution and explanation
public class Main {
    public static void main(String[] args) {
        int[] rollNos = {1021, 1044, 1007, 1093, 1050};
        int search = 1093;
        int index = -1;
        for (int i = 0; i < rollNos.length; i++) {
            if (rollNos[i] == search) {
                index = i;
                break;
            }
        }
        if (index >= 0) {
            System.out.println(search + " found at position " + (index + 1));
        } else {
            System.out.println(search + " not found");
        }
    }
}
1093 found at position 4

How it works: linear search: check each element until a match. −1 is the classic “not found” marker, because it can never be a valid index. For a sorted array, binary search (Lesson 3.4, problem P8) is much faster.

P6Medium

Second largest value

Find the second largest distinct value in one pass.

Input
scores = {72, 95, 88, 95, 60}
Expected output
Largest: 95, Second largest: 88
Show solution and explanation
public class Main {
    public static void main(String[] args) {
        int[] scores = {72, 95, 88, 95, 60};
        int first = Integer.MIN_VALUE, second = Integer.MIN_VALUE;
        for (int s : scores) {
            if (s > first) {
                second = first;
                first = s;
            } else if (s > second && s != first) {
                second = s;
            }
        }
        System.out.println("Largest: " + first + ", Second largest: " + second);
    }
}
Largest: 95, Second largest: 88

How it works: keep the top two seen so far. A new champion pushes the old one down to second place. The s != first check stops the duplicate 95 from becoming “second”. Sorting would also work but is slower than one pass.

P7Medium

Rotate right by k places

Rotate the array to the right by k positions; elements that fall off the end come back at the start.

Input
a = {1, 2, 3, 4, 5, 6, 7}, k = 3
Expected output
[5, 6, 7, 1, 2, 3, 4]
Show solution and explanation
import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] a = {1, 2, 3, 4, 5, 6, 7};
        int k = 3;
        int n = a.length;
        int[] result = new int[n];
        for (int i = 0; i < n; i++) {
            result[(i + k) % n] = a[i];
        }
        System.out.println(Arrays.toString(result));
    }
}
[5, 6, 7, 1, 2, 3, 4]

How it works: each element moves from index i to (i + k) % n. The remainder wraps positions past the end back to the start: index 5 + 3 = 8 → 8 % 7 = 1. Using k % n also handles k larger than the array.

P8Medium

Remove duplicates from a sorted array

A sorted array may contain repeats. Keep one copy of each value at the front of the array and print the unique values.

Input
a = {1, 1, 2, 3, 3, 3, 4, 5, 5}
Expected output
5 unique values: 1 2 3 4 5
Show solution and explanation
public class Main {
    public static void main(String[] args) {
        int[] a = {1, 1, 2, 3, 3, 3, 4, 5, 5};
        int unique = 1;                      // a[0] is always kept
        for (int i = 1; i < a.length; i++) {
            if (a[i] != a[unique - 1]) {
                a[unique] = a[i];
                unique++;
            }
        }
        StringBuilder out = new StringBuilder();
        for (int i = 0; i < unique; i++) out.append(a[i]).append(' ');
        System.out.println(unique + " unique values: " + out.toString().trim());
    }
}
5 unique values: 1 2 3 4 5

How it works: because the array is sorted, repeats sit next to each other. A “write position” unique marks where the next new value goes; we only copy a value when it differs from the last one kept. This is the two-pointer technique, used in many interview problems.

P9Medium

Count ratings from 1 to 5

Customers rated a product from 1 to 5 stars. Count how many gave each rating and draw a small bar chart.

Input
ratings = {5, 4, 5, 3, 5, 4, 2, 5, 4, 1, 5, 4}
Expected output
5 star: ##### 5
4 star: #### 4
3 star: # 1
2 star: # 1
1 star: # 1
Show solution and explanation
public class Main {
    public static void main(String[] args) {
        int[] ratings = {5, 4, 5, 3, 5, 4, 2, 5, 4, 1, 5, 4};
        int[] count = new int[6];             // index 1..5 used
        for (int r : ratings) {
            count[r]++;
        }
        for (int star = 5; star >= 1; star--) {
            System.out.println(star + " star: " + "#".repeat(count[star]) + " " + count[star]);
        }
    }
}
5 star: ##### 5 4 star: #### 4 3 star: # 1 2 star: # 1 1 star: # 1

How it works: the rating itself is used as the index into a counting array, so count[r]++ counts it in one step, with no ifs. We make the array size 6 so indexes 1–5 match star values directly. This counting trick is the idea behind fast frequency counts and counting sort.

P10Business problem

Monthly expense review

A family tracks monthly expenses for a year. Print the average, the costliest month and every month that went above the average.

Input
expenses Jan–Dec = 32000, 29500, 31000, 35500,
41000, 30000, 28500, 33000, 38000, 45500, 36000, 34000
Expected output
Average: Rs 34500
Costliest month: Oct (Rs 45500)
Above average: Apr May Sep Oct Nov
Show solution and explanation
public class Main {
    public static void main(String[] args) {
        String[] months = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
                           "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
        int[] expenses = {32000, 29500, 31000, 35500, 41000, 30000,
                          28500, 33000, 38000, 45500, 36000, 34000};
        long total = 0;
        int maxIndex = 0;
        for (int i = 0; i < expenses.length; i++) {
            total += expenses[i];
            if (expenses[i] > expenses[maxIndex]) maxIndex = i;
        }
        double average = (double) total / expenses.length;
        System.out.printf("Average: Rs %.0f%n", average);
        System.out.println("Costliest month: " + months[maxIndex] + " (Rs " + expenses[maxIndex] + ")");
        StringBuilder above = new StringBuilder();
        for (int i = 0; i < expenses.length; i++) {
            if (expenses[i] > average) above.append(months[i]).append(' ');
        }
        System.out.println("Above average: " + above.toString().trim());
    }
}
Average: Rs 34500 Costliest month: Oct (Rs 45500) Above average: Apr May Sep Oct Nov

How it works:

  1. Parallel arrays: months[i] and expenses[i] describe the same month. (Later you'd use a class or a Map to keep them together.)
  2. The first loop computes the total and the index of the maximum together; the second loop needs the finished average, so it must be a separate pass.
  3. The total is a long as a habit for money sums that can grow large.
P11Business problem

Best day to buy and sell a stock

Given a stock's closing price for each day, find the maximum profit from buying once and selling once later. Print the buy day, sell day and profit.

Input
prices = {310, 295, 302, 280, 318, 340, 322, 335}
Expected output
Buy on day 4 at Rs 280
Sell on day 6 at Rs 340
Profit per share: Rs 60
Show solution and explanation
public class Main {
    public static void main(String[] args) {
        int[] prices = {310, 295, 302, 280, 318, 340, 322, 335};
        int minIndex = 0;                 // cheapest day seen so far
        int bestProfit = 0, buy = -1, sell = -1;
        for (int day = 1; day < prices.length; day++) {
            int profit = prices[day] - prices[minIndex];
            if (profit > bestProfit) {
                bestProfit = profit;
                buy = minIndex;
                sell = day;
            }
            if (prices[day] < prices[minIndex]) {
                minIndex = day;
            }
        }
        if (buy < 0) {
            System.out.println("No profitable trade");
        } else {
            System.out.println("Buy on day " + (buy + 1) + " at Rs " + prices[buy]);
            System.out.println("Sell on day " + (sell + 1) + " at Rs " + prices[sell]);
            System.out.println("Profit per share: Rs " + bestProfit);
        }
    }
}
Buy on day 4 at Rs 280 Sell on day 6 at Rs 340 Profit per share: Rs 60

How it works:

  1. Checking every buy–sell pair with nested loops would be O(n²). Instead, one pass keeps the cheapest price so far; for each day, selling today would earn price − cheapest.
  2. The order of the two ifs matters: we compute today's profit using the minimum from earlier days, then update the minimum.
  3. Buying on day 4 at ₹280 and selling on day 6 at ₹340 gives ₹60. This is a very common interview question (and only a teaching example, not investment advice).
P12Business problem

Running balance and overdraft check

Starting with ₹2,000, apply a day's transactions in order (positive = credit, negative = debit). Print the closing balance, the lowest balance reached, and whether the account ever went below zero.

Input
opening = 2000
txns = {-500, -1200, 3000, -2500, -1100, 400}
Expected output
Closing balance: Rs 100
Lowest balance: Rs -300
Overdrawn after transaction #5
Show solution and explanation
public class Main {
    public static void main(String[] args) {
        int balance = 2000;
        int[] txns = {-500, -1200, 3000, -2500, -1100, 400};
        int lowest = balance;
        int firstOverdraft = -1;
        for (int i = 0; i < txns.length; i++) {
            balance += txns[i];
            if (balance < lowest) lowest = balance;
            if (balance < 0 && firstOverdraft == -1) firstOverdraft = i;
        }
        System.out.println("Closing balance: Rs " + balance);
        System.out.println("Lowest balance: Rs " + lowest);
        if (firstOverdraft >= 0) {
            System.out.println("Overdrawn after transaction #" + (firstOverdraft + 1));
        } else {
            System.out.println("Never overdrawn");
        }
    }
}
Closing balance: Rs 100 Lowest balance: Rs -300 Overdrawn after transaction #5

How it works:

  1. A running total: each transaction updates the balance, in order, exactly as a bank statement does.
  2. The lowest balance is tracked during the same pass; the closing balance alone would hide that the account dipped below zero.
  3. firstOverdraft == -1 makes sure we record only the first time it happened. Here: 2000 → 1500 → 300 → 3300 → 800 → −300, so transaction #5 caused the overdraft.

Real-world scenario questions (asked in company interviews)

Arrays look simple, but shared references and fixed sizes cause real production bugs. Decide your answer first, then open the model answer.

Ed-tech · input handlingFresher

The crash when a user picks “subject 6”

A results page asks the student which subject number (1–5) to show, then reads marks[choice]. Students report that subject 1 shows the second subject's marks, and choosing 5 crashes the page. Explain both bugs and the fix.

The interviewer is checking: do you understand 0-based indexes and never trust user input as an index?

Show a strong answer
  • Users count from 1, arrays from 0. The code must use marks[choice - 1]; that fixes the off-by-one shift.
  • Without the shift, choice 5 reads marks[5] on a length-5 array → ArrayIndexOutOfBoundsException.
  • Validate before indexing: if (choice < 1 || choice > marks.length) show a friendly message instead of crashing.

Avoid: wrapping it in try-catch and ignoring the error. Validate the input instead.

Retail · inventoryFresher

“We sized it for 100 products”

A shop's billing program stores items in new String[100]. During the festival sale, a customer buys 120 items and billing crashes. A teammate suggests changing it to 1000. What do you recommend?

The interviewer is checking: do you know arrays are fixed-size and when to use a growable structure?

Show a strong answer

The array can't grow, so any fixed guess will eventually be wrong, and 1000 wastes memory for every small bill.

  • Use ArrayList<String>: it grows automatically (internally it creates a bigger array and copies).
  • If an array must be used, check the count before adding and grow it with Arrays.copyOf(items, items.length * 2).
  • Also keep a separate count of items actually used, since length is capacity, not how many are filled.

Avoid: “Make it really big.” That only moves the crash to a bigger sale.

Banking · encapsulation1–3 years

Someone changed the interest-rate table

A class keeps private double[] rates and has a method getRates() that returns it. A different module sorts the returned array for a report, and suddenly loan calculations use the wrong rates. How did a private field get changed, and how do you prevent it?

The interviewer is checking: do you know that returning an array returns a reference, and what a defensive copy is?

Show a strong answer

private protects the variable, not the object. getRates() handed out the reference, so the other module sorted the same array the bank's class uses.

  • Return a copy: return Arrays.copyOf(rates, rates.length); (a defensive copy).
  • Also copy arrays passed into the constructor, so the caller can't change them later.
  • Or expose an unmodifiable List instead of a raw array.

Avoid: blaming the other module only. The class leaked its internal state.

Analytics · reporting1–3 years

The top-3 report broke the daily chart

An array holds daily sales in date order. A developer adds a “top 3 days” feature by calling Arrays.sort(dailySales) and taking the last three. Now the daily sales chart shows numbers in increasing order instead of by date. What went wrong?

The interviewer is checking: do you know which operations change data in place?

Show a strong answer
  • Arrays.sort sorts in place: it rearranges the original array, so the date order is lost for everyone using it.
  • Fix: sort a copy, int[] sorted = Arrays.copyOf(dailySales, dailySales.length);, or find the top 3 in one pass without sorting.
  • If the dates matter in the result, keep day and amount together (an index array or objects) before sorting.

Avoid: assuming library methods return new data. Check whether a method modifies its argument.