Java Arrays

Su Suriya Ravichandran Updated 14 Nov 2026
7 min read ·Lesson 23 of 306

An array stores a fixed number of values of the same type in a single variable. Instead of declaring score1, score2, score3, you declare one array scores and reach each value by its position. This lesson covers the essentials; the Arrays and Collections section later covers copying, sorting, searching, and multidimensional arrays in depth.

Declaring and Creating Arrays

int[] scores = new int[5];               // five ints, all 0
String[] names = new String[3];          // three Strings, all null
double[] prices = {19.99, 5.49, 120.0};  // created and filled in one step

Reading the declaration int[] scores: the type is int[] ("array of int"), and the variable is scores.

There are two ways to create an array:

FormWhen to useExample
new Type[size]Size known, values filled in laternew int[100]
{v1, v2, ...}Values known when writing the code{"red", "green", "blue"}

The brace form (an array initializer) works only in a declaration. To assign a new array to an existing variable, include new and the type:

int[] nums;
nums = {1, 2, 3};               // compile error
nums = new int[]{1, 2, 3};      // correct

Java also accepts the C-style int scores[], but int[] scores keeps the whole type in one place and is the standard style.

Default Values

An array created with new has every element set to the type's default:

Element typeDefault
int, long, short, byte0
double, float0.0
booleanfalse
char'\u0000'
Any object type (String, etc.)null
String[] names = new String[3];
System.out.println(names[0]);            // null
System.out.println(names[0].length());   // NullPointerException

An array of objects holds references, which start as null. Each element must be assigned an object before it is used.

Accessing Elements

Elements are numbered from 0. An array of length 5 has indexes 0 through 4.

index:   0     1     2     3     4
       [ 90 ][ 75 ][ 88 ][ 62 ][ 95 ]
int[] scores = {90, 75, 88, 62, 95};

System.out.println(scores[0]);   // 90 (first)
System.out.println(scores[4]);   // 95 (last)

scores[1] = 80;                  // replace the second element
System.out.println(scores[1]);   // 80

Indexing starts at 0 because the index is an offset from the start of the array: the first element is zero positions from the beginning.

Out-of-bounds access

Java checks every index at runtime. An index below 0 or at or beyond the length throws an exception:

int[] a = new int[3];
a[3] = 10;    // ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3

In C, the same write would silently overwrite other memory. Java's bounds checking turns that class of bug into an immediate, clear error.

Length

Every array has a length field giving its number of elements:

String[] colors = {"red", "green", "blue"};
System.out.println(colors.length);                // 3
System.out.println(colors[colors.length - 1]);    // blue (last element)

length is a field, not a method: no parentheses. (Strings use length(), a method; collections use size(). The inconsistency is historical.)

An array's length is fixed when it is created and cannot change. To hold more elements, you must create a new, larger array and copy the values over, which is exactly what ArrayList does internally. When the number of items is not known in advance, use ArrayList instead of an array.

Looping Through an Array

double[] prices = {19.99, 5.49, 120.0, 42.5};

// index loop: when the position is needed
for (int i = 0; i < prices.length; i++) {
    System.out.println("Item " + (i + 1) + ": " + prices[i]);
}

// enhanced for loop: when only the values are needed
double total = 0;
for (double p : prices) {
    total += p;
}
System.out.printf("Total: %.2f%n", total);

The loop condition i < prices.length stops exactly after the last valid index. Writing i <= prices.length is a classic off-by-one error that throws on the final iteration.

Common Operations

Finding the maximum

int[] temps = {31, 34, 29, 36, 33};
int max = temps[0];
for (int i = 1; i < temps.length; i++) {
    if (temps[i] > max) {
        max = temps[i];
    }
}
System.out.println("Highest: " + max);   // 36

max starts at the first element rather than 0, so the result is correct even if every value is negative. The loop then starts at index 1, since index 0 is already accounted for. (This assumes the array is not empty.)

Counting matches

int[] marks = {72, 45, 88, 39, 91, 55};
int passed = 0;
for (int m : marks) {
    if (m >= 50) passed++;
}
System.out.println(passed + " of " + marks.length + " passed");   // 4 of 6 passed

The Arrays Utility Class

java.util.Arrays provides static methods for everyday array tasks:

import java.util.Arrays;

int[] nums = {5, 3, 9, 1, 7};

System.out.println(Arrays.toString(nums));   // [5, 3, 9, 1, 7]

Arrays.sort(nums);
System.out.println(Arrays.toString(nums));   // [1, 3, 5, 7, 9]

int idx = Arrays.binarySearch(nums, 7);      // 3 (array must be sorted)

int[] filled = new int[4];
Arrays.fill(filled, -1);                     // [-1, -1, -1, -1]

int[] bigger = Arrays.copyOf(nums, 7);       // [1, 3, 5, 7, 9, 0, 0]

boolean same = Arrays.equals(nums, new int[]{1, 3, 5, 7, 9});   // true

Printing an array directly gives something like [I@1b6d3586 (a type code and hash), not its contents, because arrays do not override toString. Use Arrays.toString for display.

Similarly, == and equals on arrays compare identity, not contents. Use Arrays.equals to compare element by element.

Arrays Are Reference Types

An array variable holds a reference to the array object. Assigning it to another variable copies the reference, not the elements:

int[] original = {1, 2, 3};
int[] alias = original;
alias[0] = 99;
System.out.println(original[0]);   // 99: both variables refer to one array

int[] copy = original.clone();      // or Arrays.copyOf(original, original.length)
copy[1] = 50;
System.out.println(original[1]);   // 2: the copy is independent

The same applies when passing an array to a method: the method receives a reference and can change the caller's array.

static void doubleAll(int[] values) {
    for (int i = 0; i < values.length; i++) {
        values[i] *= 2;
    }
}

int[] data = {1, 2, 3};
doubleAll(data);
System.out.println(Arrays.toString(data));   // [2, 4, 6]

Two-Dimensional Arrays (Preview)

An array can hold other arrays, forming a grid:

int[][] seats = {
    {1, 0, 1},
    {0, 0, 1}
};
System.out.println(seats[1][2]);   // 1: row 1, column 2
System.out.println(seats.length);      // 2 rows
System.out.println(seats[0].length);   // 3 columns in row 0

Multidimensional arrays have their own lesson.

Arrays Versus ArrayList

ArrayArrayList
SizeFixed at creationGrows and shrinks
Element typesPrimitives or objectsObjects only (Integer, not int)
Syntaxa[i], a.lengthlist.get(i), list.size()
PerformanceLowest overhead; primitives stored directlySmall overhead; boxing for numbers
Typical useFixed-size data, numeric work, low-level codeMost application code where size varies

Practical Example: Weekly Step Tracker

import java.util.Arrays;

public class StepTracker {
    public static void main(String[] args) {
        String[] days = {"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"};
        int[] steps = {8200, 10450, 6300, 12000, 9100, 15200, 4300};
        int goal = 10_000;

        int total = 0;
        int goalDays = 0;
        int bestDay = 0;

        for (int i = 0; i < steps.length; i++) {
            total += steps[i];
            if (steps[i] >= goal) {
                goalDays++;
            }
            if (steps[i] > steps[bestDay]) {
                bestDay = i;
            }
        }

        double average = (double) total / steps.length;

        System.out.println("Steps:        " + Arrays.toString(steps));
        System.out.printf("Average:      %.0f%n", average);
        System.out.println("Goal reached: " + goalDays + " of " + days.length + " days");
        System.out.println("Best day:     " + days[bestDay] + " (" + steps[bestDay] + ")");
    }
}

Output:

Steps:        [8200, 10450, 6300, 12000, 9100, 15200, 4300]
Average:      9364
Goal reached: 3 of 7 days
Best day:     Sat (15200)

Two parallel arrays share indexes: days[i] names the day whose count is steps[i]. The loop uses an index so it can track which day is best (bestDay) rather than only the best value. (double) total / steps.length prevents integer division. Parallel arrays are fine for small examples; in larger programs, a record such as record DayStats(String day, int steps) in a single array or list keeps related values together.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java Arrays and get answers drawn from it.

Signed-in readers only.