Skip to content
QuizMaker logoQuizMaker
Activity
Java Programming: From Zero to Enterprise
1. Java Fundamentals
1. Getting Started with Java & the JVM
2. Data Types & Variables
3. Control Flow: Ifs & Loops
4. String Manipulation in Depth
5. Methods (Functions) Architecture
6. Arrays & The Enhanced For Loop
7. User Input via Scanner
8. Mathematical Operations & The Math Class
9. Operators in Depth
10. Block Scope & Variable Lifecycles
11. Introduction to Object-Oriented Programming
12. Classes & Instances Deep Dive
13. Constructors
14. Encapsulation & The 'this' Keyword
15. Inheritance: Extending Functionality
16. Polymorphism & Method Overriding
17. Abstraction & Abstract Classes
18. Interfaces: The Ultimate Contract
19. Packages & Access Modifiers
20. Enums (Enumerations)
21. Exceptions: Handling Runtime Errors
22. The 'throw' and 'throws' keywords
23. Dates, Times, and Formatting
24. Enumerable Data Structures
25. LinkedLists: The Alternative
26. HashMaps: Key-Value Architecture
27. HashSets: The Art of Uniqueness
28. Iterator: Safe Collection Traversal
29. Wrapper Classes & Autoboxing
30. Basic File I/O
31. Generics: Type-Safe Templates
32. Lambda Expressions & Functional Interfaces
33. The Stream API: Functional Data Pipelines
34. Optional: Beating the NullPointerException
35. Multithreading & Concurrency Basics
36. JDBC: Connecting to SQL Databases
37. Annotations & Reflection
38. The JVM Garbage Collector
39. Introduction to Spring Boot
40. Unit Testing with JUnit
41. Java Collections for DSA
CONTENTS

6. Arrays & The Enhanced For Loop

Storing multiple values in a single variable sequence.

Java Programming: From Zero to Enterprise
1. Java Fundamentals
February 22, 2026
97
A

[!NOTE] Often, you'll need to store a list of related data—like 50 high scores or 10 usernames. Instead of creating 50 separate integer variables, you can store them in a single Array.

Declaring and Initializing Arrays

An Array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is strictly fixed.

// Method 1: Literal Initialization (when you know the values upfront)
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
int[] myScores = {10, 20, 30, 40};

// Method 2: Size Initialization (when you just want to reserve space)
int[] blankArray = new int[5]; // Creates space for 5 integers, all defaulting to 0

Accessing Elements

You access an array element by referring to the index number. Array indexes start with 0. [0] is the first element, [1] is the second, etc.

String[] cars = {"Volvo", "BMW", "Ford"};
System.out.println(cars[0]); // Outputs "Volvo"

// Modifying an element
cars[0] = "Opel"; 
System.out.println(cars[0]); // Now Outputs "Opel"

[!CAUTION] If you create an array of size 3, and try to access cars[3], you will get a catastrophic ArrayIndexOutOfBoundsException. Remember, a size 3 array only has indexes 0, 1, 2.

Looping Through Arrays

To iterate over every element in an array, you have two amazing options.

Standard For Loop

Use this if you need to know the exact index you are currently processing.

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (int i = 0; i < cars.length; i++) {
  System.out.println("Car at index " + i + " is: " + cars[i]);
}

The Enhanced For-Each Loop

Introduced in Java 5, this loop cleanly iterates through the elements without you having to manage an index counter.

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (String i : cars) {
  System.out.println(i);
}

Arrays as Fixed-Size Building Blocks

Arrays are simple and fast because their size is fixed. That fixed size is both their strength and their limitation. If you know you need exactly 7 daily temperatures or exactly 100 marks, an array is natural. If the number of items grows and shrinks often, ArrayList is usually more convenient.

Default Values

When you create an array with a size but no values, Java fills it with defaults.

int[] scores = new int[3];       // [0, 0, 0]
boolean[] flags = new boolean[2]; // [false, false]
String[] names = new String[2];   // [null, null]

The null default for object arrays matters. If you call a method on a null element, the program can fail.

Finding the Maximum Value

int[] marks = {72, 91, 64, 88};
int max = marks[0];

for (int i = 1; i < marks.length; i++) {
    if (marks[i] > max) {
        max = marks[i];
    }
}

System.out.println("Highest marks: " + max);

When Index Loops Beat For-Each

Use a normal for loop when you need the index, want to update values, or need to compare neighboring elements. Use enhanced for when you only need to read every value.

Mini Practice

Create an array of five marks. Print the total, average, highest mark, and the number of students who scored at least 60.

Practice Lab: Analyze Marks With Arrays

Use one array to calculate several useful results.

  1. Create int[] marks = {72, 39, 88, 91, 55};.
  2. Find the total and average.
  3. Find the highest mark.
  4. Count failed marks below 40.
  5. Print every mark with its index.

Goal: Practice index loops, enhanced loops, array length, and basic aggregation.

Revision Checkpoint

  • Fixed size: Array length cannot change after creation.
  • Zero index: First element is at index 0.
  • Last index: array.length - 1.
  • Index loop: Best when index matters or values need updating.
  • Enhanced loop: Best for reading every value simply.

Before the quiz: Predict what happens when code accesses arr[arr.length].

Share this article

Share on TwitterShare on LinkedInShare on FacebookShare on WhatsAppShare on Email

Test your knowledge

Take a quick quiz based on this chapter.

easyJava
Quiz: Arrays
10 questions5 min
Lesson 6 of 10 in 1. Java Fundamentals
Previous in 1. Java Fundamentals
5. Methods (Functions) Architecture
Next in 1. Java Fundamentals
7. User Input via Scanner
Back to Java Programming: From Zero to Enterprise
Back to moduleCategories