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.
Sir, my code is just the same line copied five times with different names. And now I need eight.
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.
Why does it start at 0 and not 1?
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.
What is an array?
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.
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
marks.length.{78, 92, 65}.Array facts at a glance
| Declare | int[] marks; (preferred) or int marks[];. No array exists yet. |
|---|---|
| Create | marks = new int[5]; → 5 elements, all set to default values |
| Declare + fill | int[] marks = {78, 92, 65, 88, 71}; (size worked out from the values) |
| Valid indexes | 0 to length - 1. Anything else → ArrayIndexOutOfBoundsException |
| Default values | 0 for int/long, 0.0 for double, false for boolean, '\u0000' for char, null for objects |
| Size | Fixed 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.
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.
Values known now
int[] marks = {78, 92, 65};
Only allowed in the declaration line.
New values later
marks = new int[]{60, 70};
Use this form to assign or pass a fresh array after declaring.
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]));
}
}Looping: indexed for vs for-each
Indexed for | Enhanced for (for-each) | |
|---|---|---|
| Syntax | for (int i = 0; i < a.length; i++) | for (int x : a) |
| Knows the index? | Yes, i | No |
| Can change elements? | Yes: a[i] = … | No: x is a copy of the value |
| Reverse / skip / compare neighbours | Yes | No |
| Best for | Updating, positions, two arrays at once | Just 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 <.
Working with an array, start to finish
Declare the variable
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.int[] marks;Create the array
marks = new int[5];newasks the JVM for one object on the heap big enough for 5 ints, sets all of them to 0, recordslength = 5, and puts the object's address inmarks.Store and read by index
Elements sit side by side, so the JVM findsmarks[2] = 65; System.out.println(marks[2]);marks[2]directly: start of the data + 2 × 4 bytes. That's why reading any index is equally fast.Traverse with a loop
Usingfor (int i = 0; i < marks.length; i++) { total += marks[i]; }marks.lengthinstead of 5 means the loop still works when the size changes.Stay inside the bounds
Every array access is checked by the JVM. A bad index throwsmarks[5]ormarks[-1]compiles, but crashes at run time.ArrayIndexOutOfBoundsExceptioninstead of silently reading some other memory, which is one reason Java is considered safe.
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.
marks array 6 steps- Declare:
marksexists, but there is no array yet. - Create:
new int[5]gives five elements, all0;lengthis 5. - Store:
marks[2] = 65fills the third box, because counting starts at 0. - Loop: the same few lines fill, add and average all five subjects.
- Crash:
marks[5]compiles, but at run time Java throwsArrayIndexOutOfBoundsException. - Surprise:
copy = marksdoesn't copy the boxes. Both names refer to the same array.
- The local variable
markslives on the stack. Nothing has been created on the heap. new int[5]creates one object on the heap: 5 ints next to each other pluslength.marksnow holds its address.- Because elements are equal-sized and side by side, the JVM computes where index 2 is directly. No searching.
- The loop variable
itakes 0 to 4. Whenibecomes 5,i < marks.lengthis false and the loop stops. - Before every access the JVM checks the index against
length. Index 5 fails, so it throws instead of touching memory outside the array. copy = markscopies the address, not the elements. Writing throughcopychanges the one shared array.
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.
- One variable, seven values: the array holds 7 ints side by side, numbered by index
[0]to[6]. Index 0 is Monday. - Start: assume the best day is index 0 (Monday, 4200).
- Loop: i = 1: 8100 > 4200, so best = 1. i = 2: 6500 is not bigger, best stays 1.
- i = 3: 9800 > 8100 → best = 3. The remaining days are all smaller, so best stays 3.
- Answer: Thursday, 9800 steps. One loop over the array, whatever its length (
steps.length). - Off by one: the last index of a 7-element array is 6.
steps[7]throwsArrayIndexOutOfBoundsException; Java never lets you write past the end.
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.
2. Command-line arguments
Every Java program's main receives String[] args. Tools and server apps read options like --port 8080 from this array.
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.
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.
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.
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));
}
}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. Printingmarksdirectly shows something like[I@1b6d3586, the type and a hash code, not the values.
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.
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.
days = {"Mon", "Tue", "Wed", "Thu", "Fri"}
sales = {1200, 950, 1800, 700, 1500}Total: Rs 6150 Average: Rs 1230 Best day: Wed (Rs 1800)
Approach
- Keep the day names and the sales in two parallel arrays: index i in both means the same day.
- Walk through
salesonce, adding each value tototal. - Remember the index of the best day (not just the amount), so we can also print its name.
- 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.
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.
balances = {10000.0, 2500.0, 40000.0}, rate = 4%Rs 10400.0 Rs 2600.0 Rs 41600.0
Approach
- Write a method that receives the array and the rate (methods are covered fully in Module 5).
- Inside it, loop with an index and overwrite each element:
bal[i] = bal[i] + bal[i] * rate / 100. - The method returns nothing. Because it received a reference to the same array,
mainsees 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.
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.
items = {"Rice", "Dal", "Oil", "Sugar"}
stock = {40, 6, 3, 25}, reorder level = 102 items to reorder: [Dal, Oil]
Approach
- An array's size is fixed, so first count how many items are low.
- Create a new array of exactly that size.
- 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.
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) orint[] a = {…};(values).- Indexes run
0tolength - 1; loop withi < a.length. - Defaults: 0, 0.0, false, '\u0000', null.
- Bad index →
ArrayIndexOutOfBoundsExceptionat run time. b = ashares one array;Arrays.copyOfmakes 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.
Sum and average
Find the sum and average of the numbers in an array.
marks = {78, 85, 92, 66, 90}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);
}
}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).
Largest and smallest
Find the largest and smallest values in an array.
temps = {31, 28, 35, 33, 26, 30}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);
}
}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.
Count even and odd numbers
Count how many numbers in the array are even and how many are odd.
nums = {12, 7, 9, 20, 33, 18, 4}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);
}
}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.
Reverse an array in place
Reverse the array without creating a second array.
a = {1, 2, 3, 4, 5, 6}[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));
}
}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.
Find the position of a value
Search for a value and print its position (1-based), or “not found”.
rollNos = {1021, 1044, 1007, 1093, 1050}
search = 10931093 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");
}
}
}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.
Second largest value
Find the second largest distinct value in one pass.
scores = {72, 95, 88, 95, 60}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);
}
}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.
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.
a = {1, 2, 3, 4, 5, 6, 7}, k = 3[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));
}
}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.
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.
a = {1, 1, 2, 3, 3, 3, 4, 5, 5}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());
}
}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.
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.
ratings = {5, 4, 5, 3, 5, 4, 2, 5, 4, 1, 5, 4}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]);
}
}
}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.
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.
expenses Jan–Dec = 32000, 29500, 31000, 35500, 41000, 30000, 28500, 33000, 38000, 45500, 36000, 34000
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());
}
}How it works:
- Parallel arrays:
months[i]andexpenses[i]describe the same month. (Later you'd use a class or a Map to keep them together.) - 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.
- The total is a
longas a habit for money sums that can grow large.
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.
prices = {310, 295, 302, 280, 318, 340, 322, 335}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);
}
}
}How it works:
- 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. - The order of the two ifs matters: we compute today's profit using the minimum from earlier days, then update the minimum.
- 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).
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.
opening = 2000
txns = {-500, -1200, 3000, -2500, -1100, 400}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");
}
}
}How it works:
- A running total: each transaction updates the balance, in order, exactly as a bank statement does.
- The lowest balance is tracked during the same pass; the closing balance alone would hide that the account dipped below zero.
firstOverdraft == -1makes 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.
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.
“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
lengthis capacity, not how many are filled.
Avoid: “Make it really big.” That only moves the crash to a bigger sale.
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
Listinstead of a raw array.
Avoid: blaming the other module only. The class leaked its internal state.
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.sortsorts 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.