🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10

Java Arrays — Declare, Initialize, Traverse, 2D Arrays

Java BasicsArrays🟢 Free Lesson

Java Arrays — Declare, Initialize, Traverse, 2D Arrays

Learning Objectives

  • Declare and initialize single-dimensional arrays
  • Traverse arrays with loops and enhanced for loops
  • Explain array length and index rules
  • Create and read values from two-dimensional arrays

Overview

An array is a fixed-size container that holds one data type under a single name. Instead of creating score1, score2, and score3 as separate variables, you create one array named scores and access each slot by position. The position number is called an index, and Java indexes start at zero.

Arrays are objects in Java. That means an array variable holds a reference to a block of memory managed by the runtime, and the array knows its own length through a length field.

Declaring and Initializing

Declaration states the element type followed by square brackets. Initialization with the new keyword allocates space and fills numeric slots with zero, boolean slots with false, and reference slots with null.

int[] scores;                 // declare
scores = new int[5];          // create space for 5 ints
int[] values = new int[3];    // declare and create together

You may also initialize an array at creation time by listing values inside curly braces. The size then equals the number of items you provide.

int[] values = {10, 20, 30, 40};
String[] names = {"Ann", "Bob", "Cara"};
System.out.println(values.length); // 4

Index Rules

Each element has an index from zero up to length minus one. Reading or writing outside that range throws an ArrayIndexOutOfBoundsException at runtime. The compiler cannot always catch this because indexes may be computed.

Index0123
value10203040
int[] values = {10, 20, 30, 40};
values[0] = 99;          // replace first element
System.out.println(values[3]); // 40
// System.out.println(values[4]); // error: out of range

Traversing an Array

Traversal means visiting every element. A classic for loop with an index is the most flexible choice because you can read, modify, or compare positions. The enhanced for loop is shorter when you only need each value.

int[] values = {10, 20, 30, 40};
int total = 0;

for (int i = 0; i < values.length; i++) {
    total += values[i];
}

for (int value : values) {
    System.out.println(value);
}

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

Replace the placeholder mentally with values.length: the loop runs while i is less than the length. Forgetting the comparison and looping while i is less than or equal to length causes an out of range error on the final pass.

Searching and Updating

Two classic array tasks are finding a value and updating a value. Both use the same pattern: loop, compare, act.

int[] prices = {5, 12, 8, 20};
int target = 8;
int foundIndex = -1;

for (int i = 0; i < prices.length; i++) {
    if (prices[i] == target) {
        foundIndex = i;
        break;
    }
}

if (foundIndex == 1) {
    prices[foundIndex] = 9;
}

System.out.println(foundIndex);

Using negative one as a not found marker is a common convention because no real index equals negative one.

Two-Dimensional Arrays

A two-dimensional array is an array of arrays. Think of a table with rows and columns. The first index selects the row and the second selects the column.

int[][] grid = {
    {1, 2, 3},
    {4, 5, 6}
};

System.out.println(grid[0][0]); // 1
System.out.println(grid[1][2]); // 6
System.out.println(grid.length);       // 2 rows
System.out.println(grid[0].length);    // 3 columns

Nested loops print a matrix cleanly: the outer loop walks rows and the inner loop walks columns in the current row. Java allows rows of different lengths, which is called a ragged array, but beginners should keep rows even until the concept feels solid.

Array Limitations

Arrays are fast and simple, but their size is fixed after creation. Growing an array means creating a larger one and copying elements, which is tedious by hand. When you need a resizable list, the collections lessons on ArrayList will show a better tool. Use arrays for fixed tables of primitives and known sizes; use collections for dynamic data.

Key Takeaways

💡

  • Arrays store fixed numbers of same-typed elements and index from zero
  • length reports the capacity; valid indexes run from zero to length minus one
  • Enhanced for loops read values; indexed loops can update them
  • Two-dimensional arrays model rows and columns with nested indexes
  • Out of range access throws a runtime exception, so guard dynamic indexes

Practice Questions

  1. Create an array of five double values, print each with an indexed loop, and print the length.
  2. Why does a loop condition that uses length as an inclusive upper bound fail?
  3. Write nested loops that fill a 3 by 3 int table with values 1 through 9 and print it as a grid.

Extended Learning: Beyond the Basics

Key Concepts Summary

This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.

Prerequisite Knowledge

Before studying this topic in depth, ensure you understand:

  • Basic definitions and terminology
  • Core formulas and their derivations
  • Common applications in real-world scenarios
  • Typical pitfalls and misconceptions

Step-by-Step Walkthrough

Let us work through a complete example to solidify understanding:

Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.

Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.

Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.

Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.

Common Mistakes to Avoid

  1. Misidentifying the problem type — Always start by categorizing the problem
  2. Incorrect formula application — Verify the formula applies to your specific case
  3. Unit errors — Always check units are consistent throughout
  4. Sign errors — Pay careful attention to positive and negative values
  5. Rounding too early — Keep full precision until the final answer
  6. Forgetting constraints — Check that solutions satisfy all given conditions

Real-World Applications

Understanding this concept is essential for:

  • Advanced problem solving in examinations
  • Building intuition for more complex topics
  • Developing analytical thinking skills
  • Applying mathematical reasoning to practical situations

Practice Exercises

  1. Basic: Solve 5 problems of increasing difficulty using the core concept.
  2. Intermediate: Apply the concept to word problems with multiple steps.
  3. Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
  4. Challenge: Create your own problem that requires this concept plus additional knowledge.

Interview and Exam Tips

  • Common question patterns: Identify which exam or interview formats test this topic
  • Time management: Practice completing problems within time constraints
  • Common traps: Know the typical mistakes examiners set as distractors
  • Verification strategy: Develop a quick method to check your answer

Related Topics

Quick Reference Card

ConceptFormula/RuleKey InsightCommon Use
Core DefinitionSee main textUnderstand the intuitionFoundation for all applications
Key FormulaSee main textMemorize the derivationDirect problem solving
Special CaseSee main textRecognize when it appliesSimplifies complex problems
Edge CaseSee main textKnow the limitationsAvoids errors

Further Reading

For students who want to go deeper:

  • Standard textbooks on the subject
  • Research papers applying this concept
  • Online courses with video explanations
  • Practice problem collections with detailed solutions
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-11-14

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Java Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement