Ever wondered how a video game keeps track of scores for each player? That's an array in disguise!
In Simple Words: An array is like a row of numbered lockers. Each locker (or slot) holds one piece of data, and you can open any locker by its number.
What is an Array in Java?
In Java, an array is a collection that stores several values of the same type in a single variable. Think of it as a train with many cars; each car holds a passenger (a value) and you can hop into any car by knowing its position.
How to Declare and Initialize Arrays
First you declare the array – tell Java what kind of data it will hold. Then you initialize it – actually create the slots.
Example:
int[] marks = new int[5]; // five slots for integers
Here int is the data type (whole numbers), [] tells Java it’s an array, and new int[5] creates five empty slots.
You can also give the array values right away:
int[] marks = {78, 85, 92, 67, 88};
That’s called array initializer. It’s like walking into a locker room and finding each locker already filled with a specific item.
Accessing Array Elements
Each slot has an index – a number starting from 0. So the first element is at index 0, the second at index 1, and so on.
System.out.println(marks[0]); // prints 78
If you try to use an index that doesn’t exist, Java throws an ArrayIndexOutOfBoundsException – basically a “you’re out of the locker range” error.
Common Array Operations
- Finding length:
marks.lengthgives the number of slots (5 in our example). - Looping through: The classic
forloop lets you visit each locker.for(int i = 0; i
- For‑each loop: A shorter way when you only need the value, not the index.
for(int score : marks){ System.out.println(score); } - Updating a value: Just assign a new one.
marks[2] = 95; // changes third score to 95
Multidimensional Arrays
Sometimes you need a grid, like a chess board. That’s a two‑dimensional array – an array of arrays.
int[][] matrix = new int[3][4]; // 3 rows, 4 columns
You can picture it as a table of lockers: rows are the outer lockers, columns are the inner ones.
Filling it:
int[][] matrix = {
{1,2,3,4},
{5,6,7,8},
{9,10,11,12}
};
Accessing a value uses two indices: matrix[1][2] gives the element in the second row, third column (value 7).
Quick Summary Table
| Aspect | One‑Dimensional | Two‑Dimensional |
|---|---|---|
| Structure | Single row of slots | Table (rows × columns) |
| Declaration | type[] name; | type[][] name; |
| Access | name[index] | name[row][col] |
| Typical use | List of scores, names | Matrix math, game board |
Tips for Remembering Arrays
- Index starts at 0 – like the first floor in a building (ground floor).
- Length is a property, not a method:
arr.length(no parentheses). - Use
for‑eachwhen you don’t need the index; it’s safer. - Never go beyond
arr.length‑1or you’ll get an error.
📝 Likely Exam Questions
- Write a Java program to store five student marks in an array and display the highest mark.
Model answer: Declareint[] marks = new int[5];, read values, loop with a variablemaxinitialized tomarks[0], updatemaxif a larger value is found, finally printmax. - Explain what happens if you try to access
arr[10]whenarrwas declared asnew int[5].
Model answer: Java throws anArrayIndexOutOfBoundsExceptionbecause index 10 exceeds the valid range 0‑4. - How do you declare and initialise a 2‑D array for a 3×3 tic‑tac‑toe board?
Model answer:char[][] board = {{' ',' ',' '},{' ',' ',' '},{' ',' ',' '}};(each inner brace represents a row). - What is the difference between a
forloop and afor‑eachloop when working with arrays?
Model answer: Aforloop gives you the index, so you can modify or locate elements; afor‑eachloop directly gives each element value, making the code shorter but you cannot change the original array element via the loop variable. - Write a code snippet to reverse the elements of an integer array.
Model answer: Use two indices,i=0andj=arr.length‑1, swaparr[i]andarr[j], then incrementiand decrementjuntil they meet.