Java Arrays Real-Life Examples

📦 Java Arrays – Real-Life Examples

Arrays are widely used in Java to store collections of similar data. Here are some practical real-life examples of arrays.


1️⃣ Store Student Marks

public class Main {
public static void main(String[] args) {
int[] marks = {85, 90, 78, 92, 88}; // Marks of 5 students

int sum = 0;
for (int mark : marks) {
sum += mark;
}

double average = sum / (double) marks.length;
System.out.println("Average marks: " + average);
}
}

📌 Output:

Average marks: 86.6

2️⃣ Store Names of Employees

public class Main {
public static void main(String[] args) {
String[] employees = {"John", "Alice", "Bob", "Mary"};

System.out.println("Employee List:");
for (String employee : employees) {
System.out.println(employee);
}
}
}

📌 Output:

Employee List:
John
Alice
Bob
Mary

3️⃣ Daily Temperature of a Week

public class Main {
public static void main(String[] args) {
int[] temperature = {30, 32, 31, 29, 28, 27, 33};

for (int i = 0; i < temperature.length; i++) {
System.out.println("Day " + (i + 1) + " temperature: " + temperature[i] + "°C");
}
}
}

📌 Output:

Day 1 temperature: 30°C
Day 2 temperature: 32°C
Day 3 temperature: 31°C
Day 4 temperature: 29°C
Day 5 temperature: 28°C
Day 6 temperature: 27°C
Day 7 temperature: 33°C

4️⃣ Shopping Cart Prices

public class Main {
public static void main(String[] args) {
double[] prices = {499.99, 249.50, 150.00, 299.99};
double total = 0;

for (double price : prices) {
total += price;
}

System.out.println("Total price: $" + total);
}
}

📌 Output:

Total price: $1199.48

5️⃣ Track Attendance (Boolean Array)

public class Main {
public static void main(String[] args) {
boolean[] attendance = {true, true, false, true, false};

for (int i = 0; i < attendance.length; i++) {
if (attendance[i]) {
System.out.println("Day " + (i + 1) + ": Present");
} else {
System.out.println("Day " + (i + 1) + ": Absent");
}
}
}
}

📌 Output:

Day 1: Present
Day 2: Present
Day 3: Absent
Day 4: Present
Day 5: Absent

6️⃣ Product IDs (Integer Array)

public class Main {
public static void main(String[] args) {
int[] productIDs = {101, 102, 103, 104, 105};

System.out.println("Product IDs in the store:");
for (int id : productIDs) {
System.out.println(id);
}
}
}

📌 Output:

Product IDs in the store:
101
102
103
104
105

🧠 Key Takeaways

  • Arrays store multiple values of the same type.

  • Useful for real-life data like marks, names, prices, temperatures, attendance, IDs.

  • Loops (for, for-each, while) make it easy to iterate and process data.

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *