Notifications
Clear all
Topic starter 01/08/2025 11:56 pm
📦 What is an Array in Java?
An array is a container object that holds a fixed number of values of a single type. Think of it like a row of mailboxes, each storing a value and indexed by a number.
🛠️ Declaring and Creating Arrays
int[] numbers; // Declaration
numbers = new int[5]; // Creation with 5 elements
You can also declare and create at the same time:
int[] numbers = new int[5];
🌱 Initializing with Values
You can fill an array with values right away:
int[] scores = {90, 85, 70, 95, 88};
Now scores[0]
is 90
, scores[1]
is 85
, etc.
🔍 Accessing and Changing Values
Java arrays use zero-based indexing, meaning the first element is at index 0.
System.out.println(scores[2]); // Prints: 70
scores[2] = 75; // Changes third value to 75
📏 Finding the Array Length
System.out.println(scores.length); // Prints: 5
Note: length
is a property, not a method—no parentheses!
🔄 Looping Through Arrays
You can loop through an array using a for
loop:
for (int i = 0; i < scores.length; i++) {
System.out.println(scores[i]);
}
Or use an enhanced for-each
loop:
for (int score : scores) {
System.out.println(score);
}