An array stores a fixed number of values of the same type. In Java, arrays are objects: they live on the heap, know their own length, and every index is checked at run time.
Creating arrays#
int[] marks = new int[5]; // 5 zeros
int[] primes = {2, 3, 5, 7, 11}; // with values
String[] names = new String[3]; // 3 nulls
double[] prices = new double[]{9.5, 12.0};
First: 78, last: 71 marks[0] = 78 marks[1] = 92 marks[2] = 70 marks[3] = 88 marks[4] = 71 Average: 79.8 false null
Java में array एक object है - उसका size length से मिलता है (बिना brackets)। Index 0 से शुरू होता है। अगर आप गलत index (जैसे marks[5]) इस्तेमाल करें तो C की तरह चुपचाप गलत value नहीं मिलती, बल्कि ArrayIndexOutOfBoundsException आती है - इससे bugs जल्दी पकड़ में आते हैं।
Error: Index 3 out of bounds for length 3
The Arrays class#
java.util.Arrays has ready-made helpers:
6 elements: [64, 25, 12, 22, 11, 90] Sorted: [11, 12, 22, 25, 64, 90] Index of 22: 2 Copy: [11, 12, 22, 25, 64, 90, 0, 0] Part: [12, 22, 25] Filled: [7, 7, 7, 7] Equal? false [Bhopal, Indore, Ujjain]
Arrays are references#
Assigning an array variable copies the reference, not the elements:
a = [99, 2, 3] a = [99, 2, 3], c = [99, 55, 3]
This also means a method that receives an array can change the caller's elements.
Common algorithms#
Reversed: [42, 23, 16, 15, 8, 4] 15 at index 3 Rotated: [16, 15, 8, 4, 42, 23] 1:2 3:3 9:1
2D arrays#
A 2D array is an array of arrays. Each row can even have a different length (a jagged array):
Student 0 total 253, average 84.3 Student 1 total 207, average 69.0 Student 2 total 275, average 91.7 1 1 1 1 2 1
Matrix multiplication#
[[19, 22], [43, 50]]
Summary#
- Arrays are fixed-size objects; use
.length; indexes are checked (exceptions for bad indexes). - Default values: 0, false, or null.
Arrays.toString,sort,binarySearch,copyOf,fill,equals,deepToStringsave time.- Array variables hold references - use
clone()orArrays.copyOfto copy. - 2D arrays are arrays of rows; rows can have different lengths.