Arrays in Java: Declare, Create, Access and Avoid Common Errors
Difficulty: Beginner · Importance: High · Java version: All versions (tested on JDK 25) · Last updated: 3 Nov 2026
Quick puzzle:
int[] marks = {78, 92, 65};. What doesmarks[3]give you? If you said 65, you’re one step off. It crashes, and this lesson shows why.
Quick Answer
An array in Java is a fixed-size object that stores many values of the same type under one name. You reach each value by an index that starts at 0 and ends at length - 1. Create one with new int[5] or a literal like {78, 92, 65}. Its size can never change after creation.
Before you start: you should know primitive data types, reference types and the for loop.
Why Do We Need Arrays?
Say you store five students’ marks as mark1, mark2 … mark5. That works for five. For 500 it falls apart. You can’t loop over separate variables, count them, or pass them to a method as one group.
An array solves this. One name (marks) holds all the values, and a loop can walk through them using the index.
Analogy: an array is like a row of numbered lockers. All the lockers are the same size, the numbering starts at 0, and you can’t add more lockers once the row is built.
How to Declare and Initialize an Array in Java
There are three steps: declare the variable, create the array, and fill it.
| Form | Example | When to use it |
|---|---|---|
| Declare only | int[] marks; | Creates a variable that refers to no array yet |
| Create with a size | int[] marks = new int[5]; | You know the size but not the values yet |
| Array literal | int[] marks = {78, 92, 65}; | You know the values now |
| Literal after declaring | marks = new int[]{78, 92}; | Assigning to an existing variable |
Key rules:
int[] marksis the preferred style. The C-styleint marks[]also compiles, but you’ll mostly see it in old code.- Declaring is not creating. A local
int[] marks;has no array yet, and using it is a compile error. - The size can be any
intexpression, such asnew int[studentCount]. Once created, the length is fixed. - Very large arrays cost memory. A request like
new int[1_000_000_000](about 4 GB) can fail withOutOfMemoryErroron a default heap.
Example: Store, Read and Average Marks
Output:
First mark: 78Last mark: 71
Count: 5
Average: 79.6
What’s happening:
- Writing vs reading.
marks[2] = 69writes, because the bracket is on the left of=.marks[0]reads. lengthis a field, not a method. Writemarks.length, nevermarks.length(). Reading it is a constant-time operation.- The last element is at
length - 1.marks[marks.length - 1]always gives the last element. - The cast avoids integer division.
(double) totalmakes the division keep its decimal part.
Dry run of the loop (marks are {78, 92, 69, 88, 71} after the write):
| i | i < 5? | marks[i] | total |
|---|---|---|---|
| 0 | true | 78 | 78 |
| 1 | true | 92 | 170 |
| 2 | true | 69 | 239 |
| 3 | true | 88 | 327 |
| 4 | true | 71 | 398 |
| 5 | false | — | loop ends; 398 / 5 = 79.6 |
Why Does the Array Index Start From 0?
The index is an offset from the start of the array. The first element is 0 steps from the start, the second is 1 step, and so on. That’s why the valid range is 0 to length - 1.
Array Default Values in Java
When you create an array with new and don’t fill it, Java fills every slot with a default value:
Output:
int: 0double: 0.0
boolean: false
char: 0
String: null
Type of scores: [I
| Element type | Default |
|---|---|
byte, short, int, long | 0 |
float, double | 0.0 |
boolean | false |
char | '\u0000' (the null character) |
Any object type (String, etc.) | null |
Note: null is not the same as an empty string "". A null slot has no object at all.
Is an Array an Object in Java?
Yes. Every array is an object created on the heap, even an int[]. The variable marks holds a reference to it. That’s why getClass().getName() printed [I, the JVM’s internal name for “array of int”.
How It Works Internally
The variable lives in the method’s stack frame and stores only a reference. The array object, including its fixed length and the element slots, lives on the heap.
The bytecode confirms it. javap -c StudentMarks on JDK 25 shows that the literal {78, 92, …} is just shorthand for “create an array, then store each value”:
0: iconst_51: newarray int // create an int[] of size 5 on the heap
3: dup
4: iconst_0
5: bipush 78
7: iastore // marks[0] = 78
...
Reading marks.length compiles to the arraylength instruction, and marks[i] compiles to iaload.
Two Variables, One Array
Because the variable holds a reference, assigning one array variable to another doesn’t copy the elements:
Output:
fees: [40000, 12000, 8000]same object? true
fees: [40000, 12000, 8000]
copy: [40000, 0, 8000]
alias = fees made two names for one array, so changing alias[0] changed fees. Arrays.copyOf created a separate array. This is the same rule you saw in Pass by Value: the reference is copied, not the object. Copying arrays is covered in detail later in this section.
Common Mistakes With Arrays
Mistake 1: Going One Index Too Far (ArrayIndexOutOfBoundsException)
7892
65
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
at OutOfBounds.main(OutOfBounds.java:5)
Why it happens: the valid indexes are 0, 1 and 2. Java checks every access at runtime, and a negative index like marks[-1] throws the same exception. Java has no “−1 means last element” shortcut.
Mistake 2: Calling length() With Brackets
error: cannot find symbolsymbol: method length()
location: variable marks of type int[]
Fix: marks.length. Arrays use the length field. String uses the length() method, which you’ll meet in the next section.
Mistake 3: Assigning a Bare Literal Later
error: illegal start of expressionFix: marks = new int[]{78, 92};. A bare {…} is allowed only in the declaration line itself.
Mistake 4: Using an Array That Was Never Created
error: variable marks might not have been initializedFix: create the array first, using new int[n] or a literal.
Mistake 5: Calling a Method on an Empty Object Slot
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.length()" because "names[1]" is nullFix: fill every slot, using a literal such as {"Asha", "Ravi"}, or check names[1] != null first.
Note: the variable name names[1] appears in the message when the class is compiled with debug info, as IDEs do by default. With plain javac you’ll see "<local1>[1]" instead.
Mistake 6: Treating = as a Copy
int[] backup = fees; doesn’t create a backup. Both names point to the same array (see SharedArray above). Fix: Arrays.copyOf(fees, fees.length).
Array vs ArrayList in Java
| Feature | Array (int[]) | ArrayList<Integer> |
|---|---|---|
| Size | Fixed at creation | Grows and shrinks |
| Element types | Primitives or objects | Objects only (Integer, not int) |
| Length | arr.length (field) | list.size() (method) |
| Access | arr[i] | list.get(i) |
| Speed and memory | Fastest, no extra overhead | Small overhead for boxing and resizing |
| Use when | The size is known, or performance-critical code and DSA | The size changes at runtime |
You’ll learn ArrayList in the Collections section.
Best Practices
- Write
int[] marks, notint marks[]. The type should read as “int array”. - Use the literal when you know the values. Use
new type[n]when you’ll fill the array later. - Always loop with
i < arr.length. Never hard-code the size. - Use plural, meaningful names like
marksorprices, notaorarr1. - Print arrays with
Arrays.toString(arr). Printingarrdirectly shows something like[I@1b6d3586, which is not the contents. - Switch to
ArrayListwhen the number of items isn’t known in advance.
Interview Questions on Arrays
How to answer in an interview: “What is an array in Java?”
“An array is a fixed-size object that stores elements of one type, accessed by a zero-based index. It’s created on the heap, and the variable holds a reference to it. The length is fixed once it’s created and is read with the length field. Unfilled slots get default values, and accessing an invalid index throws ArrayIndexOutOfBoundsException.”
Output-Prediction Questions
Q1.
Answer: 5. The unset slots default to 0.
Q2.
Answer: 9. a and b refer to the same array.
Q3.
Answer: null!. String concatenation prints null without throwing.
Conceptual Follow-Ups
- Can you change an array’s size after creating it? No. Create a new, bigger array and copy the elements, or use
ArrayList. - Is
lengtha method or a field? A field, and it isfinal. - Where is an array stored? On the heap. The variable holding the reference may be on the stack.
- Can an array hold mixed types? Only through a common supertype such as
Object[]. A plainint[]holds onlyint. - What’s the difference between
length,length()andsize()?lengthis for arrays,length()is forString, andsize()is for collections.
More: Java Interview Questions for Freshers · Intermediate Questions
Practice Exercises
- Easy: Store 5 product prices in an array and print the highest one.
- Easy: Create
new boolean[4]and print each slot. Predict the output first. - Easy–Medium: Count how many marks in
{45, 78, 33, 90, 61}are 40 or above (the pass mark). - Medium: Print an array in reverse without creating a second array.
- Medium: Make a real copy of an array, change the copy, and prove the original is unchanged.
Practise on ExamAdda Practice and the ExamAdda DSA track.
FAQs
1. What is an array in Java?
An array is a fixed-size object that stores multiple values of the same type, accessed by a zero-based index.
2. How do you declare and initialize an array in Java?
Use int[] marks = new int[5]; to create an array of a given size, or int[] marks = {78, 92, 65}; to create it with values. To assign values later, use marks = new int[]{…}.
3. What are the default values of an array in Java?
Numeric types default to 0 or 0.0, boolean to false, char to '\u0000', and object types such as String to null.
4. How do you find the length of an array in Java?
Use the length field, for example marks.length, without brackets. It returns the number of slots, which never changes.
5. Why does ArrayIndexOutOfBoundsException occur?
It occurs when you access an index below 0 or at or above length. The most common cause is writing <= instead of < in a loop condition.
6. Is an array an object in Java?
Yes. Every array, including a primitive array like int[], is an object on the heap, and its variable holds a reference to it.
7. Can we change the size of an array in Java?
No. An array’s length is fixed at creation. Create a new array and copy the elements, or use ArrayList for a resizable list.
{
"@context": "https://schema.org",
"@type": "FAQPage",
"mainEntity": [
{"@type": "Question", "name": "What is an array in Java?", "acceptedAnswer": {"@type": "Answer", "text": "An array is a fixed-size object that stores multiple values of the same type, accessed by a zero-based index."}},
{"@type": "Question", "name": "How do you declare and initialize an array in Java?", "acceptedAnswer": {"@type": "Answer", "text": "Use int[] marks = new int[5]; to create an array of a given size, or int[] marks = {78, 92, 65}; to create it with values. To assign values later, use marks = new int[]{...}."}},
{"@type": "Question", "name": "What are the default values of an array in Java?", "acceptedAnswer": {"@type": "Answer", "text": "Numeric types default to 0 or 0.0, boolean to false, char to '\\u0000', and object types such as String to null."}},
{"@type": "Question", "name": "How do you find the length of an array in Java?", "acceptedAnswer": {"@type": "Answer", "text": "Use the length field, for example marks.length, without brackets. It returns the number of slots, which never changes."}},
{"@type": "Question", "name": "Why does ArrayIndexOutOfBoundsException occur?", "acceptedAnswer": {"@type": "Answer", "text": "It occurs when you access an index below 0 or at or above length. The most common cause is writing <= instead of < in a loop condition."}},
{"@type": "Question", "name": "Is an array an object in Java?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. Every array, including a primitive array like int[], is an object on the heap, and its variable holds a reference to it."}},
{"@type": "Question", "name": "Can we change the size of an array in Java?", "acceptedAnswer": {"@type": "Answer", "text": "No. An array's length is fixed at creation. Create a new array and copy the elements, or use ArrayList for a resizable list."}}
]
}Quiz
1. What is the last valid index of new int[10]?
a) 10 b) 9 c) 11 d) 0
Answer: b. Indexes run from 0 to length − 1.
2. What is the default value of new String[3][0]?
a) "" b) "null" c) null d) A compile error
Answer: c. Object slots default to null, which is not an empty string.
3. Which line compiles?
a) int[] a; a = {1, 2}; b) int[] a = new int[]{1, 2}; c) int a[] = new int(2); d) int[] a = new int[];
Answer: b.
4. How do you get an array’s size?
a) arr.size() b) arr.length() c) arr.length d) arr.count
Answer: c.
5. After int[] b = a; b[0] = 7;, what is a[0]?
a) Unchanged b) 7 c) 0 d) An exception
Answer: b. Both variables refer to the same array.
Article Summary
- An array stores a fixed number of same-type values, accessed by indexes 0 to
length - 1. - Create it with
new type[n](filled with defaults) or a literal{…}. Usenew type[]{…}when assigning later. lengthis a field. An invalid index throwsArrayIndexOutOfBoundsException.- Arrays are heap objects.
b = ashares one array, whileArrays.copyOfmakes a real copy. - Use
ArrayListwhen the size must change.
Next → [INTERNAL LINK: next Array lesson] · ← Previous: Pass by Value in Java
References: JLS Chapter 10: Arrays · Oracle Java Tutorials: Arrays · java.util.Arrays Javadoc (JDK 25)