Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

Java Dictionary

  1. Home
  2. Java Dictionary
  3. Array Basics (Java)

Array Basics (Java)

A data structure that manages a sequence of values of the same type. Arrays in Java have a fixed length determined at declaration time and cannot be resized afterward. Indexes start at 0, and .length returns the number of elements. This page covers declaring and initializing one-dimensional and multi-dimensional arrays, accessing elements, converting to a string with Arrays.toString(), and when to use ArrayList instead when a variable-length collection is needed.

Syntax

import java.util.Arrays;

// Declare and initialize a 1D array (specify length with new)
type[] varName = new type[length];

// Declare and initialize a 1D array (list initial values directly)
type[] varName = {value0, value1, value2, ...};

// Access an element by index (index starts at 0)
varName[index]

// Get the number of elements in the array
varName.length

// Convert an array to a string with Arrays.toString() (useful for debugging and printing)
Arrays.toString(varName)

// Declare and initialize a 2D array
type[][] varName = new type[rows][cols];

// Declare a 2D array with initial values
type[][] varName = {
    {value, value, ...},
    {value, value, ...},
};

// Convert a 2D array to a string
Arrays.deepToString(varName)

Array Characteristics

CharacteristicDescription
Fixed lengthThe length is determined at declaration time and cannot be changed afterward.
Zero-based indexThe first element is accessed with [0], and the last with [length - 1].
Default valuesElements allocated with new are initialized to their default values (0 for int, null for String).
Reference typeAn array variable holds a reference to an object. == compares references, not contents. Use Arrays.equals() to compare contents.
Multi-dimensional arraysImplemented as arrays of arrays. int[][] is "an array of int arrays".

Sample Code

ArrayBasic.java
import java.util.Arrays;

public class ArrayBasic {
    public static void main(String[] args) {

        // --- Declare and initialize an array (specify length with new) ---
        // Allocate an array of length 4. Each element is initialized to its default value (null).
        String[] fighters = new String[4];

        // Assign values by specifying the index. Indexes start at 0.
        fighters[0] = "草薙京";   // KOF protagonist
        fighters[1] = "八神庵";
        fighters[2] = "テリー・ボガード";
        fighters[3] = "不知火舞";

        // Get the array length with .length
        System.out.println("Fighter count: " + fighters.length); // 4

        // Access elements by index
        System.out.println("Protagonist: " + fighters[0]); // 草薙京
        System.out.println("Rival: " + fighters[1]); // 八神庵

        // Print the entire array as a string using Arrays.toString()
        System.out.println("All fighters: " + Arrays.toString(fighters));

        // --- Declare and initialize an array (list initial values directly) ---
        // A more concise literal initialization
        int[] power = {1800, 1600, 1500, 1400};

        System.out.println("Kusanagi Kyo's power: " + power[0]); // 1800

        // --- Process all elements in order with a for loop ---
        System.out.println("=== Power List ===");
        for (int i = 0; i < fighters.length; i++) {
            System.out.println(fighters[i] + ": " + power[i]);
        }

        // --- Process all elements with an enhanced for loop (for-each) ---
        // Use this when an index is not needed — it's simpler
        System.out.println("=== Participants (for-each) ===");
        for (String name : fighters) {
            System.out.println("・" + name);
        }

        // --- Out-of-bounds access causes ArrayIndexOutOfBoundsException ---
        // Accessing fighters[4] throws a runtime exception.
        // The last element is accessed with fighters[fighters.length - 1].
        System.out.println("Last fighter: " + fighters[fighters.length - 1]);
    }
}
javac ArrayBasic.java
java ArrayBasic
Fighter count: 4
Protagonist: 草薙京
Rival: 八神庵
All fighters: [草薙京, 八神庵, テリー・ボガード, 不知火舞]
Kusanagi Kyo's power: 1800
=== Power List ===
草薙京: 1800
八神庵: 1600
テリー・ボガード: 1500
不知火舞: 1400
=== Participants (for-each) ===
・草薙京
・八神庵
・テリー・ボガード
・不知火舞
Last fighter: 不知火舞
ArrayMultiDim.java
import java.util.Arrays;

public class ArrayMultiDim {
    public static void main(String[] args) {

        // --- Declare and initialize a 2D array ---
        // A 3-team x 3-member 2D array modeled after KOF team battles
        String[][] teams = {
            {"草薙京",         "二階堂紅丸",     "大門五郎"},   // Team Japan
            {"テリー・ボガード", "アンディ・ボガード", "ジョー東"},  // Team Bogard
            {"八神庵",         "マチュア",       "バイス"},     // Team Yagami
        };

        // Get the number of rows (teams) with teams.length
        System.out.println("Team count: " + teams.length); // 3

        // Get the number of columns (members per team) with teams[row].length
        System.out.println("Members per team: " + teams[0].length); // 3

        // Access with [row][col]. Both are zero-based.
        System.out.println("Team Japan leader: " + teams[0][0]); // 草薙京
        System.out.println("Team Bogard 2nd: " + teams[1][1]); // アンディ・ボガード

        // --- Print all elements with nested for loops ---
        System.out.println("=== Team List ===");
        for (int i = 0; i < teams.length; i++) {
            System.out.print("Team " + (i + 1) + ": ");
            for (int j = 0; j < teams[i].length; j++) {
                System.out.print(teams[i][j]);
                if (j < teams[i].length - 1) {
                    System.out.print(", ");
                }
            }
            System.out.println();
        }

        // --- Print a 2D array all at once with Arrays.deepToString() ---
        // Using Arrays.toString() on a 2D array shows object references for the inner arrays.
        // Always use deepToString() for multi-dimensional arrays.
        System.out.println("All teams (deepToString): " + Arrays.deepToString(teams));

        // --- Modify an element of a 2D array ---
        teams[2][0] = "八神庵(怒り爆発)";
        System.out.println("After update: " + teams[2][0]);
    }
}
javac ArrayMultiDim.java
java ArrayMultiDim
Team count: 3
Members per team: 3
Team Japan leader: 草薙京
Team Bogard 2nd: アンディ・ボガード
=== Team List ===
Team 1: 草薙京, 二階堂紅丸, 大門五郎
Team 2: テリー・ボガード, アンディ・ボガード, ジョー東
Team 3: 八神庵, マチュア, バイス
All teams (deepToString): [[草薙京, 二階堂紅丸, 大門五郎], [テリー・ボガード, アンディ・ボガード, ジョー東], [八神庵, マチュア, バイス]]
After update: 八神庵(怒り爆発)
ArrayVsArrayList.java
import java.util.ArrayList;
import java.util.Arrays;

public class ArrayVsArrayList {
    public static void main(String[] args) {

        // --- Array: fixed length ---
        // Managing KOF entry fighters with an array.
        // The length is fixed at declaration time and cannot be changed.
        String[] entryArray = {"草薙京", "八神庵", "テリー・ボガード"};
        System.out.println("Array length: " + entryArray.length);
        System.out.println("Array contents: " + Arrays.toString(entryArray));

        // Elements can be overwritten, but adding or removing elements is not possible.
        entryArray[0] = "クーラ・ダイアモンド"; // Overwriting is OK
        System.out.println("After overwrite: " + Arrays.toString(entryArray));
        // entryArray[3] = "K'"; // Index out of bounds — throws ArrayIndexOutOfBoundsException

        // --- ArrayList: variable length ---
        // Use ArrayList when you need to add or remove elements.
        ArrayList<String> entryList = new ArrayList<>();
        entryList.add("草薙京");
        entryList.add("八神庵");
        entryList.add("テリー・ボガード");
        System.out.println("List size: " + entryList.size()); // Use .size(), not .length
        System.out.println("List contents: " + entryList);

        // add() appends an element to the end (not available for arrays)
        entryList.add("K'");
        entryList.add("クーラ・ダイアモンド");
        System.out.println("After add: " + entryList);

        // remove() removes the element at the specified index
        entryList.remove(1); // Removes the element at index 1 (八神庵)
        System.out.println("After remove: " + entryList);

        // --- Converting between Array and ArrayList ---
        // Array → ArrayList
        String[] arr = {"草薙京", "テリー・ボガード", "不知火舞"};
        ArrayList<String> fromArr = new ArrayList<>(Arrays.asList(arr));
        fromArr.add("ライデン"); // Elements can now be added
        System.out.println("List converted from array: " + fromArr);

        // ArrayList → Array
        String[] backToArr = fromArr.toArray(new String[0]);
        System.out.println("Array converted from list: " + Arrays.toString(backToArr));
    }
}
javac ArrayVsArrayList.java
java ArrayVsArrayList
Array length: 3
Array contents: [草薙京, 八神庵, テリー・ボガード]
After overwrite: [クーラ・ダイアモンド, 八神庵, テリー・ボガード]
List size: 3
List contents: [草薙京, 八神庵, テリー・ボガード]
After add: [草薙京, 八神庵, テリー・ボガード, K', クーラ・ダイアモンド]
After remove: [草薙京, テリー・ボガード, K', クーラ・ダイアモンド]
List converted from array: [草薙京, テリー・ボガード, 不知火舞, ライデン]
Array converted from list: [草薙京, テリー・ボガード, 不知火舞, ライデン]

Array vs. ArrayList: When to Use Each

ArrayArrayList
LengthFixed (cannot change)Variable (add/remove freely)
Get element count.length.size()
Get elementarr[i]list.get(i)
Add elementNot possible (overwrite only)list.add(value)
Remove elementNot possiblelist.remove(index)
Store primitives directlyYes (int[], etc.)No (requires wrapper types such as Integer)
Convert to stringArrays.toString(arr)list.toString() or System.out.println(list)
Best suited forFixed-size data with a known element countData whose element count changes dynamically

Common Mistake 1: ArrayIndexOutOfBoundsException (out-of-bounds access)

Array indexes start at 0, and the maximum valid index is length - 1. Using an index equal to length throws an ArrayIndexOutOfBoundsException at runtime.

IndexErrorNg.java
public class IndexErrorNg {
    public static void main(String[] args) {
        String[] fighters = {"草薙京", "八神庵", "テリー・ボガード"};

        // fighters.length is 3, but index 3 does not exist.
        // The last element is fighters[2] (= fighters[length - 1]).
        for (int i = 0; i <= fighters.length; i++) {  // Using <= goes out of bounds
            System.out.println(fighters[i]);
        }
    }
}
javac IndexErrorNg.java
java IndexErrorNg
草薙京
八神庵
テリー・ボガード
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
	at IndexErrorNg.main(IndexErrorNg.java:8)

Fix the termination condition from i <= fighters.length to i < fighters.length.

IndexErrorOk.java
public class IndexErrorOk {
    public static void main(String[] args) {
        String[] fighters = {"草薙京", "八神庵", "テリー・ボガード"};

        // Using < fighters.length keeps the index within the range 0–2.
        for (int i = 0; i < fighters.length; i++) {
            System.out.println(fighters[i]);
        }
    }
}
javac IndexErrorOk.java
java IndexErrorOk
草薙京
八神庵
テリー・ボガード

Common Mistake 2: Confusing length() and length

Getting the character count of a String uses length() (a method call — parentheses required), whereas getting the element count of an array uses .length (a field access — no parentheses). Using the wrong form causes a compile error.

LengthConfusionNg.java
public class LengthConfusionNg {
    public static void main(String[] args) {
        String[] fighters = {"草薙京", "八神庵", "テリー・ボガード"};

        // length() does not exist on an array (compile error)
        System.out.println(fighters.length()); // NG: cannot find symbol
    }
}
javac LengthConfusionNg.java
LengthConfusionNg.java:6: error: cannot find symbol
        System.out.println(fighters.length());
                                   ^
  symbol:   method length()
  location: variable fighters of type String[]
1 error

Use .length (no parentheses) for arrays. Use .length() (with parentheses) for the character count of a String.

LengthConfusionOk.java
public class LengthConfusionOk {
    public static void main(String[] args) {
        String[] fighters = {"草薙京", "八神庵", "テリー・ボガード"};
        String name = "草薙京";

        System.out.println("Array element count: " + fighters.length);   // Field (no parentheses)
        System.out.println("String character count: " + name.length());   // Method (with parentheses)
    }
}
javac LengthConfusionOk.java
java LengthConfusionOk
Array element count: 3
String character count: 3

Common Mistake 3: Comparing array contents with ==

An array variable holds a reference (the address of the object). Comparing with == checks whether the two references point to the same object, not whether the contents are equal. Two arrays with identical contents return false with ==. Use Arrays.equals() to compare contents.

ArrayEqualNg.java
import java.util.Arrays;

public class ArrayEqualNg {
    public static void main(String[] args) {
        String[] a = {"草薙京", "八神庵"};
        String[] b = {"草薙京", "八神庵"};

        // == compares references, so even identical contents return false
        System.out.println(a == b); // false (separate objects)
    }
}
javac ArrayEqualNg.java
java ArrayEqualNg
false

Use Arrays.equals() to compare the contents of arrays.

ArrayEqualOk.java
import java.util.Arrays;

public class ArrayEqualOk {
    public static void main(String[] args) {
        String[] a = {"草薙京", "八神庵"};
        String[] b = {"草薙京", "八神庵"};

        System.out.println(a == b);              // false (different references)
        System.out.println(Arrays.equals(a, b)); // true (contents are equal)
    }
}
javac ArrayEqualOk.java
java ArrayEqualOk
false
true

Notes

An array is a data structure that stores values of the same type in a contiguous region of memory. Index-based access is fast, making arrays well suited for managing data with a fixed element count. The length is determined at declaration time and cannot be changed afterward.

Use .length to get the element count. length() (with parentheses) is a method of the String class. Arrays use .length (no parentheses — a field). Accessing a non-existent index throws an ArrayIndexOutOfBoundsException at runtime. The standard loop termination condition is i < arr.length (equivalent to i <= arr.length - 1).

To print the contents of a multi-dimensional array, use Arrays.deepToString(). Using Arrays.toString() on a multi-dimensional array prints the inner arrays as object references (strings like [Ljava.lang.String;@...).

When you need to add or remove elements, ArrayList is an option. See ArrayList add() / get() for how to use it. For sorting and content comparison, see Arrays.sort() and Arrays.equals() / toString().

If you find any errors or copyright issues, please .