Java Arrays
Java Arrays
Every program works with groups of related data — a list of student marks, a set of product prices, a collection of employee names. Java's most fundamental way to store a fixed-size group of same-type values is an array.
An array is a single variable that holds multiple values of the same type, arranged in a numbered sequence. Instead of declaring int mark1, int mark2, int mark3 ... int mark50 for fifty students, you declare int[] marks and store all fifty values in one place. Each value is accessed by its position number — called an index — starting from zero.
What Is an Array?
An array is a fixed-size, ordered collection of elements of the same data type stored in contiguous memory locations. Once created, its size cannot change.
An int array of size 5:
Index: [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ]
Value: [ 85 ] [ 90 ] [ 78 ] [ 95 ] [ 88 ]
↑
marks[0] = 85
marks[1] = 90
marks[3] = 95
Key points:
— Index starts at 0 (not 1)
— Last valid index = length - 1
— All elements must be the same type
— Size is fixed at creation time
Declaring and Creating Arrays
There are three ways to create an array in Java. Understanding all three prevents confusion when reading code written by others.
1// File: ArrayCreationDemo.java
2
3import java.util.Arrays;
4
5public class ArrayCreationDemo {
6
7 public static void main(String[] args) {
8
9 // Way 1 — declare size, fill later
10 // JVM fills with default values: 0 for int, null for String
11 int[] marks = new int[5];
12 marks[0] = 85;
13 marks[1] = 90;
14 marks[2] = 78;
15 marks[3] = 95;
16 marks[4] = 88;
17 System.out.println("Way 1 — fill later : " + Arrays.toString(marks));
18
19 // Way 2 — declare and initialise in one line (array initialiser)
20 String[] days = {"Monday", "Tuesday", "Wednesday", "Thursday",
21 "Friday", "Saturday", "Sunday"};
22 System.out.println("Way 2 — initialiser : " + Arrays.toString(days));
23
24 // Way 3 — new keyword with inline values
25 double[] prices = new double[]{499.0, 1299.0, 2499.0, 899.0};
26 System.out.println("Way 3 — new + values : " + Arrays.toString(prices));
27
28 // Default values when size is declared but not filled
29 int[] intDefaults = new int[3];
30 double[] doubleDefaults = new double[3];
31 boolean[] boolDefaults = new boolean[3];
32 String[] strDefaults = new String[3];
33
34 System.out.println("\nDefault values:");
35 System.out.println("int defaults: " + Arrays.toString(intDefaults));
36 System.out.println("double defaults: " + Arrays.toString(doubleDefaults));
37 System.out.println("boolean defaults: " + Arrays.toString(boolDefaults));
38 System.out.println("String defaults : " + Arrays.toString(strDefaults));
39 }
40}Output:
Way 1 — fill later : [85, 90, 78, 95, 88]
Way 2 — initialiser : [Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday]
Way 3 — new + values : [499.0, 1299.0, 2499.0, 899.0]
Default values:
int defaults: [0, 0, 0]
double defaults: [0.0, 0.0, 0.0]
boolean defaults: [false, false, false]
String defaults : [null, null, null]
When you declare new int[5], the JVM allocates five integer slots and fills each with 0. For String[], it fills with null. Knowing default values prevents the common mistake of reading an array element before setting it and wondering why you get 0 or null.
Accessing and Modifying Elements
Array elements are accessed using their index inside square brackets. The index must be a non-negative integer between 0 and array.length - 1.
1// File: ArrayAccessDemo.java
2
3public class ArrayAccessDemo {
4
5 public static void main(String[] args) {
6
7 String[] topCities = {"Mumbai", "Delhi", "Bengaluru",
8 "Chennai", "Hyderabad"};
9
10 // Reading elements by index
11 System.out.println("First city : " + topCities[0]);
12 System.out.println("Last city : " + topCities[topCities.length - 1]);
13 System.out.println("Array length: " + topCities.length);
14
15 // Modifying an element
16 topCities[2] = "Bangalore"; // update Bengaluru to Bangalore
17 System.out.println("After update: " + topCities[2]);
18
19 // Accessing with a variable index
20 int index = 3;
21 System.out.println("City at index " + index + ": " + topCities[index]);
22
23 System.out.println();
24
25 // What happens with an invalid index
26 try {
27 System.out.println(topCities[10]); // index 10 does not exist
28 } catch (ArrayIndexOutOfBoundsException e) {
29 System.out.println("Error: " + e.getMessage());
30 }
31
32 try {
33 System.out.println(topCities[-1]); // negative index invalid
34 } catch (ArrayIndexOutOfBoundsException e) {
35 System.out.println("Error: " + e.getMessage());
36 }
37 }
38}Output:
First city : Mumbai
Last city : Hyderabad
Array length: 5
After update: Bangalore
City at index 3: Chennai
Error: Index 10 out of bounds for length 5
Error: Index -1 out of bounds for length 5
array.length — note: no parentheses — is a field, not a method. It always equals the number of slots the array was created with. The last valid index is always array.length - 1. Any index outside this range throws ArrayIndexOutOfBoundsException at runtime.
Traversing Arrays
Traversal means visiting every element in order. Java gives you three ways to loop through an array.
1// File: ArrayTraversalDemo.java
2
3public class ArrayTraversalDemo {
4
5 public static void main(String[] args) {
6
7 int[] scores = {72, 88, 91, 65, 78, 95, 83};
8
9 // Method 1 — traditional for loop
10 // Use when you need the index inside the loop
11 System.out.println("Traditional for loop:");
12 for (int i = 0; i < scores.length; i++) {
13 System.out.println(" scores[" + i + "] = " + scores[i]);
14 }
15
16 System.out.println();
17
18 // Method 2 — enhanced for loop (for-each)
19 // Cleaner when you only need the value, not the index
20 System.out.println("Enhanced for-each:");
21 int total = 0;
22 for (int score : scores) {
23 total += score;
24 }
25 System.out.println(" Total = " + total);
26 System.out.printf(" Average = %.2f%n", (double) total / scores.length);
27
28 System.out.println();
29
30 // Method 3 — while loop
31 // Useful when the stopping condition is more complex
32 System.out.println("While loop (stop at first score above 90):");
33 int i = 0;
34 while (i < scores.length) {
35 if (scores[i] > 90) {
36 System.out.println(" Found score > 90 at index " + i
37 + ": " + scores[i]);
38 break;
39 }
40 i++;
41 }
42 }
43}Output:
Traditional for loop:
scores[0] = 72
scores[1] = 88
scores[2] = 91
scores[3] = 65
scores[4] = 78
scores[5] = 95
scores[6] = 83
Enhanced for-each:
Total = 572
Average = 81.71
While loop (stop at first score above 90):
Found score > 90 at index 2: 91
The for-each loop is the cleanest and safest traversal — no index management, no off-by-one errors. Use the traditional for loop when you need to know the index — for printing position numbers, skipping elements, or modifying elements at specific positions.
Common Array Operations
1// File: ArrayOperationsDemo.java
2
3import java.util.Arrays;
4
5public class ArrayOperationsDemo {
6
7 public static void main(String[] args) {
8
9 int[] marks = {55, 90, 72, 88, 61, 95, 78, 83};
10
11 // 1 — Find maximum
12 int max = marks[0];
13 for (int mark : marks) {
14 if (mark > max) max = mark;
15 }
16 System.out.println("Maximum mark: " + max);
17
18 // 2 — Find minimum
19 int min = marks[0];
20 for (int mark : marks) {
21 if (mark < min) min = mark;
22 }
23 System.out.println("Minimum mark: " + min);
24
25 // 3 — Calculate sum and average
26 int sum = 0;
27 for (int mark : marks) sum += mark;
28 System.out.printf("Sum: %d | Average: %.2f%n", sum, (double) sum / marks.length);
29
30 // 4 — Count elements meeting a condition
31 int passCount = 0;
32 for (int mark : marks) {
33 if (mark >= 60) passCount++;
34 }
35 System.out.println("Students passed (>=60): " + passCount);
36
37 // 5 — Search for a specific value (linear search)
38 int target = 88;
39 int foundAt = -1;
40 for (int i = 0; i < marks.length; i++) {
41 if (marks[i] == target) { foundAt = i; break; }
42 }
43 System.out.println("Mark " + target + " found at index: " + foundAt);
44
45 // 6 — Sort using Arrays.sort()
46 int[] copy = Arrays.copyOf(marks, marks.length);
47 Arrays.sort(copy);
48 System.out.println("Sorted : " + Arrays.toString(copy));
49 System.out.println("Original: " + Arrays.toString(marks)); // unchanged
50
51 // 7 — Copy using Arrays.copyOf()
52 int[] firstFour = Arrays.copyOf(marks, 4);
53 System.out.println("First 4 : " + Arrays.toString(firstFour));
54
55 // 8 — Fill with a value
56 int[] blanks = new int[5];
57 Arrays.fill(blanks, 99);
58 System.out.println("Filled : " + Arrays.toString(blanks));
59 }
60}Output:
Maximum mark: 95
Minimum mark: 55
Sum: 622 | Average: 77.75
Students passed (>=60): 7
Mark 88 found at index: 3
Sorted : [55, 61, 72, 78, 83, 88, 90, 95]
Original: [55, 90, 72, 88, 61, 95, 78, 83]
Maximum mark: 95
Minimum mark: 55
Sum: 622 | Average: 77.75
Students passed (>=60): 7
Mark 88 found at index: 3
Sorted : [55, 61, 72, 78, 83, 88, 90, 95]
Original: [55, 90, 72, 88, 61, 95, 78, 83]
First 4 : [55, 90, 72, 88]
Filled : [99, 99, 99, 99, 99]
Arrays.sort() modifies the original array in place. If you need to sort without changing the original, copy it first with Arrays.copyOf() — as shown above.
Array vs ArrayList — When to Use Which
| Aspect | Array int[] / String[] | ArrayList ArrayList<Integer> |
|---|---|---|
| Size | Fixed at creation — cannot grow or shrink | Dynamic — grows and shrinks automatically |
| Type | Primitives and objects both work | Objects only (use wrapper: Integer, Double) |
| Syntax | arr[i] for access | list.get(i) for access |
| Add element | Not possible after creation | list.add(value) |
| Remove element | Not possible — overwrite with default | list.remove(index) |
| Sorting | Arrays.sort(arr) | Collections.sort(list) |
| Memory | Less overhead — raw array | More overhead — object wrapper |
| Performance | Faster — direct memory access | Slightly slower — method calls |
| Iteration | for, for-each, while | for, for-each, Iterator, stream |
| When to use | Known size, performance-critical, primitive data | Unknown or changing size, need add/remove |
Real-World Example 1 — Student Marks Analyser for a School
The Business Problem
A school teacher wants a simple program to record marks for a class, calculate statistics, assign grades, and find the topper. Every student appears for the same subjects — the class size is known in advance. Arrays are the right tool: fixed size, same type, indexed access.
1// File: StudentMarksAnalyser.java
2
3import java.util.Arrays;
4
5public class StudentMarksAnalyser {
6
7 private static final String[] STUDENT_NAMES = {
8 "Priya Sharma", "Rohan Mehta", "Sneha Rao",
9 "Karan Singh", "Ananya Iyer", "Deepak Joshi"
10 };
11
12 private static final int[] MARKS = {85, 92, 67, 78, 95, 55};
13
14 // Returns the grade letter for a given mark
15 public static String getGrade(int mark) {
16 if (mark >= 90) return "A+";
17 if (mark >= 75) return "A";
18 if (mark >= 60) return "B";
19 if (mark >= 45) return "C";
20 return "D";
21 }
22
23 public static void main(String[] args) {
24
25 int total = 0;
26 int maxMark = MARKS[0];
27 int minMark = MARKS[0];
28 int topperIdx = 0;
29 int lowScoreIdx = 0;
30
31 System.out.println("╔═══════════════════════════════════════════╗");
32 System.out.println("║ CLASS MARKS REPORT ║");
33 System.out.println("╠═══════════════════════════════════════════╣");
34 System.out.printf("║ %-20s %5s %5s %s%n",
35 "Name", "Marks", "Grade", " ║");
36 System.out.println("╠═══════════════════════════════════════════╣");
37
38 for (int i = 0; i < MARKS.length; i++) {
39 String grade = getGrade(MARKS[i]);
40 System.out.printf("║ %-20s %5d %5s ║%n",
41 STUDENT_NAMES[i], MARKS[i], grade);
42
43 total += MARKS[i];
44
45 if (MARKS[i] > maxMark) { maxMark = MARKS[i]; topperIdx = i; }
46 if (MARKS[i] < minMark) { minMark = MARKS[i]; lowScoreIdx = i; }
47 }
48
49 double average = (double) total / MARKS.length;
50
51 // Count how many students passed (>=45)
52 int passCount = 0;
53 for (int mark : MARKS) { if (mark >= 45) passCount++; }
54
55 System.out.println("╠═══════════════════════════════════════════╣");
56 System.out.printf("║ %-28s %d ║%n", "Total Students:", MARKS.length);
57 System.out.printf("║ %-28s %d ║%n", "Students Passed:", passCount);
58 System.out.printf("║ %-28s %.2f ║%n", "Class Average:", average);
59 System.out.printf("║ %-28s %s (%d) ║%n",
60 "Topper:", STUDENT_NAMES[topperIdx], maxMark);
61 System.out.printf("║ %-28s %s (%d) ║%n",
62 "Needs Improvement:", STUDENT_NAMES[lowScoreIdx], minMark);
63 System.out.println("╚═══════════════════════════════════════════╝");
64
65 // Sorted marks for ranking (without disturbing original)
66 int[] sortedMarks = Arrays.copyOf(MARKS, MARKS.length);
67 Arrays.sort(sortedMarks);
68 System.out.println("\nMarks in ascending order: " + Arrays.toString(sortedMarks));
69 }
70}Output:
╔═══════════════════════════════════════════╗
║ CLASS MARKS REPORT ║
╠═══════════════════════════════════════════╣
║ Name Marks Grade ║
╠═══════════════════════════════════════════╣
║ Priya Sharma 85 A ║
║ Rohan Mehta 92 A+ ║
║ Sneha Rao 67 B ║
║ Karan Singh 78 A ║
║ Ananya Iyer 95 A+ ║
║ Deepak Joshi 55 C ║
╠═══════════════════════════════════════════╣
║ Total Students: 6 ║
║ Students Passed: 6 ║
║ Class Average: 78.67 ║
║ Topper: Ananya Iyer (95) ║
║ Needs Improvement: Deepak Joshi (55) ║
╚═══════════════════════════════════════════╝
Marks in ascending order: [55, 67, 78, 85, 92, 95]
Two parallel arrays — STUDENT_NAMES and MARKS — are kept in sync by index. STUDENT_NAMES[i] and MARKS[i] always refer to the same student. This is a common beginner pattern that works well when the data structure is simple and size is fixed.
Real-World Example 2 — Daily Sales Tracker for a Kirana Shop
The Business Problem
A small kirana (grocery) shop owner wants to track daily sales for a week, find the best and worst day, and compute the weekly total. The week always has seven days — the size never changes. Arrays map perfectly to this fixed-size daily data.
1// File: SalesTracker.java
2
3import java.util.Arrays;
4
5public class SalesTracker {
6
7 private static final String[] DAY_NAMES = {
8 "Monday", "Tuesday", "Wednesday", "Thursday",
9 "Friday", "Saturday", "Sunday"
10 };
11
12 public static void main(String[] args) {
13
14 // Daily sales figures for one week (in Rupees)
15 double[] dailySales = {4200.0, 3800.0, 5100.0, 4600.0,
16 6200.0, 8500.0, 7300.0};
17
18 // Calculate weekly total and average
19 double weeklyTotal = 0;
20 for (double sale : dailySales) weeklyTotal += sale;
21 double dailyAvg = weeklyTotal / dailySales.length;
22
23 // Find best and worst day
24 int bestDayIdx = 0;
25 int worstDayIdx = 0;
26 for (int i = 1; i < dailySales.length; i++) {
27 if (dailySales[i] > dailySales[bestDayIdx]) bestDayIdx = i;
28 if (dailySales[i] < dailySales[worstDayIdx]) worstDayIdx = i;
29 }
30
31 // Count days above average
32 int aboveAvgCount = 0;
33 for (double sale : dailySales) {
34 if (sale > dailyAvg) aboveAvgCount++;
35 }
36
37 // Print weekly report
38 System.out.println("══════════════════════════════════════");
39 System.out.println(" WEEKLY SALES REPORT — KIRANA SHOP");
40 System.out.println("══════════════════════════════════════");
41
42 for (int i = 0; i < dailySales.length; i++) {
43 String tag = (i == bestDayIdx) ? " ← BEST" :
44 (i == worstDayIdx) ? " ← WORST" : "";
45 System.out.printf(" %-10s Rs.%7.2f%s%n",
46 DAY_NAMES[i], dailySales[i], tag);
47 }
48
49 System.out.println("──────────────────────────────────────");
50 System.out.printf(" Weekly Total : Rs.%,.2f%n", weeklyTotal);
51 System.out.printf(" Daily Average : Rs.%,.2f%n", dailyAvg);
52 System.out.printf(" Best Day : %s (Rs.%.2f)%n",
53 DAY_NAMES[bestDayIdx], dailySales[bestDayIdx]);
54 System.out.printf(" Worst Day : %s (Rs.%.2f)%n",
55 DAY_NAMES[worstDayIdx], dailySales[worstDayIdx]);
56 System.out.printf(" Days above avg: %d out of %d%n",
57 aboveAvgCount, dailySales.length);
58 System.out.println("══════════════════════════════════════");
59
60 // Reverse the array to see latest day first
61 System.out.println("\nSales from latest to earliest:");
62 for (int i = dailySales.length - 1; i >= 0; i--) {
63 System.out.printf(" %s: Rs.%.2f%n", DAY_NAMES[i], dailySales[i]);
64 }
65 }
66}Output:
══════════════════════════════════════
WEEKLY SALES REPORT — KIRANA SHOP
══════════════════════════════════════
Monday Rs. 4200.00
Tuesday Rs. 3800.00 ← WORST
Wednesday Rs. 5100.00
Thursday Rs. 4600.00
Friday Rs. 6200.00
Saturday Rs. 8500.00 ← BEST
Sunday Rs. 7300.00
──────────────────────────────────────
Weekly Total : Rs.39,700.00
Daily Average : Rs.5,671.43
Best Day : Saturday (Rs.8500.00)
Worst Day : Tuesday (Rs.3800.00)
Days above avg: 3 out of 7
══════════════════════════════════════
Sales from latest to earliest:
Sunday: Rs.7300.00
Saturday: Rs.8500.00
Friday: Rs.6200.00
Thursday: Rs.4600.00
Wednesday: Rs.5100.00
Tuesday: Rs.3800.00
Monday: Rs.4200.00
This example shows the most common array patterns a fresher needs: parallel arrays indexed together, find-max with index tracking, conditional counting, and reverse traversal. A small kirana shop owner in a tier-2 city uses exactly this kind of tracking in a notebook — the program is a digital version of something real and familiar.
Best Practices
Always use array.length in loop conditions — never a hardcoded number. Writing for (int i = 0; i < 5; i++) breaks the moment the array size changes. for (int i = 0; i < marks.length; i++) always works correctly regardless of how many elements are in the array.
Check the length before accessing the first or last element. marks[0] on an empty array throws ArrayIndexOutOfBoundsException. Before writing max = arr[0], verify arr.length > 0. This single check prevents the most common array crash in beginner code.
Use the for-each loop when you only need values. for (int mark : marks) is shorter, cleaner, and impossible to get the index wrong — because there is no index to manage. Switch to the indexed for loop only when you genuinely need the index — for position tracking, modifying elements, or printing "element number N".
Never hardcode array sizes outside the declaration. The size of an array should live in exactly one place — the declaration or the constant that controls it. Using the magic number 7 scattered through a program that processes a week of data breaks silently when the data changes to include 8 days.
Common Mistakes
Mistake 1 — ArrayIndexOutOfBoundsException From Off-by-One
1int[] scores = {10, 20, 30, 40, 50};
2
3// Wrong — loops to index 5, but last valid index is 4
4for (int i = 0; i <= scores.length; i++) {
5 System.out.println(scores[i]); // throws at i=5
6}
7
8// Correct — strict less than
9for (int i = 0; i < scores.length; i++) {
10 System.out.println(scores[i]);
11}Mistake 2 — Printing an Array Directly
1int[] prices = {299, 599, 999};
2System.out.println(prices); // prints [I@7852e922 — useless reference
3
4// Correct — use Arrays.toString()
5import java.util.Arrays;
6System.out.println(Arrays.toString(prices)); // [299, 599, 999]An array does not override toString(). Printing it directly gives the type code and memory address. Always use Arrays.toString(array) for readable output.
Mistake 3 — Confusing length (field) With length() (method)
1int[] numbers = {1, 2, 3, 4, 5};
2String name = "Priya";
3
4System.out.println(numbers.length); // CORRECT — field, no parentheses
5System.out.println(name.length()); // CORRECT — String method, parentheses
6
7System.out.println(numbers.length()); // COMPILE ERROR — arrays have no length() method
8System.out.println(name.length); // COMPILE ERROR — String has no length fieldMistake 4 — Trying to Resize an Array
1int[] items = new int[3];
2items[0] = 10;
3items[1] = 20;
4items[2] = 30;
5
6// Cannot add a 4th element — array is full
7items[3] = 40; // ArrayIndexOutOfBoundsException
8
9// Fix — create a new larger array and copy
10int[] bigger = new int[5];
11System.arraycopy(items, 0, bigger, 0, items.length);
12bigger[3] = 40;
13bigger[4] = 50;
14
15// Or use ArrayList which resizes automaticallyInterview Questions
Q1. What is an array in Java and what are its key characteristics?
An array is a fixed-size, ordered collection of elements of the same data type stored in contiguous memory. Once created, its size cannot change. Elements are accessed by a zero-based integer index — the first element is at index 0, the last at array.length - 1. Arrays can hold primitives (int[], double[]) as well as objects (String[], custom classes). Accessing an index outside the valid range throws ArrayIndexOutOfBoundsException at runtime.
Q2. What is the default value of array elements in Java?
The JVM initialises every array element to its type's default value. For int, short, byte, and long, the default is 0. For double and float, it is 0.0. For boolean, it is false. For char, it is the null character '\u0000'. For any reference type — String, objects — it is null. This automatic initialisation prevents reading garbage memory values but means checking for null before using object array elements is important.
Q3. What is the difference between array length and String length()?
For arrays, length is a final field — no parentheses: arr.length. It holds the number of elements the array was created with. For String, length() is a method — with parentheses: str.length(). It returns the number of characters in the string. Using parentheses on an array (arr.length()) or omitting them on a String (str.length) causes a compile error. This distinction trips up most beginners at least once.
Q4. What is ArrayIndexOutOfBoundsException and what causes it?
ArrayIndexOutOfBoundsException is a runtime exception thrown when code tries to access an array element at an invalid index — either negative or greater than or equal to the array's length. The most common causes are: using <= instead of < in a loop condition (i <= arr.length accesses one index past the end); hardcoding a size that has changed; accessing arr[0] on an empty array; or computing an index incorrectly. The fix is always to verify the index is within 0 to arr.length - 1.
Q5. What is the difference between Array and ArrayList in Java?
An array has a fixed size set at creation — elements cannot be added or removed, only modified. An ArrayList grows and shrinks automatically as elements are added or removed. Arrays can hold both primitives and objects directly. ArrayList can only hold objects — primitives must be wrapped (Integer, Double). Arrays have direct element access via arr[i]; ArrayList uses list.get(i). Arrays are faster and use less memory for fixed-size data. ArrayList is more flexible for collections that grow or shrink.
Q6. How do you copy an array in Java?
Three common ways: Arrays.copyOf(original, newLength) creates a new array with the specified length, copying elements from the original; System.arraycopy(src, srcPos, dest, destPos, length) copies elements between arrays with fine-grained control over positions; and Arrays.copyOfRange(original, from, to) copies a slice. The assignment int[] b = a does NOT copy — it makes b point to the same array as a. Mutating b will change a too.
FAQs
Can an array hold elements of different types?
No — a typed array (int[], String[]) can only hold elements of its declared type. However, Object[] can hold any type of object since every class extends Object. In practice, mixing types in an array is poor design — use a class or record to group related but differently-typed values.
What is the maximum size of an array in Java?
The theoretical maximum is Integer.MAX_VALUE — about 2.1 billion elements. In practice, the limit is the available JVM heap memory. Trying to allocate an array too large for the heap throws OutOfMemoryError. For most programs, arrays with a few thousand to a few million elements are well within limits.
Is the length of an array fixed after creation?
Yes. Once created with new int[5], the array always has exactly 5 slots. You can modify the values in those slots, but you cannot add a 6th slot. If you need more capacity, create a new larger array, copy the elements using System.arraycopy() or Arrays.copyOf(), and discard the old array. ArrayList handles this automatically — it is the right choice when the size varies.
Can you have an array of arrays in Java?
Yes — this is called a two-dimensional array (2D array). int[][] grid = new int[3][4] creates 3 rows of 4 integers each. Each row is itself an array accessible with grid[0], grid[1], etc. Individual elements are accessed with grid[row][col]. Java also supports jagged arrays where each row can have a different length.
Does Arrays.sort() modify the original array?
Yes. Arrays.sort(arr) sorts the elements of arr in place — the original array is modified. If you need the sorted order without changing the original, use int[] copy = Arrays.copyOf(arr, arr.length) first, then sort the copy.
Summary
An array is Java's foundation for working with fixed-size groups of same-type data. Declare it with the type and [], create it with new Type[size] or an initialiser, access elements with zero-based indices, and always loop with arr.length rather than a hardcoded number.
The two habits that prevent the most common array bugs: check arr.length > 0 before reading the first element, and use arr.length - 1 for the last element rather than counting manually. When the size needs to change at runtime — adding or removing items — ArrayList is the right choice over an array.
For interviews, be ready to explain default values, the difference between length field and length() method, why System.out.println(array) gives a useless output, and how to correctly copy an array without accidentally sharing the reference.
What to Read Next
| Topic | Link |
|---|---|
| How multi-dimensional arrays create grids and matrices in Java | Java Arrays → |
| How ArrayList solves the fixed-size limitation with dynamic resizing | Java ArrayList → |
| How the Arrays utility class provides sort, search, copy, and fill operations | Java Collections Framework → |
| How for-each loops simplify array traversal compared to indexed loops | Java Variables → |
| How strings relate to char arrays internally and why they are immutable | Java String Class → |