🎮 Java Arrays Made Easy! 🎮
📦What is an Array?
An Array is like a row of lockers or boxes in a train!
Imagine you have 5 pencils and you want to store them in a pencil box with 5 slots. Each slot holds one pencil!
🖍️ | 🖍️ | 🖍️ | 🖍️ | 🖍️
That’s exactly what an array is – a container that holds multiple items of the same type!
Think of an array as a train with compartments:
Each box has a number (called index) starting from 0!
• Arrays hold multiple items of the same type (all numbers, all strings, etc.)
• Each item has a position number called an index
• Index always starts from 0, not 1!
• Array size is fixed – once created, you can’t make it bigger or smaller
✨How to Create an Array?
Method 1: Declare and Create Together
Tell Java: “I want 5 boxes for numbers!”
// Create an array that can hold 5 integers
int[] numbers = new int[5];// Create an array that can hold 3 stringsString[] names = new String[3];
// Create an array for 10 decimal numbers
double[] prices = new double[10];
dataType[] arrayName = new dataType[size];
• dataType: What type of items? (int, String, double, etc.)
• []: This tells Java it’s an array
• arrayName: Give it a name (like “numbers” or “scores”)
• size: How many items can it hold?
Method 2: Create and Fill with Values Right Away
Create an array and put items in it immediately!
// Create array with 5 numbers already inside
int[] scores = {95, 87, 92, 78, 88};// Create array with student namesString[] students = {“John”, “Emma”, “Alex”, “Sophia”};
// Create array with prices
double[] prices = {19.99, 25.50, 12.75};
This creates:
public class ArrayExample {
public static void main(String[] args) {
// Method 1: Create empty array, then fill it
int[] ages = new int[3];
ages[0] = 10;
ages[1] = 12;
ages[2] = 11;// Method 2: Create and fill togetherString[] colors = {“Red”, “Blue”, “Green”};
System.out.println(“First age: ” + ages[0]);
System.out.println(“Second color: ” + colors[1]);
}
}
First age: 10
Second color: Blue
🔢Accessing Array Elements
To get or change an item in an array, use its index number inside square brackets [ ]
Array: fruits
Apple
Banana
Orange
Mango
String[] fruits = {"Apple", "Banana", "Orange", "Mango"};// GET (Read) values from arraySystem.out.println(fruits[0]); // Apple
System.out.println(fruits[2]); // Orange
// SET (Change) values in array
fruits[1] = “Strawberry”; // Change Banana to Strawberry
System.out.println(fruits[1]); // Strawberry
// Get first and last items
System.out.println(“First: ” + fruits[0]);
System.out.println(“Last: ” + fruits[3]);
Apple
Orange
Strawberry
First: Apple
Last: Mango
If your array has 5 items (index 0 to 4), don’t try to access index 5 or higher!
This will cause an
ArrayIndexOutOfBoundsException error!
fruits[10] // ❌ ERROR if array only has 4 items!
📏Array Length
Want to know how many items are in an array? Use the length property!
String[] fruits = {"Apple", "Banana", "Orange", "Mango"};int numberOfFruits = fruits.length;System.out.println(“Total fruits: ” + numberOfFruits);
int[] scores = {95, 87, 92, 78, 88, 91};
System.out.println(“Total scores: ” + scores.length);
Total fruits: 4
Total scores: 6
Use
.length to find the last item safely:
fruits[fruits.length - 1] // Gets the last item!
Why -1? Because if array has 4 items, last index is 3 (not 4)!
🔄Looping Through Arrays
Want to do something with EVERY item in an array? Use loops!
Method 1: Traditional For Loop
int[] scores = {95, 87, 92, 78, 88};System.out.println(“All Scores:”);for(int i = 0; i < scores.length; i++) {
System.out.println(“Score ” + (i+1) + “: ” + scores[i]);
}
All Scores:
Score 1: 95
Score 2: 87
Score 3: 92
Score 4: 78
Score 5: 88
Method 2: Enhanced For Loop (For-Each)
Simpler way when you don’t need the index number!
String[] colors = {"Red", "Blue", "Green", "Yellow"};System.out.println(“My favorite colors:”);for(String color : colors) {
System.out.println(“❤️ ” + color);
}
My favorite colors:
❤️ Red
❤️ Blue
❤️ Green
❤️ Yellow
Regular For Loop
Use when:
• You need the index number
• You want to modify array values
• You want to loop backwards
for(int i=0; i<arr.length; i++)
For-Each Loop
Use when:
• You just want to read values
• You don’t need the index
• Simpler, cleaner code
for(Type item : array)
🧮Common Array Operations
1️⃣ Finding Sum and Average
int[] scores = {95, 87, 92, 78, 88};// Calculate sumint sum = 0;
for(int score : scores) {
sum = sum + score;
}
// Calculate average
double average = (double) sum / scores.length;
System.out.println(“Total: ” + sum);
System.out.println(“Average: ” + average);
Total: 440
Average: 88.0
2️⃣ Finding Maximum and Minimum
int[] numbers = {45, 12, 78, 23, 67, 34};int max = numbers[0]; // Start with first numberint min = numbers[0];
for(int num : numbers) {
if(num > max) {
max = num; // Found bigger number!
}
if(num < min) {
min = num; // Found smaller number!
}
}
System.out.println(“Highest: ” + max);
System.out.println(“Lowest: ” + min);
Highest: 78
Lowest: 12
3️⃣ Searching for a Value
String[] students = {"John", "Emma", "Alex", "Sophia", "Liam"};
String searchName = "Alex";
boolean found = false;
int position = -1;for(int i = 0; i < students.length; i++) {if(students[i].equals(searchName)) {
found = true;
position = i;
break; // Stop searching once found!
}
}
if(found) {
System.out.println(“✅ Found ” + searchName + ” at position ” + position);
} else {
System.out.println(“❌ ” + searchName + ” not found”);
}
✅ Found Alex at position 2
4️⃣ Counting Specific Items
int[] grades = {95, 87, 92, 78, 95, 88, 95, 91};
int target = 95;
int count = 0;for(int grade : grades) {if(grade == target) {
count++;
}
}
System.out.println(“Number of students who got ” + target + “: ” + count);
Number of students who got 95: 3
📊Multi-Dimensional Arrays (2D Arrays)
A 2D array is like a table with rows and columns – or a grid!
Think of it like a classroom seating chart:
| Column 0 | Column 1 | Column 2 |
|---|---|---|
| Row 0: John | Emma | Alex |
| Row 1: Sophia | Liam | Olivia |
| Row 2: Noah | Ava | Ethan |
Creating a 2D Array
// Create a 3x3 grid (3 rows, 3 columns)
int[][] grid = new int[3][3];// Create and fill a 2D array with valuesint[][] scores = {
{95, 87, 92}, // Row 0
{78, 88, 91}, // Row 1
{85, 90, 88} // Row 2
};
// Another example: Tic-Tac-Toe board
String[][] board = {
{“X”, “O”, “X”},
{“O”, “X”, “O”},
{“X”, “O”, “X”}
};
Accessing 2D Array Elements
int[][] scores = {
{95, 87, 92},
{78, 88, 91},
{85, 90, 88}
};// Access specific element: [row][column]System.out.println(“Row 0, Column 1: ” + scores[0][1]); // 87
System.out.println(“Row 2, Column 2: ” + scores[2][2]); // 88
// Change a value
scores[1][0] = 80; // Change 78 to 80
System.out.println(“Updated: ” + scores[1][0]);
Row 0, Column 1: 87
Row 2, Column 2: 88
Updated: 80
Looping Through 2D Arrays
int[][] scores = {
{95, 87, 92},
{78, 88, 91},
{85, 90, 88}
};System.out.println(“All Scores:”);for(int row = 0; row < scores.length; row++) {
System.out.print(“Row ” + row + “: “);
for(int col = 0; col < scores[row].length; col++) {
System.out.print(scores[row][col] + ” “);
}
System.out.println(); // New line after each row
}
All Scores:
Row 0: 95 87 92
Row 1: 78 88 91
Row 2: 85 90 88
🎮Fun Projects with Arrays!
public class GradeCalculator {
public static void main(String[] args) {
String[] subjects = {"Math", "Science", "English", "History"};
int[] scores = {95, 87, 92, 88};System.out.println(“📊 Student Report Card”);System.out.println(“=” .repeat(30));
int total = 0;
for(int i = 0; i < subjects.length; i++) { System.out.println(subjects[i] + “: ” + scores[i]); total += scores[i]; } double average = (double) total / scores.length; System.out.println(“=” .repeat(30)); System.out.println(“Total: ” + total); System.out.println(“Average: ” + average); // Determine grade if(average >= 90) {
System.out.println(“Grade: A – Excellent! 🌟”);
} else if(average >= 80) {
System.out.println(“Grade: B – Good Job! 👍”);
} else if(average >= 70) {
System.out.println(“Grade: C – Keep Trying! 💪”);
}
}
}
📊 Student Report Card
==============================