6.1 Declaring, Instantiating & Using 1D Arrays
Key Takeaways
In
int a[], b;,ais anint[]array reference whilebis a plain primitiveint; placing brackets after the type inint[] a, b;makes both variablesint[]arrays.Never specify a size in an array declaration (
int[3] a;fails compilation), and never supply both a size and an initializer (new int[3]{1, 2, 3}fails compilation).An array initializer can appear in a declaration, inside another initializer, or after
new int[]. Usenew int[]{1, 2, 3}as an expression in a standalone assignment or method call.new Type[size]fills elements with their type’s default value. A newly allocatedString[3]contains three null references.Arrays expose a
public final int lengthfield (arr.length, notarr.length()), throwNegativeArraySizeExceptionfornew int[-1], and throwArrayIndexOutOfBoundsExceptionon invalid indices.
Declaring, Instantiating & Using 1D Arrays
Arrays are the foundational fixed-size indexed containers in Java SE 8. Unlike ArrayList, a Java array cannot grow or shrink after creation, stores homogeneous elements (either all of one primitive type or references compatible with one reference type), and lives as an object on the heap. Questions on array syntax frequently test subtle differences between valid code, compile-time errors, and runtime exceptions.
Legal vs. Illegal Array Declarations
An array-variable declaration without an initializer introduces a reference variable. An array creation expression or initializer creates the array object itself. Java allows the square brackets [] either immediately after the element type or immediately after the variable name:
int[] scores; // Preferred Java style: brackets on the type
int [] counts; // Legal: whitespace around brackets is ignored
int flags[]; // Legal (C-style): brackets after the identifier
The bracket placement becomes a classic trap when declaring multiple variables in a single statement. Brackets attached to the type apply to every variable in the comma-separated list, whereas brackets attached to an identifier apply only to that single variable:
int[] a, b; // Both a and b are int[] references
int c[], d; // c is an int[] reference, but d is a plain primitive int!
int e, f[]; // e is a plain int, and f is an int[] reference
Warning
Never write the array size inside a declaration. Statements such as int[5] nums; and int nums[5]; both fail to compile because the declaration describes only the variable's type, not its heap allocation.
Instantiating Arrays: new, Shorthand, and Anonymous Arrays
To create the actual array object on the heap, you must either allocate it with new or supply an initializer:
1. Explicit Allocation with new
int[] a = new int[3]; // Allocates 3 ints initialized to 0
int[] empty = new int[0]; // Legal! Length is 0; valid indices: none
byte b = 4;
char c = 2;
int[] fromByte = new int[b]; // Legal: byte widens to int via numeric promotion
int[] fromChar = new int[c]; // Legal: char widens to int (length 2)
After unary numeric promotion, a size expression must have type int. Primitives byte, short, char, and int work, as do their wrappers after unboxing. A null wrapper throws NullPointerException, while a long, floating-point, or boolean size is rejected during compilation.
What about negative sizes? Because -1 has type int, new int[-1] compiles without error, then throws NegativeArraySizeException at runtime when the JVM executes the allocation.
2. Declaration-Only Initializer Shorthand
When you declare and initialize an array in a single statement, Java lets you omit new Type[]:
int[] primes = {2, 3, 5, 7}; // Legal in declaration
String[] tags = {"alpha", "beta",}; // Legal: trailing comma is allowed
An initializer without new Type[] can appear in a variable declaration or inside an enclosing array initializer. Bare braces do not form an expression for a standalone assignment or method argument:
int[] vals;
vals = {1, 2, 3}; // COMPILE ERROR: illegal start of expression
printSum({1, 2, 3}); // COMPILE ERROR: bare initializer not allowed here
3. Anonymous Array Expressions
When you need to reassign an existing array variable, pass an inline array to a method, or return a new array directly, use an anonymous array (new Type[]{...}):
int[] vals;
vals = new int[]{1, 2, 3}; // Legal reassignment
printSum(new int[]{10, 20, 30}); // Legal inline method argument
Caution
Never combine an explicit size with an initializer list. Writing new int[3]{1, 2, 3} is a compile-time error because the compiler calculates the array length directly from the number of elements inside {...}.
| Code Pattern | Outcome | Explanation |
|---|---|---|
int[] a, b; | Compiles | Both a and b are int[] references |
int a[], b; | Compiles | a is int[]; b is primitive int |
int[3] a; | Compile Error | Size cannot appear in a declaration |
int[] a = {1, 2, 3}; | Compiles | Declaration-only shorthand creates length-3 array |
a = {1, 2, 3}; | Compile Error | Bare {...} invalid outside declaration |
a = new int[]{1, 2, 3}; | Compiles | Anonymous array valid in assignments and calls |
new int[3]{1, 2, 3} | Compile Error | Cannot specify both size and initializer |
new int[0] | Compiles & Runs | Valid empty array with length == 0 |
new int[-1] | Runtime Exception | Compiles, throws NegativeArraySizeException |
Default Element Values
A local array variable must be definitely assigned before you read it. When you create an array with explicit dimensions and no initializer list, each element receives its type’s default value:
| Element Type | Default Value | Notes |
|---|---|---|
byte, short, int | 0 | Integral zero |
long | 0L | 64-bit integer zero |
float, double | 0.0f / 0.0 | Floating-point zero |
boolean | false | Logical false |
char | '\u0000' | Null character (numeric value 0) |
Any reference type (String, Object, etc.) | null | No objects are constructed yet |
A frequent pitfall involves String[]: allocating String[] words = new String[3]; creates three null slots, not three empty strings "". Calling a method on an unpopulated slot triggers NullPointerException:
String[] words = new String[3];
System.out.println(words[0]); // Prints: null
System.out.println(words[0].length()); // Throws NullPointerException!
Using .length, Indexing, and Bounds Checking
Every array exposes a public final int length field — not a method. Confusing arr.length with String.length() or List.size() is heavily tested:
int[] data = {10, 20, 30};
int n = data.length; // Legal: evaluates to 3
// int x = data.length(); // COMPILE ERROR: cannot find symbol method length()
// data.length = 10; // COMPILE ERROR: cannot assign a value to final variable length
Array indices are zero-based, so an array of length n has valid indices 0 through n - 1. Accessing any negative index or any index >= arr.length compiles cleanly (provided the index expression promotes to int) and throws ArrayIndexOutOfBoundsException for a non-null array after evaluating the index. A null array reference instead throws NullPointerException after successful evaluation of the index:
int[] nums = {10, 20, 30};
System.out.println(nums[0]); // 10
System.out.println(nums[nums.length - 1]); // 30
// nums[0L] = 5; // COMPILE ERROR: long cannot convert to int
System.out.println(nums[3]); // Runtime: ArrayIndexOutOfBoundsException
// Tested separately: nums[-1] also throws ArrayIndexOutOfBoundsException.
Similarly, indexing an empty array int[] empty = new int[0]; at empty[0] compiles and throws ArrayIndexOutOfBoundsException because no valid index exists.
Iterating Over 1D Arrays
You can traverse a 1D array with either a classic indexed for loop or an enhanced for-each loop:
int[] scores = {80, 90, 100};
// Enhanced for-each loop reads a copy of each element value
for (int s : scores) {
s += 5; // Modifies local copy 's', NOT the array element!
}
System.out.println(scores[0]); // Still 80
// Classic indexed loop can update elements in place
for (int i = 0; i < scores.length; i++) {
scores[i] += 5;
}
System.out.println(scores[0]); // 85
Tip
Use an enhanced for loop when you only need to read elements sequentially. Switch to an indexed for loop whenever you must overwrite array slots, inspect adjacent indices, iterate backward, or track the current index.
Given the declaration int a[], b; inside a method, which statement compiles without error?
a = {1, 2, 3};
b = new int[2];
b = 42;
a = new int[2]{1, 2};
What is the result of compiling and running the following snippet?
String[] items = new String[3];
System.out.println(items[1].isEmpty());
Compiles cleanly and throws NullPointerException at runtime
Compiles cleanly and prints true
Compiles cleanly and throws ArrayIndexOutOfBoundsException at runtime
Fails to compile because items[1] is uninitialized
Which snippet compiles cleanly AND throws ArrayIndexOutOfBoundsException when executed?
int[] x = new int[-2];
int[] x = new int[2]; System.out.println(x.length());
int[] x = new int[2]; System.out.println(x[0L]);
int[] x = new int[]{10, 20}; System.out.println(x[x.length]);
Sections you finish are checked off in the contents.