`[]` Operator in Java

java dev.to

Arrays are one of the most fundamental data structures in Java, and the square bracket operator ([]) is used everywhere while working with them.

The [] operator is used to:

  • Declare arrays
  • Create arrays
  • Access array elements

Although the operator itself is simple, Java arrays have several rules that are frequently asked in interviews.

In this guide, we'll cover everything you need to know about the [] operator with examples, common mistakes, and interview tips.


What is the [] Operator?

The square bracket operator ([]) is known as the array operator.

It is used in three different ways:

  1. Array declaration
  2. Array creation (construction)
  3. Array element access

1. Array Declaration

Declaring an array means creating a reference variable that can point to an array object.

Recommended Style

int[] numbers;
Enter fullscreen mode Exit fullscreen mode

Other Valid Styles

int []numbers;

int numbers[];
Enter fullscreen mode Exit fullscreen mode

All three declarations are valid in Java.

However, the first style is generally recommended because it clearly associates the brackets with the data type.


Array Size Cannot Be Specified During Declaration

Valid

int[] numbers;
Enter fullscreen mode Exit fullscreen mode

Invalid

int[5] numbers;
Enter fullscreen mode Exit fullscreen mode

Compile Error

']' expected
Enter fullscreen mode Exit fullscreen mode

Remember:

Declaration creates only the reference variable—not the array itself.


2. Array Creation

Arrays are created using the new operator.

int[] numbers = new int[5];
Enter fullscreen mode Exit fullscreen mode

This allocates memory for five integers on the heap.


3. Accessing Array Elements

Arrays use zero-based indexing.

int[] numbers = new int[3];

numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;

System.out.println(numbers[0]);
Enter fullscreen mode Exit fullscreen mode

Output

10
Enter fullscreen mode Exit fullscreen mode

Multi-Dimensional Array Declarations

Java supports multiple declaration styles.

2D Arrays

All of these are valid:

int[][] a;

int [][]a;

int a[][];

int[] []a;

int[] a[];

int []a[];
Enter fullscreen mode Exit fullscreen mode

3D Arrays

These are also valid:

int[][][] a;

int [][][]a;

int a[][][];

int[] [][]a;

int[] a[][];

int[] []a[];

int[][] []a;

int[][] a[];

int []a[][];

int [][]a[];
Enter fullscreen mode Exit fullscreen mode

Although Java allows many declaration styles, using

int[][] matrix;
Enter fullscreen mode Exit fullscreen mode

is generally the clearest.


Multiple Variable Declarations

Consider the following examples:

int[] a1, b1;
Enter fullscreen mode Exit fullscreen mode

Both a1 and b1 are one-dimensional arrays.


int[] a2[], b2;
Enter fullscreen mode Exit fullscreen mode
  • a2 → 2D array
  • b2 → 1D array

int[][] a3, b3;
Enter fullscreen mode Exit fullscreen mode

Both are two-dimensional arrays.


Invalid

int[] a, []b;
Enter fullscreen mode Exit fullscreen mode

Compile Error

illegal start of expression
Enter fullscreen mode Exit fullscreen mode

Rules for Array Creation

Rule 1: Size Is Mandatory

Valid

int[] numbers = new int[5];
Enter fullscreen mode Exit fullscreen mode

Invalid

int[] numbers = new int[];
Enter fullscreen mode Exit fullscreen mode

Compile Error

array dimension missing
Enter fullscreen mode Exit fullscreen mode

Rule 2: Zero-Length Arrays Are Valid

int[] numbers = new int[0];

System.out.println(numbers.length);
Enter fullscreen mode Exit fullscreen mode

Output

0
Enter fullscreen mode Exit fullscreen mode

A zero-length array is perfectly legal.


Rule 3: Negative Size Causes Runtime Exception

int[] numbers = new int[-5];
Enter fullscreen mode Exit fullscreen mode

Runtime Exception

NegativeArraySizeException
Enter fullscreen mode Exit fullscreen mode

Notice this is not a compile-time error.


Rule 4: Allowed Data Types for Size

The array size must evaluate to an integer.

Allowed:

byte b = 5;
new int[b];

short s = 10;
new int[s];

char c = 'A';
new int[c];
Enter fullscreen mode Exit fullscreen mode

All of these work because they are promoted to int.


Not Allowed

new int[10L];

new int[10.5];
Enter fullscreen mode Exit fullscreen mode

Compile Error

possible loss of precision
Enter fullscreen mode Exit fullscreen mode

Rule 5: Maximum Array Size

The index type is int.

Therefore, the maximum theoretical array size is:

2147483647
Enter fullscreen mode Exit fullscreen mode

Example

int[] numbers = new int[2147483647];
Enter fullscreen mode Exit fullscreen mode

This compiles but will almost certainly throw

OutOfMemoryError
Enter fullscreen mode Exit fullscreen mode

at runtime.


Default Values

Every element receives a default value automatically.

Data Type Default Value
byte, short, int, long 0
float, double 0.0
char '\u0000'
boolean false
Object references null

Example

int[] numbers = new int[3];

System.out.println(numbers[0]);
Enter fullscreen mode Exit fullscreen mode

Output

0
Enter fullscreen mode Exit fullscreen mode

Custom Initialization

int[] numbers = new int[4];

numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
Enter fullscreen mode Exit fullscreen mode

Accessing Invalid Indexes

numbers[4] = 50;
Enter fullscreen mode Exit fullscreen mode

Runtime Exception

ArrayIndexOutOfBoundsException
Enter fullscreen mode Exit fullscreen mode

Negative indexes also fail.

numbers[-1] = 100;
Enter fullscreen mode Exit fullscreen mode

Declaration + Creation + Initialization

The simplest way to create arrays.

int[] numbers = {10, 20, 30, 40};
Enter fullscreen mode Exit fullscreen mode

Characters

char[] vowels = {'a', 'e', 'i', 'o', 'u'};
Enter fullscreen mode Exit fullscreen mode

Strings

String[] names = {
    "Rajesh",
    "Rahul",
    "Priya"
};
Enter fullscreen mode Exit fullscreen mode

Two-Dimensional Arrays

int[][] matrix = {
    {10, 20, 30},
    {40, 50}
};
Enter fullscreen mode Exit fullscreen mode

Important Restriction

This shortcut works only during declaration.

Valid

int[] numbers = {10, 20, 30};
Enter fullscreen mode Exit fullscreen mode

Invalid

int[] numbers;

numbers = {10, 20, 30};
Enter fullscreen mode Exit fullscreen mode

Compile Error

illegal start of expression
Enter fullscreen mode Exit fullscreen mode

length vs length()

One of the most common Java interview questions.

Arrays Strings
length length()
Variable Method

Arrays

int[] numbers = new int[5];

System.out.println(numbers.length);
Enter fullscreen mode Exit fullscreen mode

Output

5
Enter fullscreen mode Exit fullscreen mode

Incorrect

numbers.length();
Enter fullscreen mode Exit fullscreen mode

Compile Error


Strings

String name = "Rajesh";

System.out.println(name.length());
Enter fullscreen mode Exit fullscreen mode

Output

6
Enter fullscreen mode Exit fullscreen mode

Incorrect

name.length;
Enter fullscreen mode Exit fullscreen mode

Compile Error


Multi-Dimensional Array Length

int[][] matrix = new int[6][3];
Enter fullscreen mode Exit fullscreen mode
System.out.println(matrix.length);
Enter fullscreen mode Exit fullscreen mode

Output

6
Enter fullscreen mode Exit fullscreen mode

This returns the number of rows.


System.out.println(matrix[0].length);
Enter fullscreen mode Exit fullscreen mode

Output

3
Enter fullscreen mode Exit fullscreen mode

This returns the number of columns in the first row.


Anonymous Arrays

Sometimes an array is needed only once.

Instead of assigning it to a variable, create an anonymous array.

new int[]{10, 20, 30, 40};
Enter fullscreen mode Exit fullscreen mode

Two-dimensional

new int[][]{
    {10, 20},
    {30, 40}
};
Enter fullscreen mode Exit fullscreen mode

Anonymous Arrays Cannot Specify Size

Invalid

new int[3]{10, 20, 30};
Enter fullscreen mode Exit fullscreen mode

Valid

new int[]{10, 20, 30};
Enter fullscreen mode Exit fullscreen mode

Anonymous Arrays as Method Arguments

public class Test {

    public static void main(String[] args) {

        System.out.println(sum(new int[]{10, 20, 30, 40}));

    }

    static int sum(int[] numbers) {

        int total = 0;

        for (int value : numbers) {
            total += value;
        }

        return total;
    }
}
Enter fullscreen mode Exit fullscreen mode

Output

100
Enter fullscreen mode Exit fullscreen mode

The array exists only for that method call.


Multi-Dimensional Arrays Are Arrays of Arrays

Java does not implement true matrices.

Instead, it stores arrays inside arrays.

Example

int[][] matrix = new int[2][];

matrix[0] = new int[3];

matrix[1] = new int[2];
Enter fullscreen mode Exit fullscreen mode

Each row can have a different length.

These are called jagged arrays.


Valid and Invalid Constructions

Statement Valid?
new int[]
new int[3]
new int[3][4]
new int[3][]
new int[][4]
new int[3][4][5]
new int[3][4][]
new int[3][][5]

Rule:

Dimensions must be specified from left to right.

You cannot skip a middle dimension.


Internal Representation

Arrays have JVM-specific internal class names.

Array Type Internal Name
int[] [I
int[][] [[I
double[] [D
String[] [Ljava.lang.String;

Example

int[] numbers = new int[3];

System.out.println(numbers);
Enter fullscreen mode Exit fullscreen mode

Output

[I@5acf9800
Enter fullscreen mode Exit fullscreen mode

The format is:

ClassName@HashCode
Enter fullscreen mode Exit fullscreen mode

Interview Questions

Can we specify array size during declaration?

No.

int[] numbers;
Enter fullscreen mode Exit fullscreen mode

is valid, but

int[5] numbers;
Enter fullscreen mode Exit fullscreen mode

is invalid.


Is a zero-length array valid?

Yes.

new int[0];
Enter fullscreen mode Exit fullscreen mode

What happens if the array size is negative?

Java throws:

NegativeArraySizeException
Enter fullscreen mode Exit fullscreen mode

What exception occurs for an invalid index?

ArrayIndexOutOfBoundsException
Enter fullscreen mode Exit fullscreen mode

What is the difference between length and length()?

  • Arrays use the length variable.
  • Strings use the length() method.

Are Java multidimensional arrays real matrices?

No.

They are arrays of arrays, allowing jagged structures.


Memory Tricks 🧠

Remember the Three Uses of []

Declaration

↓

Creation

↓

Access
Enter fullscreen mode Exit fullscreen mode

Arrays

numbers.length
Enter fullscreen mode Exit fullscreen mode

No parentheses.


Strings

name.length()
Enter fullscreen mode Exit fullscreen mode

Parentheses required.


Easy Way to Remember

[] is everywhere in arrays—declare, create, and access.


Key Takeaways

  • The [] operator is used to declare arrays, create them using new, and access their elements.
  • Array size is specified only during creation, not during declaration.
  • Arrays use zero-based indexing, and invalid indexes result in ArrayIndexOutOfBoundsException.
  • A zero-length array is valid, but a negative size causes NegativeArraySizeException.
  • Array sizes must evaluate to an int; byte, short, and char are promoted automatically.
  • Java multidimensional arrays are arrays of arrays, allowing jagged structures.
  • Arrays use the length variable, whereas String objects use the length() method.
  • Anonymous arrays are useful for one-time operations such as passing data directly to methods.

Happy Coding!

Source: dev.to

arrow_back Back to Tutorials