Array creation and indexing
What you will learn
An array stores a fixed number of values of one component type. Access each position with a zero-based index. Arrays are useful when the number of items is known, such as seven daily temperatures.
public class Main { public static void main(String[] args) { int[] stock = {4, 7, 2}; stock[1] = 9; System.out.println(stock[1]); System.out.println(stock.length); }}Expected output:
93Index 1 selects the second item. The update leaves length unchanged.
How it works
int[] stock = {4, 7, 2}; declares a reference and creates a three-element array. new int[3] creates three zeros. The array length is fixed, but its elements can change. stock.length is a field, not a method. Valid indices run from zero through length minus one. Numeric components default to zero, boolean components to false and reference components to null. A local array variable itself must be assigned before use. Arrays.toString gives readable one-dimensional array contents. The import at the top makes the utility class name available.
import java.util.Arrays;public class Main { public static void main(String[] args) { int[] counts = new int[2]; boolean[] flags = new boolean[1]; String[] names = new String[1]; System.out.println(Arrays.toString(counts)); System.out.println(flags[0]); System.out.println(names[0]); }}Expected output:
[0, 0]falsenullThe components receive their type defaults. Null is not empty text.
Check a boundary or unusual input
public class Main { public static void main(String[] args) { int[] values = {}; int total = 0; for (int i = 0; i < values.length; i++) total += values[i]; System.out.println(total); }}Expected output:
0The loop condition is false immediately, so no array access occurs.
Common mistakes
An empty array has no valid index. Access outside the valid range throws ArrayIndexOutOfBoundsException; a negative creation length throws NegativeArraySizeException. A final array variable cannot be reassigned, but its elements can still change.
Try it yourself
Write static int countPositive(int[] values) to count values greater than zero in a non-null array. Do not mutate it. Check mixed, empty and all nonpositive input.
Save each example independently as Main.java; compile with javac --release 21 -encoding UTF-8 Main.java and launch using java Main. Local Java practice only; automatic ByteMind Java grading is not established.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Array creation and indexing — knowledge check
Practice core behavior and boundary cases.
Last valid index of length 4?
Initial contents of new int[2]?
How do you read array length?
Reading a[0] from an empty int array causes what?
What does a[1] = 7 change?