Java Arrays Tutorial: 1D, 2D, Sorting, Searching & Best Practices (2026)
⏱️ Reading Time: 26 minutes | 🎯 Difficulty: Beginner | 🔄 Last Updated: August 21, 2026
Table of Contents
What is an Array in Java?
An array in Java is a container object that holds a fixed number of values of a single data type. The values are stored in contiguous memory locations, and each value is accessed using an index that starts from 0.
Think of an array as a row of numbered lockers in a school:
- Each locker has a number (index): 0, 1, 2, 3...
- All lockers are the same size (same data type)
- You can open any locker instantly if you know its number (random access)
- The total number of lockers is fixed when the row is built (fixed size)
1// Instead of 5 separate variables... 2int mark1 = 85; 3int mark2 = 90; 4int mark3 = 78; 5int mark4 = 88; 6int mark5 = 92; 7 8// Use one array 9int[] marks = {85, 90, 78, 88, 92};
Why Do We Need Arrays?
"I once had to store 100 student marks. I created mark1, mark2... mark100. When the principal asked for the average, I spent an hour writing 100 variable names. An array would have taken 3 lines." — Every developer's array awakening.
Arrays solve the problem of managing collections of related data:
| Scenario | Without Arrays | With Arrays |
|---|---|---|
| 100 student marks | 100 variables | 1 array |
| Calculate average | Sum 100 variables manually | One loop over array |
| Find highest score | Compare 100 variables | One loop with comparison |
| Sort scores | Impossible manually | Arrays.sort() |
| Matrix operations | Hundreds of variables | 2D array |
| Image pixels | Millions of variables | Multidimensional array |
Real-world applications:
- E-commerce: Store product prices, ratings, inventory counts
- Gaming: Store player scores, map coordinates, sprite data
- Finance: Store stock prices, transaction histories
- Healthcare: Store patient vitals, test results
- Data Science: Store datasets for analysis and machine learning
One-Dimensional Arrays
A one-dimensional array is the simplest form — a single row of elements.
Declaration Syntax
1// Method 1: Declare and allocate separately 2dataType[] arrayName; 3arrayName = new dataType[size]; 4 5// Method 2: Declare and allocate together 6dataType[] arrayName = new dataType[size]; 7 8// Method 3: Declare with initial values 9dataType[] arrayName = {value1, value2, value3};
Example: Creating an Array
1public class ArrayCreation { 2 public static void main(String[] args) { 3 // Method 1: Default values (0 for int) 4 int[] scores = new int[5]; 5 // scores = {0, 0, 0, 0, 0} 6 7 // Method 2: With initial values 8 int[] marks = {85, 90, 78, 95, 88}; 9 10 // Method 3: Anonymous array 11 int[] primes = new int[] {2, 3, 5, 7, 11}; 12 13 System.out.println("Marks array created with " + marks.length + " elements"); 14 } 15}
Accessing and Modifying Elements
1int[] marks = {85, 90, 78, 95, 88}; 2 3// Accessing 4System.out.println(marks[0]); // 85 (first element) 5System.out.println(marks[2]); // 78 (third element) 6 7// Modifying 8marks[1] = 100; // Change second element from 90 to 100 9System.out.println(marks[1]); // 100
The length Property
Every array has a built-in length property (not a method!):
1int[] numbers = {10, 20, 30, 40, 50}; 2System.out.println(numbers.length); // 5 3 4// Use in loops — never hardcode array sizes! 5for (int i = 0; i < numbers.length; i++) { 6 System.out.println(numbers[i]); 7}
⚠️ The ArrayIndexOutOfBoundsException
1int[] arr = {1, 2, 3}; 2System.out.println(arr[3]); // ❌ CRASH! Index 3 does not exist 3// Valid indices: 0, 1, 2 4// arr.length = 3, so maximum index is 2
Golden Rule: Valid indices are
0tolength - 1. Accessingarr[arr.length]or beyond throwsArrayIndexOutOfBoundsException.
Complete Example: Student Marks
1public class StudentMarks { 2 public static void main(String[] args) { 3 int[] marks = {85, 90, 78, 95, 88}; 4 int total = 0; 5 6 System.out.println("--- Student Marks ---"); 7 for (int i = 0; i < marks.length; i++) { 8 System.out.println("Subject " + (i + 1) + ": " + marks[i]); 9 total += marks[i]; 10 } 11 12 double average = total / (double) marks.length; 13 System.out.println("Total: " + total); 14 System.out.println("Average: " + average); 15 } 16}
Output:
1--- Student Marks --- 2Subject 1: 85 3Subject 2: 90 4Subject 3: 78 5Subject 4: 95 6Subject 5: 88 7Total: 436 8Average: 87.2
Two-Dimensional Arrays
A two-dimensional array represents data in rows and columns — like a spreadsheet or a matrix. It is essentially an array of arrays.
Declaration Syntax
1// Method 1: Declare and allocate 2dataType[][] arrayName = new dataType[rows][columns]; 3 4// Method 2: With initial values 5dataType[][] arrayName = { 6 {row0col0, row0col1, row0col2}, 7 {row1col0, row1col1, row1col2}, 8 {row2col0, row2col1, row2col2} 9};
Example: Creating a Matrix
1public class MatrixDemo { 2 public static void main(String[] args) { 3 int[][] matrix = { 4 {1, 2, 3}, 5 {4, 5, 6}, 6 {7, 8, 9} 7 }; 8 9 // Access element at row 1, column 2 10 System.out.println("Element at [1][2]: " + matrix[1][2]); // 6 11 12 // Get dimensions 13 System.out.println("Rows: " + matrix.length); // 3 14 System.out.println("Cols in row 0: " + matrix[0].length); // 3 15 } 16}
Visual Representation
Col 0 Col 1 Col 2
Row 0: 1 2 3
Row 1: 4 5 6
Row 2: 7 8 9
matrix[1][2] = 6 (Row 1, Column 2)
Traversing a 2D Array
1public class MatrixTraversal { 2 public static void main(String[] args) { 3 int[][] matrix = { 4 {1, 2, 3}, 5 {4, 5, 6}, 6 {7, 8, 9} 7 }; 8 9 System.out.println("--- Matrix ---"); 10 for (int row = 0; row < matrix.length; row++) { 11 for (int col = 0; col < matrix[row].length; col++) { 12 System.out.print(matrix[row][col] + " "); 13 } 14 System.out.println(); // New line after each row 15 } 16 } 17}
Output:
1--- Matrix --- 21 2 3 34 5 6 47 8 9
Jagged Arrays (Arrays with Different Row Lengths)
Java allows rows to have different lengths:
1int[][] jagged = { 2 {1, 2}, // Row 0: 2 elements 3 {3, 4, 5, 6}, // Row 1: 4 elements 4 {7} // Row 2: 1 element 5}; 6 7for (int i = 0; i < jagged.length; i++) { 8 System.out.print("Row " + i + ": "); 9 for (int j = 0; j < jagged[i].length; j++) { 10 System.out.print(jagged[i][j] + " "); 11 } 12 System.out.println(); 13}
Output:
1Row 0: 1 2 2Row 1: 3 4 5 6 3Row 2: 7
Multidimensional Arrays
Java supports arrays with more than two dimensions. While rarely used in basic applications, they are essential for scientific computing, 3D graphics, and game development.
3D Array Example
1// A 3D array: 2 blocks × 3 rows × 4 columns 2int[][][] cube = new int[2][3][4]; 3 4// Assign a value 5cube[0][2][1] = 50; 6 7// Visual analogy: A Rubik's cube or a 2-story building with rooms 8// Block 0, Row 2, Column 1 = 50
Real-World Uses of Multidimensional Arrays
| Domain | Use Case | Dimensions |
|---|---|---|
| 3D Graphics | Voxel data, 3D textures | 3D (x, y, z) |
| Game Development | 3D game maps, terrain height | 3D (x, y, z) |
| Image Processing | RGB color channels | 3D (width, height, channel) |
| Scientific Computing | Climate models, fluid dynamics | 3D+ (x, y, z, time) |
| Machine Learning | Tensors for neural networks | 4D+ (batch, height, width, channels) |
Array Traversal Techniques
Traversal means visiting every element of an array. Java provides multiple ways to do this.
1. Traditional for Loop (Index-Based)
Use this when you need the index (for modification, reverse traversal, or index-dependent logic):
1int[] numbers = {10, 20, 30, 40}; 2 3for (int i = 0; i < numbers.length; i++) { 4 System.out.println("Index " + i + ": " + numbers[i]); 5}
2. Enhanced for Loop (For-Each)
Use this when you only need the value and do not care about the index:
1int[] numbers = {10, 20, 30, 40}; 2 3for (int number : numbers) { 4 System.out.println("Value: " + number); 5}
3. while Loop
Useful for conditional traversal:
1int[] numbers = {10, 20, 30, 40, 50}; 2int i = 0; 3 4while (i < numbers.length && numbers[i] < 35) { 5 System.out.println(numbers[i]); 6 i++; 7} 8// Output: 10, 20, 30 (stops when value >= 35)
4. Reverse Traversal
1int[] numbers = {10, 20, 30, 40}; 2 3for (int i = numbers.length - 1; i >= 0; i--) { 4 System.out.println(numbers[i]); 5} 6// Output: 40, 30, 20, 10
Traversal Comparison
| Method | Best For | Can Modify? | Index Access? |
|---|---|---|---|
for (index) | Modification, complex logic | ✅ Yes | ✅ Yes |
Enhanced for | Simple reading, cleaner code | ⚠️ Primitives: no | ❌ No |
while | Conditional traversal | ✅ Yes | ✅ Yes |
Arrays.stream() | Functional operations | Via map | Via IntStream |
Array Sorting
Sorting arranges array elements in a specific order (ascending or descending). Java provides built-in and manual sorting options.
Using Arrays.sort() (Built-in)
1import java.util.Arrays; 2 3public class SortDemo { 4 public static void main(String[] args) { 5 int[] numbers = {40, 10, 70, 20, 30, 50}; 6 7 System.out.println("Before: " + Arrays.toString(numbers)); 8 // Output: Before: [40, 10, 70, 20, 30, 50] 9 10 Arrays.sort(numbers); // Dual-Pivot Quicksort (very fast) 11 12 System.out.println("After: " + Arrays.toString(numbers)); 13 // Output: After: [10, 20, 30, 40, 50, 70] 14 } 15}
Sorting a Sub-Range
1int[] numbers = {40, 10, 70, 20, 30, 50}; 2Arrays.sort(numbers, 1, 4); // Sorts indices 1 to 3 only 3// Result: {40, 10, 20, 70, 30, 50}
Sorting in Descending Order
Arrays.sort() sorts primitives in ascending order only. For descending:
1Integer[] numbers = {40, 10, 70, 20, 30}; // Must use Integer, not int 2Arrays.sort(numbers, Collections.reverseOrder()); 3// Result: [70, 40, 30, 20, 10]
Manual Bubble Sort (For Learning)
1public class BubbleSort { 2 public static void main(String[] args) { 3 int[] arr = {64, 34, 25, 12, 22, 11, 90}; 4 5 for (int i = 0; i < arr.length - 1; i++) { 6 for (int j = 0; j < arr.length - i - 1; j++) { 7 if (arr[j] > arr[j + 1]) { 8 // Swap 9 int temp = arr[j]; 10 arr[j] = arr[j + 1]; 11 arr[j + 1] = temp; 12 } 13 } 14 } 15 16 System.out.println("Sorted: " + Arrays.toString(arr)); 17 } 18}
In production: Always use
Arrays.sort()orCollections.sort(). Manual sorts are for learning algorithms only.
Linear Search
Linear Search checks each element one by one from the start until the target is found or the array ends.
Characteristics
- Works on sorted and unsorted arrays
- Simple to implement
- Slow for large arrays: O(n) time complexity
Example
1public class LinearSearch { 2 public static void main(String[] args) { 3 int[] numbers = {45, 12, 78, 23, 67, 89, 34}; 4 int target = 67; 5 int index = -1; 6 7 for (int i = 0; i < numbers.length; i++) { 8 if (numbers[i] == target) { 9 index = i; 10 break; // Found it! Stop searching. 11 } 12 } 13 14 if (index != -1) { 15 System.out.println("✅ Found " + target + " at index " + index); 16 } else { 17 System.out.println("❌ " + target + " not found."); 18 } 19 } 20}
Output:
1✅ Found 67 at index 4
Binary Search
Binary Search is dramatically faster than linear search but requires a sorted array. It repeatedly divides the search range in half.
How It Works
Array: [10, 20, 30, 40, 50, 60, 70, 80]
Target: 60
Step 1: Check middle (index 3) = 40. 60 > 40, search right half.
Step 2: Check middle of right half (index 5) = 60. Found!
Only 2 checks instead of 6 with linear search!
Using Arrays.binarySearch()
1import java.util.Arrays; 2 3public class BinarySearchDemo { 4 public static void main(String[] args) { 5 int[] numbers = {10, 20, 30, 40, 50, 60, 70, 80}; 6 int target = 60; 7 8 int index = Arrays.binarySearch(numbers, target); 9 10 if (index >= 0) { 11 System.out.println("✅ Found " + target + " at index " + index); 12 } else { 13 System.out.println("❌ Not found."); 14 } 15 } 16}
Output:
1✅ Found 60 at index 5
⚠️ Critical: Array Must Be Sorted!
1int[] unsorted = {40, 10, 90, 20, 70}; 2Arrays.sort(unsorted); // MUST sort first! 3int index = Arrays.binarySearch(unsorted, 70);
Search Algorithm Comparison
| Algorithm | Requires Sorted? | Time Complexity | Best For |
|---|---|---|---|
| Linear Search | No | O(n) | Small arrays, unsorted data |
| Binary Search | Yes | O(log n) | Large sorted arrays |
| Hash Lookup | No | O(1) average | Frequent lookups (use HashMap) |
For 1 million elements: Linear search takes ~500,000 checks on average. Binary search takes only 20 checks!
Copying Arrays
Java provides several ways to copy arrays. Each has different use cases.
Method 1: clone() — Simple Full Copy
1int[] original = {1, 2, 3, 4, 5}; 2int[] copy = original.clone(); 3 4copy[0] = 100; // Modifies only 'copy' 5System.out.println("Original: " + Arrays.toString(original)); // [1, 2, 3, 4, 5] 6System.out.println("Copy: " + Arrays.toString(copy)); // [100, 2, 3, 4, 5]
Method 2: Arrays.copyOf() — Copy with Resize
1int[] original = {1, 2, 3, 4, 5}; 2 3// Exact copy 4int[] copy1 = Arrays.copyOf(original, original.length); 5 6// Truncate to first 3 elements 7int[] copy2 = Arrays.copyOf(original, 3); // [1, 2, 3] 8 9// Extend with zeros 10int[] copy3 = Arrays.copyOf(original, 8); // [1, 2, 3, 4, 5, 0, 0, 0]
Method 3: Arrays.copyOfRange() — Copy a Subset
1int[] original = {10, 20, 30, 40, 50, 60}; 2int[] subset = Arrays.copyOfRange(original, 2, 5); // [30, 40, 50] 3// Copies indices 2, 3, 4 (start inclusive, end exclusive)
Method 4: System.arraycopy() — High-Performance Copy
1int[] source = {1, 2, 3, 4, 5}; 2int[] dest = new int[5]; 3 4// System.arraycopy(src, srcPos, dest, destPos, length) 5System.arraycopy(source, 0, dest, 0, source.length);
Copy Method Comparison
| Method | Use Case | Performance |
|---|---|---|
clone() | Simple full copy | Good |
Arrays.copyOf() | Copy + resize | Good |
Arrays.copyOfRange() | Copy subset | Good |
System.arraycopy() | Native, fastest | ✅ Best |
⚠️ Shallow Copy vs Deep Copy
For primitive arrays, all copy methods create independent copies. For object arrays, they copy references (shallow copy):
1String[] original = {"A", "B", "C"}; 2String[] copy = original.clone(); 3 4copy[0] = "Z"; // Safe — Strings are immutable 5 6// But for mutable objects: 7Student[] original = {new Student("A"), new Student("B")}; 8Student[] copy = original.clone(); 9copy[0].name = "Z"; // ❌ Also changes original[0]!
Real-World Use Cases
Use Case 1: E-Commerce Cart Total
1public class ShoppingCart { 2 public static void main(String[] args) { 3 double[] prices = {299.99, 149.50, 899.00, 49.99, 199.00}; 4 double total = 0; 5 double maxPrice = prices[0]; 6 7 for (double price : prices) { 8 total += price; 9 if (price > maxPrice) maxPrice = price; 10 } 11 12 double average = total / prices.length; 13 14 System.out.printf("Items: %d%n", prices.length); 15 System.out.printf("Total: ₹%.2f%n", total); 16 System.out.printf("Average: ₹%.2f%n", average); 17 System.out.printf("Most Expensive: ₹%.2f%n", maxPrice); 18 } 19}
Use Case 2: Temperature Analysis (2D Array)
1public class TemperatureAnalysis { 2 public static void main(String[] args) { 3 // Rows = cities, Cols = days 4 double[][] temps = { 5 {32.5, 33.0, 31.8, 34.2, 35.0, 33.5, 32.0}, // Mumbai 6 {28.0, 29.5, 30.0, 29.0, 28.5, 30.2, 31.0}, // Delhi 7 {25.0, 26.5, 27.0, 26.0, 25.5, 26.0, 27.5} // Bangalore 8 }; 9 10 String[] cities = {"Mumbai", "Delhi", "Bangalore"}; 11 12 for (int i = 0; i < temps.length; i++) { 13 double sum = 0; 14 for (double temp : temps[i]) { 15 sum += temp; 16 } 17 double avg = sum / temps[i].length; 18 System.out.printf("%s average: %.2f°C%n", cities[i], avg); 19 } 20 } 21}
Use Case 3: Leaderboard System
1import java.util.Arrays; 2import java.util.Collections; 3 4public class Leaderboard { 5 public static void main(String[] args) { 6 Integer[] scores = {850, 1200, 940, 1100, 780, 1350, 920}; 7 8 // Sort descending 9 Arrays.sort(scores, Collections.reverseOrder()); 10 11 System.out.println("🏆 TOP 3 PLAYERS 🏆"); 12 for (int i = 0; i < Math.min(3, scores.length); i++) { 13 System.out.println((i + 1) + ". " + scores[i] + " points"); 14 } 15 } 16}
Common Mistakes
Mistake 1: ArrayIndexOutOfBoundsException
1int[] arr = {1, 2, 3}; 2 3// WRONG — index 3 does not exist 4System.out.println(arr[3]); // ❌ Crash! 5 6// WRONG — off-by-one in loop 7for (int i = 0; i <= arr.length; i++) { // Should be < not <= 8 System.out.println(arr[i]); // Crashes on last iteration 9} 10 11// CORRECT 12for (int i = 0; i < arr.length; i++) { 13 System.out.println(arr[i]); 14}
Mistake 2: Assigning One Array to Another (Reference Copy)
1int[] a = {1, 2, 3}; 2int[] b = a; // ❌ Both point to SAME array! 3 4b[0] = 100; 5System.out.println(a[0]); // 100 — 'a' also changed! 6 7// CORRECT — Create a true copy 8int[] b = a.clone();
Mistake 3: Forgetting Arrays Are Fixed Size
1int[] arr = new int[3]; 2arr[3] = 10; // ❌ ArrayIndexOutOfBoundsException! 3 4// CORRECT — Use ArrayList for dynamic sizing 5// Or create a new larger array and copy 6int[] newArr = Arrays.copyOf(arr, arr.length + 1); 7newArr[3] = 10; // ✅ Works
Mistake 4: Binary Search on Unsorted Array
1int[] unsorted = {40, 10, 90, 20, 70}; 2int index = Arrays.binarySearch(unsorted, 20); // ❌ Wrong result! 3 4// CORRECT 5Arrays.sort(unsorted); // Sort first! 6int index = Arrays.binarySearch(unsorted, 20); // ✅ Correct
Mistake 5: Using == to Compare Arrays
1int[] a = {1, 2, 3}; 2int[] b = {1, 2, 3}; 3 4System.out.println(a == b); // false — compares references 5System.out.println(a.equals(b)); // false — array equals() is reference-based 6 7// CORRECT — Use Arrays.equals() 8System.out.println(Arrays.equals(a, b)); // true — compares content 9 10// For 2D arrays — use deepEquals 11int[][] x = {{1, 2}, {3, 4}}; 12int[][] y = {{1, 2}, {3, 4}}; 13System.out.println(Arrays.deepEquals(x, y)); // true
Best Practices
-
Always use
lengthin loops — Never hardcode array sizes.1// Good 2for (int i = 0; i < arr.length; i++) 3 4// Bad 5for (int i = 0; i < 5; i++) // What if array size changes? -
Use enhanced
forfor reading — Cleaner and less error-prone.1for (int value : scores) { 2 total += value; 3} -
Check bounds before accessing — Especially with user input.
1if (index >= 0 && index < arr.length) { 2 System.out.println(arr[index]); 3} -
Use
Arrays.toString()for debugging — Stop writing manual print loops.1System.out.println(Arrays.toString(marks)); // [85, 90, 78, 95] -
Sort before binary search — Always.
1Arrays.sort(arr); 2int index = Arrays.binarySearch(arr, target); -
Use meaningful names —
studentMarksnotarr. -
Clone or copyOf for independent copies — Remember reference assignment is not a copy.
-
Consider
ArrayListfor dynamic sizing — Arrays are fixed. If size changes, useArrayList.
Architecture & Performance Considerations
How Arrays Are Stored in Memory
Arrays in Java are objects. When you declare int[] arr = new int[5];:
- Memory is allocated for 5 integers (20 bytes) contiguously
- A reference variable
arrpoints to this memory block - The JVM knows the exact location of every element:
baseAddress + (index × elementSize)
This is why random access (accessing arr[i]) is O(1) — constant time, regardless of array size.
Time Complexity of Array Operations
| Operation | Time Complexity | Explanation |
|---|---|---|
| Access by index | O(1) | Direct memory calculation |
| Search (linear) | O(n) | Check every element |
| Search (binary) | O(log n) | Divide and conquer |
| Insert at end | O(1) | If space exists |
| Insert at middle | O(n) | Must shift elements |
| Delete from middle | O(n) | Must shift elements |
| Sort (Arrays.sort) | O(n log n) | Dual-pivot quicksort |
Arrays vs ArrayList
| Feature | Array | ArrayList |
|---|---|---|
| Size | Fixed | Dynamic |
| Type | Can hold primitives | Only objects (auto-boxing for primitives) |
| Performance | Faster (no boxing) | Slightly slower |
| Methods | length property only | Rich API (add, remove, contains, etc.) |
| Generics | Not supported | Supported |
| Best for | Fixed data, performance | Dynamic collections |
Java 8+ Streams with Arrays
Modern Java provides functional-style operations on arrays:
1int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; 2 3// Sum of even numbers 4int sum = Arrays.stream(numbers) 5 .filter(n -> n % 2 == 0) 6 .sum(); 7// Result: 30 8 9// Average 10double avg = Arrays.stream(numbers).average().orElse(0); 11 12// Find max 13int max = Arrays.stream(numbers).max().orElse(0); 14 15// Convert to sorted array (descending) 16int[] descending = Arrays.stream(numbers) 17 .boxed() 18 .sorted(Collections.reverseOrder()) 19 .mapToInt(Integer::intValue) 20 .toArray();
Practice Programs
Exercise 1: Find Largest Element
1public class LargestElement { 2 public static void main(String[] args) { 3 int[] numbers = {45, 78, 23, 89, 12, 67, 91, 34}; 4 5 int max = numbers[0]; 6 for (int num : numbers) { 7 if (num > max) max = num; 8 } 9 10 System.out.println("Largest: " + max); // 91 11 } 12}
Exercise 2: Reverse an Array
1public class ReverseArray { 2 public static void main(String[] args) { 3 int[] original = {1, 2, 3, 4, 5}; 4 int[] reversed = new int[original.length]; 5 6 for (int i = 0; i < original.length; i++) { 7 reversed[i] = original[original.length - 1 - i]; 8 } 9 10 System.out.println("Original: " + Arrays.toString(original)); 11 System.out.println("Reversed: " + Arrays.toString(reversed)); 12 } 13}
Exercise 3: Count Even and Odd
1public class EvenOddCount { 2 public static void main(String[] args) { 3 int[] numbers = {12, 17, 8, 25, 30, 41, 6, 9}; 4 int even = 0, odd = 0; 5 6 for (int num : numbers) { 7 if (num % 2 == 0) even++; 8 else odd++; 9 } 10 11 System.out.println("Even: " + even); // 4 12 System.out.println("Odd: " + odd); // 4 13 } 14}
Exercise 4: Matrix Multiplication
1public class MatrixMultiplication { 2 public static void main(String[] args) { 3 int[][] a = {{1, 2, 3}, {4, 5, 6}}; 4 int[][] b = {{7, 8}, {9, 10}, {11, 12}}; 5 6 int[][] result = new int[2][2]; 7 8 for (int i = 0; i < 2; i++) { 9 for (int j = 0; j < 2; j++) { 10 for (int k = 0; k < 3; k++) { 11 result[i][j] += a[i][k] * b[k][j]; 12 } 13 } 14 } 15 16 System.out.println("Result:"); 17 for (int[] row : result) { 18 System.out.println(Arrays.toString(row)); 19 } 20 } 21}
Exercise 5: Student Ranking System
1import java.util.Arrays; 2import java.util.Collections; 3 4public class StudentRanking { 5 public static void main(String[] args) { 6 Integer[] marks = {78, 92, 85, 67, 95, 88, 73, 91}; 7 String[] names = {"Amit", "Priya", "Rahul", "Sneha", "Vikram", "Neha", "Karan", "Anita"}; 8 9 // Sort marks descending while keeping names aligned 10 // (In real apps, use a Student class with comparable) 11 Arrays.sort(marks, Collections.reverseOrder()); 12 13 System.out.println("🏆 TOP 3 STUDENTS 🏆"); 14 for (int i = 0; i < 3; i++) { 15 System.out.println((i + 1) + ". " + marks[i] + " marks"); 16 } 17 } 18}
Mini Project: Student Grade Management System
Build a comprehensive console application that manages multiple students, subjects, and grades using arrays, sorting, and searching.
1import java.util.Arrays; 2import java.util.Scanner; 3 4public class GradeManagementSystem { 5 6 static void printHeader(String title) { 7 System.out.println("\\n" + "=".repeat(50)); 8 System.out.println(" " + title); 9 System.out.println("=".repeat(50)); 10 } 11 12 static double calculateAverage(int[] marks) { 13 int sum = 0; 14 for (int mark : marks) sum += mark; 15 return marks.length > 0 ? (double) sum / marks.length : 0; 16 } 17 18 static String getGrade(double avg) { 19 if (avg >= 90) return "A+"; 20 if (avg >= 80) return "A"; 21 if (avg >= 70) return "B"; 22 if (avg >= 60) return "C"; 23 if (avg >= 40) return "D"; 24 return "F"; 25 } 26 27 static int findStudentIndex(String[] names, String target) { 28 for (int i = 0; i < names.length; i++) { 29 if (names[i].equalsIgnoreCase(target)) return i; 30 } 31 return -1; 32 } 33 34 static void displayAllStudents(String[] names, int[][] marks, String[] subjects) { 35 printHeader("ALL STUDENTS REPORT"); 36 System.out.printf("%-15s", "Name"); 37 for (String sub : subjects) System.out.printf("%8s", sub); 38 System.out.printf("%10s%8s%n", "Average", "Grade"); 39 System.out.println("-".repeat(50)); 40 41 for (int i = 0; i < names.length; i++) { 42 System.out.printf("%-15s", names[i]); 43 for (int mark : marks[i]) System.out.printf("%8d", mark); 44 double avg = calculateAverage(marks[i]); 45 System.out.printf("%10.2f%8s%n", avg, getGrade(avg)); 46 } 47 } 48 49 static void displayTopper(String[] names, int[][] marks) { 50 int topIndex = 0; 51 double topAvg = calculateAverage(marks[0]); 52 53 for (int i = 1; i < marks.length; i++) { 54 double avg = calculateAverage(marks[i]); 55 if (avg > topAvg) { 56 topAvg = avg; 57 topIndex = i; 58 } 59 } 60 61 printHeader("🏆 CLASS TOPPER 🏆"); 62 System.out.println("Name: " + names[topIndex]); 63 System.out.printf("Average: %.2f%%%n", topAvg); 64 System.out.println("Grade: " + getGrade(topAvg)); 65 } 66 67 static void searchStudent(String[] names, int[][] marks, String[] subjects, String target) { 68 int index = findStudentIndex(names, target); 69 70 if (index == -1) { 71 System.out.println("❌ Student not found."); 72 return; 73 } 74 75 printHeader("STUDENT DETAILS: " + names[index]); 76 for (int i = 0; i < subjects.length; i++) { 77 System.out.printf("%-12s: %d%n", subjects[i], marks[index][i]); 78 } 79 double avg = calculateAverage(marks[index]); 80 System.out.printf("%-12s: %.2f%%%n", "Average", avg); 81 System.out.printf("%-12s: %s%n", "Grade", getGrade(avg)); 82 } 83 84 public static void main(String[] args) { 85 try (Scanner input = new Scanner(System.in)) { 86 String[] subjects = {"Math", "Science", "English", "History"}; 87 String[] names = {"Amit", "Priya", "Rahul", "Sneha", "Vikram"}; 88 89 int[][] marks = { 90 {85, 90, 78, 88}, 91 {92, 88, 95, 90}, 92 {78, 82, 80, 75}, 93 {95, 92, 88, 94}, 94 {70, 75, 72, 68} 95 }; 96 97 boolean running = true; 98 99 while (running) { 100 System.out.println("\\n--- GRADE MANAGEMENT SYSTEM ---"); 101 System.out.println("1. View All Students"); 102 System.out.println("2. View Class Topper"); 103 System.out.println("3. Search Student"); 104 System.out.println("4. Subject-wise Average"); 105 System.out.println("5. Exit"); 106 System.out.print("Choice: "); 107 108 int choice = Integer.parseInt(input.nextLine()); 109 110 switch (choice) { 111 case 1 -> displayAllStudents(names, marks, subjects); 112 case 2 -> displayTopper(names, marks); 113 case 3 -> { 114 System.out.print("Enter student name: "); 115 String name = input.nextLine(); 116 searchStudent(names, marks, subjects, name); 117 } 118 case 4 -> { 119 printHeader("SUBJECT AVERAGES"); 120 for (int s = 0; s < subjects.length; s++) { 121 int sum = 0; 122 for (int i = 0; i < marks.length; i++) { 123 sum += marks[i][s]; 124 } 125 double avg = (double) sum / marks.length; 126 System.out.printf("%-12s: %.2f%n", subjects[s], avg); 127 } 128 } 129 case 5 -> { 130 System.out.println("👋 Goodbye!"); 131 running = false; 132 } 133 default -> System.out.println("❌ Invalid choice."); 134 } 135 } 136 } 137 } 138}
What This Project Covers:
- 1D arrays for names and subjects
- 2D arrays for marks (students × subjects)
- Array traversal with nested loops
- Average calculation per student and per subject
- Linear search for student lookup
- Grade assignment logic
- Formatted tabular output
- Interactive menu system
Summary & Cheat Sheet
Quick Reference
| Task | Code | Notes |
|---|---|---|
| Declare array | int[] arr = new int[5]; | Fixed size |
| Initialize | int[] arr = {1, 2, 3}; | Inline values |
| Get length | arr.length | Property, not method |
| Access element | arr[0] | Index starts at 0 |
| Modify element | arr[0] = 100; | Direct assignment |
| Loop (index) | for (int i = 0; i < arr.length; i++) | For modification |
| Loop (value) | for (int val : arr) | For reading |
| Sort | Arrays.sort(arr); | In-place, ascending |
| Binary search | Arrays.binarySearch(arr, val); | Array must be sorted |
| Copy | arr.clone() or Arrays.copyOf(arr, len) | Shallow for objects |
Key Takeaways
- Arrays store multiple values of the same type — Use them instead of many variables.
- Index starts at 0 — The first element is
arr[0], the last isarr[arr.length - 1]. - Arrays have fixed size — You cannot resize them. Use
ArrayListfor dynamic sizing. ArrayIndexOutOfBoundsExceptionis the most common array bug — Always validate indices.- Use
lengthin loops — Never hardcode array sizes. - Enhanced
foris for reading — Use index-basedforwhen you need to modify elements. - Sort before binary search —
Arrays.binarySearch()requires sorted data. - Assignment copies references — Use
clone()orArrays.copyOf()for true copies. - 2D arrays are arrays of arrays — Each row can have different lengths (jagged arrays).
Arrays.toString()is your friend — Use it for quick debugging instead of manual loops.
What's Next?
Now that you can store and manipulate collections of data, you are ready for:
- ArrayList & Collections Framework — Dynamic sizing, rich API
- Object-Oriented Programming — Store data in custom objects (Student, Product)
- Sorting Algorithms — Bubble, Selection, Insertion, Merge, Quick sort
- String Manipulation — Character arrays, StringBuilder
- Exception Handling — Make array operations robust
- Multithreading — Process large arrays in parallel
Arrays are the foundation of data structures in Java. Master them, and every advanced topic — from collections to algorithms — becomes significantly easier.
SEO Keywords
java arrays tutorial, java 1d array, java 2d array, java multidimensional array, java array sorting, java linear search, java binary search, java array copy, java array best practices, learn java arrays, java array examples, java array traversal, java array length, java array index, java programming arrays, java beginner arrays
Found this guide helpful? Bookmark it and share it with fellow learners. For more Java tutorials, explore the Tech3Space Java Course.
Tags: #Java #Arrays #1DArray #2DArray #Sorting #BinarySearch #Programming #Tech3Space #CodingForBeginners