Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Java
  • Install Java 25 (JDK) and IntelliJ IDEA, Then Run Your First Program
  • Use Claude Agent, Copilot or Junie Inside IntelliJ IDEA
  • Java Hello World with Maven: What the JDK Does and What Maven Adds
  • Java Variables, Keywords and Naming Rules
  • Maven in IntelliJ: pom.xml, Dependencies and the Build Lifecycle
  • Java Primitive Types and Memory: What int x = 5 Really Does
  • Java Strings and Text Blocks: Quotes, Concatenation and parseInt
  • Java Operators: Arithmetic, a++ vs ++a, Precedence, && || and the Ternary
  • Java Type Casting: Widening, Narrowing and Converting Text to Numbers
  • Java Practice Lab: A Cafe Bill with Variables, Operators and Casting
  • Java if, else and switch: Braces, Else-If Ladders and the Modern Switch
  • Java Loops: for, while, do-while and for-each
  • Java break, continue and Nested Loops
  • What's New in Java 21 to 25: Compact Source Files and Sequenced Collections
  • Java Arrays: Indexes, Default Values, Loops and 2D Grids
  • Java Methods and Overloading: Parameters, return and Pass-by-Value
  • Java Scope, Code Blocks and the Call Stack
  • Read User Input in Java with Scanner (and the Leftover Enter Trap)
  • Java Practice Lab: A Gym Weekly Tracker with Loops, Arrays and Methods
  • Debugging Java in IntelliJ: Stack Traces, Breakpoints and a Better AI Prompt
  • Java var: Let Java Infer the Type
  • Push and Pull in IntelliJ: Two Developers, One GitHub Repository, a Rejected Push and a Conflict
  • Java Classes and Objects: One Blueprint, Many Cars
  • Java Constructors and the this Keyword
  • Java Instance Methods, Getters, Setters and toString
  • Java static: Fields, Methods and Blocks Shared by the Whole Class
  • Java Packages and Imports: Every Class Has an Address
  • Java Access Modifiers and Encapsulation: Private Data, Public Methods
  • Java final and Immutable Objects: Assign Once, Share Safely
  • Java Strings as Objects: The String Pool, == vs equals, StringBuilder and printf
  • Java Practice Lab: A Library Book Catalogue with final Fields and StringBuilder
  • Java Inheritance: extends, super and the Order Objects Are Built
  • Java Method Overriding, @Override and the Object Class
  • Java Polymorphism: Upcasting, Dynamic Dispatch and Downcasting
  • Java Composition: Has-A vs Is-A
  • Java Abstract Classes: A Parent That Leaves One Blank
  • Java Interfaces: Contracts and Multiple Inheritance
  • Java Nested, Inner and Anonymous Classes
  • Java Enums with Fields, Methods and switch
  • Java Practice Lab: Payment Processing with an Interface, an Abstract Class and an Enum
  • Java Records: A Whole Data Class in One Line
  • Java Sealed Classes and Interfaces
  • Java Pattern Matching with instanceof and switch
  • Java Record Patterns: Unpacking a Record
  • Java equals and hashCode: Why a HashSet Needs Both
  • From Arrays to Collections: The Java Collections Framework Map
  • Java Wrapper Classes and Autoboxing
  • Java ArrayList: The Stretchy Array
  • Java LinkedList vs ArrayList: Nodes or an Array
  • Java Sets: HashSet, LinkedHashSet and TreeSet
  • Java Sorting with Comparable and Comparator
  • Java Maps: HashMap, LinkedHashMap and TreeMap
  • Java Stacks, Queues and Deques: ArrayDeque and PriorityQueue
  • Choosing a Java Collection: Immutable and Sequenced Collections
  • Java Exception Handling: try, catch and finally
  • Java throw, throws, Checked vs Unchecked and Custom Exceptions
  • Java try-with-resources and Clean Error Handling
  • Java Generics: Type-Safe Containers
  • Java Generic Methods, Bounded Types and Wildcards
  • Java Lambdas and Functional Interfaces
  • Java Built-in Functional Interfaces: Predicate, Function, Consumer, Supplier
  • Java Optional: Saying Maybe Without null
  • Java Streams I: filter, map and reduce
  • Java Streams II: Collectors, groupingBy and flatMap
  • Why Concurrency: Processes, Threads and the Main Thread in Java
  • Creating Threads in Java: Thread, Runnable and Lambdas
  • Java Thread Lifecycle: sleep, join and interrupt
  • Java Race Conditions and synchronized
  • Java volatile and Atomic Variables
  • Java ExecutorService and Thread Pools
  • Java Callable, Future and CompletableFuture
  • Java Locks, Deadlock and tryLock
  • Java Concurrent Collections and Virtual Threads
  • Why Slow Work Belongs off the Request Thread: 202 Accepted and a Job Id in Spring Boot
  • Virtual Threads in Spring Boot: One Property, and the Connection Pool Trap
  • @Async, Named TaskExecutors and Structured Concurrency in Spring Boot
  • Java Files and Directories with NIO.2: Path and Files
  • Reading and Writing Text Files in Java
  • Java Structured Data: Reading and Writing JSON and CSV
  1. Blog
  2. /
  3. Java
  4. /
  5. Basics

Java Arrays: Indexes, Default Values, Loops and 2D Grids

An array is a row of numbered lockers: one name, a fixed size, indexes from 0. A week of temperatures shows defaults, braces, loops, the Arrays toolbox, the 'Index 7 out of bounds for length 7' error and a cinema seating grid.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Basics

What you will learn

  • Create an array with new int[7] or with braces, and read its length
  • Store and fetch values by a zero-based index and know each type's default
  • Loop over an array with a classic for and a for-each, and use Arrays.toString, sort and fill
  • Read an ArrayIndexOutOfBoundsException and build a 2D grid

Before you start

  • Java loops: for, while, do-while and for-each

You want a temperature for every day of the week. Seven separate variables would work, but a whole year would need 365 of them. An array solves this: one name, many numbered slots. Picture a row of numbered lockers in a gym.

int[] temps = new int[7] builds seven lockers numbered 0 to 6. temps[2] = 19 stores 19 in locker 2. There is no locker 7. int[] temps = new int[7]; temps[2] = 19; 0019 0000 [0][1][2] [3][4][5][6] no [7] Same-size slots, numbered from 0. The size is fixed when the row is built.
Seven lockers, indexes 0 to 6. Each new slot starts at the type's default, 0 for int.

int[] means "array of int". new int[7] builds seven lockers in one line. Each locker has a number, its index, and the index always starts at 0, so seven lockers are 0 to 6. temps[2] = 19 stores a value; int wed = temps[2] fetches it. The size is fixed: you can't bolt on an eighth locker later.

One line builds seven lockers

package org.studyeasy.s02l12;

public class Ex01_BuildRow {
    public static void main(String[] args) {
        // one line builds seven lockers, all holding int
        int[] temps = new int[7];
        System.out.println("Lockers: " + temps.length);
        System.out.println("Locker 0 starts as " + temps[0]);

        temps[0] = 21;
        System.out.println("Locker 0 now holds " + temps[0]);

        // every type has its own starting value
        double[] prices = new double[2];
        boolean[] present = new boolean[2];
        String[] guests = new String[2];
        System.out.println(prices[0] + " " + present[0] + " " + guests[0]);
    }
}
Lockers: 7
Locker 0 starts as 0
Locker 0 now holds 21
0.0 false null

temps.length gives 7. Note: no brackets after length. A new array is never full of junk; every slot gets a default:

Array typeEach slot starts as
int[]0
double[]0.0
boolean[]false
char[]the character with code 0
String[]null (no object yet)

Leave out the size, new int[], and javac says "array dimension missing".

Build it already full

package org.studyeasy.s02l12;

public class Ex02_Braces {
    public static void main(String[] args) {
        // the values are known, so Java counts the lockers for us
        int[] temps = {21, 24, 19, 26, 30, 28, 23};
        System.out.println("Length: " + temps.length);
        System.out.println("First: " + temps[0]);
        System.out.println("Last: " + temps[temps.length - 1]);

        int wed = temps[2];
        temps[2] = 17;
        System.out.println("Wednesday: " + wed + " then " + temps[2]);
    }
}
Length: 7
First: 21
Last: 23
Wednesday: 19 then 17
  • With braces, Java counts the values; there's no 7 anywhere.
  • The last index is length - 1: the length is 7, the last locker is 6.
  • wed kept a copy of the old 19, so changing temps[2] to 17 doesn't touch it.

The short brace form only works on the declaration line. Declare int[] temps; first and write temps = {21, 24}; later, and it won't compile. Write temps = new int[] {21, 24}; instead.

One loop walks every locker

package org.studyeasy.s02l12;

public class Ex03_Loops {
    public static void main(String[] args) {
        int[] temps = {21, 24, 19, 26, 30, 28, 23};

        // classic for: we need the locker number
        for (int i = 0; i < temps.length; i++) {
            System.out.println("Day " + i + ": " + temps[i]);
        }

        // for-each: we only need every value once
        int total = 0;
        for (int t : temps) {
            total += t;
        }
        System.out.println("Total: " + total);
        System.out.println("Average: " + total / (double) temps.length);
    }
}
Day 0: 21
Day 1: 24
Day 2: 19
Day 3: 26
Day 4: 30
Day 5: 28
Day 6: 23
Total: 171
Average: 24.428571428571427

The classic for gives you the index, and i < temps.length still fits if the array grows. The for-each gives you each value and nothing else, which is all you need for a total. The cast to double keeps the decimals in the average.

The Arrays toolbox

package org.studyeasy.s02l12;

import java.util.Arrays;

public class Ex04_Toolbox {
    public static void main(String[] args) {
        int[] temps = {21, 24, 19, 26, 30, 28, 23};
        System.out.println(Arrays.toString(temps));

        Arrays.sort(temps);
        System.out.println(Arrays.toString(temps));

        int[] scores = new int[5];
        Arrays.fill(scores, 10);
        System.out.println(Arrays.toString(scores));
    }
}
[21, 24, 19, 26, 30, 28, 23]
[19, 21, 23, 24, 26, 28, 30]
[10, 10, 10, 10, 10]

Arrays.toString prints the whole row. Print temps directly and you get something like [I@1b2c3d, a memory reference, not the numbers. Arrays.sort sorts in place (the original order is gone), and Arrays.fill sets every slot to one value.

There is no locker 7

package org.studyeasy.s02l12;

public class Ex05_OutOfBounds {
    public static void main(String[] args) {
        int[] temps = {21, 24, 19, 26, 30, 28, 23};
        // lockers 0 to 6 exist, so locker 7 stops the program
        try {
            System.out.println(temps[7]);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Caught: " + e.getMessage());
        }
    }
}
Caught: Index 7 out of bounds for length 7

This compiles fine and fails at run time. (The try/catch only lets us print the message; exceptions come later.) Read the message literally: it names the index you asked for and the length that exists. The usual cause is a loop with <= instead of <: i <= temps.length asks for locker 7 on its last pass.

Stack the rows into a grid

package org.studyeasy.s02l12;

import java.util.Arrays;

public class Ex06_Seats {
    public static void main(String[] args) {
        // 3 rows of 4 seats, 0 = free
        int[][] seats = new int[3][4];
        seats[1][2] = 1; // Priya books row 1, seat 2

        System.out.println("Rows: " + seats.length + ", seats per row: " + seats[0].length);
        for (int[] row : seats) {
            System.out.println(Arrays.toString(row));
        }
    }
}
Rows: 3, seats per row: 4
[0, 0, 0, 0]
[0, 0, 1, 0]
[0, 0, 0, 0]

new int[3][4] is an array whose slots are arrays: three rows of four seats, like a cinema. The first index is the row, the second is the seat, and both start at 0. seats.length counts rows; seats[0].length counts seats in a row. seats[3][0] fails: there are only rows 0 to 2.

Recap

IdeaCode
Build emptynew int[7]
Build full{21, 24, 19} on the declaration line
Sizetemps.length (no brackets)
First / lasttemps[0] / temps[temps.length - 1]
Print, sort, fillArrays.toString, Arrays.sort, Arrays.fill
Out of boundsAn index below 0 or at length or above
Gridnew int[3][4], seats[row][seat]

Arrays have a fixed size. When you need a row that grows, you'll reach for ArrayList.

Keep going in Java · 15 of 79

Previous
What's New in Java 21 to 25: Compact Source Files and Sequenced Collections
Next post
Java Methods and Overloading: Parameters, return and Pass-by-Value
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE

Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)

Related posts

Install Java 25 (JDK) and IntelliJ IDEA, Then Run Your First Program

Install JDK 25 (Microsoft Build of OpenJDK) with JAVA_HOME, install IntelliJ IDEA, then point a run configuration at the JDK and the main class and run Hello World.

Use Claude Agent, Copilot or Junie Inside IntelliJ IDEA

Open IntelliJ's AI Chat, pick Claude Agent (the agent behind Claude Code) or Copilot and a model, ask in plain words for Main.java to print the date and time, review the change, and run it.

Java Hello World with Maven: What the JDK Does and What Maven Adds

javac compiles HelloWorld.java into bytecode and java runs it on the JVM. Maven adds one pom.xml, the same folders in every project and one build command. Then a real Maven Hello World in IntelliJ.

Java Variables, Keywords and Naming Rules

A variable is a labelled jar that holds one value at a time. Four small programs show declaring, reassigning, the names Java accepts, the keywords it reserves, and why daysUntilLaunch beats d.

On this page

  • One line builds seven lockers
  • Build it already full
  • One loop walks every locker
  • The Arrays toolbox
  • There is no locker 7
  • Stack the rows into a grid
  • Recap
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE

Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.