By WebNest Studio Engineering Team
Java - Core Tutorial
Java Arrays
An array is a fixed-size, ordered container that holds multiple values of the same type under a single variable name, with each value accessed by a zero-based integer index. Arrays are themselves objects in Java (even arrays of primitives), which is why every array has a length field and is allocated on the heap with new.
Because an array's size is fixed once created, arrays are best suited to situations where you know how many elements you need in advance. When the number of elements can grow or shrink dynamically, Java's collection classes (like ArrayList) are usually a better fit, but arrays remain the foundation those collections are often built on.
Why it matters
Arrays are the simplest way to hold many values of the same type, and they sit underneath most of the collections you will use later, including ArrayList. Their two fixed rules — the size never changes, and indexes run from 0 to length minus 1 — explain both why they are fast and why ArrayIndexOutOfBoundsException is one of the first exceptions every Java developer meets.
Declaring, Creating, and Initializing Arrays
Declaring an array (int[] scores;) only creates a reference variable — no memory for elements exists yet. Creating an array with new int[4] allocates space for four ints on the heap. Java also supports an array literal shorthand at the point of declaration, such as int[] scores = {90, 85, 78, 92};, which both creates and initializes the array in one step.
Default Values and Length
When an array is created with new but no explicit values, every element gets the type's default value automatically: 0 for numeric types, false for boolean, and null for reference types — the same defaults instance variables get. The length field (not a method — no parentheses) always reports the array's fixed size and never changes after creation.
Bounds and Fixed Size
Valid indices run from 0 to length - 1. Accessing any index outside that range, in either direction, throws an ArrayIndexOutOfBoundsException at runtime rather than being caught at compile time, so index arithmetic needs care. Because arrays cannot grow, "adding" an element in practice means creating a new, larger array and copying the existing elements into it.
Time complexity
| Operation | Average | Worst case |
|---|---|---|
| Read or write by index | O(1) | O(1) |
| Search an unsorted array | O(n) | O(n) |
Example
Creating an array with default values, then filling and summing it
public class ArrayBasicsDemo {
public static void main(String[] args) {
int[] scores = new int[4]; // default values: 0, 0, 0, 0
System.out.println("Default: " + java.util.Arrays.toString(scores));
scores[0] = 90;
scores[1] = 85;
scores[2] = 78;
scores[3] = 92;
int total = 0;
for (int i = 0; i < scores.length; i++) {
total += scores[i];
}
System.out.println("Total: " + total);
System.out.println("Length: " + scores.length);
}
}
Default: [0, 0, 0, 0]
Total: 345
Length: 4
Common Mistakes
- Writing "scores.length()" with parentheses — length is a field on arrays, not a method (Strings and Lists use .length() or .size(), which is a frequent source of confusion).
- Accessing index "scores.length" instead of "scores.length - 1", causing an ArrayIndexOutOfBoundsException on the last valid access.
- Assuming an array can be resized after creation — it cannot; a new array must be created and the old data copied over.
- Forgetting that a freshly created array of objects is filled with null, not empty objects, leading to a NullPointerException on first use.
Exercise
Reverse an array in place, without creating a second array, by swapping elements from the two ends towards the middle.
Expected output: [5, 4, 3, 2, 1]
import java.util.Arrays;
public class ReverseArray {
public static void main(String[] args) {
int[] values = {1, 2, 3, 4, 5};
// TODO: swap values[left] and values[right], moving both towards the middle
System.out.println(Arrays.toString(values));
}
}
Show hints
- Use two indexes:
leftstarting at 0 andrightstarting atvalues.length - 1. - A swap needs a temporary variable to hold one of the two values.
Show solution
import java.util.Arrays;
public class ReverseArray {
public static void main(String[] args) {
int[] values = {1, 2, 3, 4, 5};
for (int left = 0, right = values.length - 1; left < right; left++, right--) {
int temp = values[left];
values[left] = values[right];
values[right] = temp;
}
System.out.println(Arrays.toString(values)); // [5, 4, 3, 2, 1]
}
}
Quick quiz
1. What does each element of new int[3] contain?
- A. 0
- B. null
- C. A random value
- D. Nothing until assigned
Show answer
A. Array elements are always initialised to defaults: 0 for numeric types, false for boolean and null for references.
2. What happens when you read arr[arr.length]?
- A. It returns the last element
- B. It throws ArrayIndexOutOfBoundsException
- C. It returns 0
- D. It does not compile
Show answer
B. Valid indexes run from 0 to length - 1. Index length is one past the end, so the access throws at runtime.
3. How do you get the number of elements in an array called arr?
- A. arr.length()
- B. arr.size()
- C. arr.length
- D. arr.count
Show answer
C. length is a field on arrays, with no parentheses. String uses the method length(), and collections use size().
Interview questions
What is the difference between an array and an ArrayList?
Show answer
An array has a fixed size set when it is created, can hold primitives or objects, and uses arr[i] and arr.length. An ArrayList grows and shrinks as needed, holds only objects (primitives are boxed), and offers methods such as add, remove and size().
Internally an ArrayList is backed by an array that it replaces with a larger one when it fills up.
Are arrays objects in Java?
Show answer
Yes. Every array is an object created on the heap, even an array of primitives. An array variable holds a reference, so assigning one array variable to another copies the reference, not the elements, and both names then refer to the same array.
Key Points to Remember
- Arrays have a fixed size set at creation time and cannot be resized afterward.
- Valid indices run from 0 to length - 1; length is a field, not a method call.
- Elements created with "new" but not explicitly set receive the type's default value (0, false, or null).
- Arrays are objects allocated on the heap, even when they hold primitive values.
Practice in the playground
Write and run your own code for this topic, or start from the exercise or an example. Runs plain Java 17. Frameworks such as Spring, and databases, are not available here. Your code for each topic is kept in this browser.
Run the examples
Change an input, predict the result, then compare it with the output. Explain why the result changes.
Written by
WebNest Studio Engineering Team
Practical lessons from developers working with Java, Python, React, databases and production systems.
Led by Vansh Duggal, Founder, WebNest Studio · Full-stack & software engineering