Java Notes
Complete introduction to arrays in Java covering definition, memory layout, types of arrays, declaration, initialization, accessing elements, and real-world use cases with detailed examples.
What is an Array?
An array is a fixed-size, contiguous data structure that stores multiple values of the same data type under a single variable name. Think of an array like a row of numbered lockers in a school — each locker (element) has a number (index), and all lockers are the same size (same data type).
In Java, an array is an object that lives in heap memory. When you create an array, Java allocates a continuous block of memory where all elements are stored side by side. This contiguous storage is what makes arrays extremely fast for accessing elements by their position.
Without arrays, if you needed to store marks of 100 students, you would need 100 separate variables:
int marks1 = 85;
int marks2 = 90;
int marks3 = 78;
// ... up to marks100 — impractical!With arrays, you store all 100 values in a single variable:
Why Do We Need Arrays?
Arrays solve several fundamental problems in programming:
1. Grouping Related Data: Instead of managing dozens of individual variables, you group related values together. Student marks, employee salaries, temperature readings — all naturally belong in arrays.
2. Efficient Access: Arrays provide O(1) — constant time — access to any element using its index. Whether you want the 1st element or the 1000th element, the access time is the same.
3. Easy Iteration: You can process all elements using loops, making operations like finding the sum, maximum, or average straightforward.
4. Memory Efficiency: Arrays store elements in contiguous memory, which is cache-friendly and reduces memory overhead compared to storing individual objects.
5. Foundation for Data Structures: Arrays are the building blocks for more complex structures like ArrayList, HashMap, Stack, Queue, and Heap.
How Arrays Work in Memory
Understanding memory layout is crucial for mastering arrays. In Java, memory is divided into two main areas:
Stack Memory
- Stores reference variables (the variable name that points to the array)
- Stores local variables and method call information
- Has a LIFO (Last In, First Out) structure
Heap Memory
- Stores the actual array object (the block of memory holding elements)
- Managed by the Garbage Collector
- Shared across the application
Memory Diagram for int[] arr = new int[5];:
Key Points:
arris a reference variable stored in the stack- The actual array
{0, 0, 0, 0, 0}is an object stored in the heap arrholds the memory address (reference) of the array object- Default values are assigned automatically (0 for int, null for objects, false for boolean)
Array Characteristics
| Characteristic | Description |
|---|---|
| Fixed Size | Once created, the size cannot be changed |
| Zero-Indexed | First element is at index 0, last at index (length - 1) |
| Homogeneous | All elements must be of the same data type |
| Contiguous Memory | Elements are stored in adjacent memory locations |
| Object in Java | Arrays are objects — they have a length property |
| Reference Type | Array variables store references, not actual data |
Declaring an Array
Declaration tells the compiler that a variable will hold a reference to an array. No memory is allocated for elements at this stage.
Syntax
// Style 1: Preferred in Java
dataType[] arrayName;
// Style 2: C-style (valid but not recommended)
dataType arrayName[];Examples
int[] numbers; // Declares an integer array reference
double[] prices; // Declares a double array reference
String[] names; // Declares a String array reference
char[] letters; // Declares a char array reference
boolean[] flags; // Declares a boolean array referenceImportant: After declaration, the variable is null — it doesn't point to any array yet.
int[] numbers;
System.out.println(numbers); // Compile error: variable might not have been initializedCreating an Array (Memory Allocation)
The new keyword allocates memory in the heap for the specified number of elements.
Syntax
Combined Declaration and Creation
Step-by-Step Execution
- Step 1: JVM reserves space for reference variable
marksin stack memory - Step 2:
new int[3]allocates a contiguous block of 12 bytes (3 × 4 bytes) in heap memory - Step 3: All elements are initialized to default value
0 - Step 4: The memory address of the array object is stored in
marks
Initializing an Array
Method 1: Using Index Assignment
Method 2: Array Literal (Declaration + Initialization)
int[] marks = {85, 90, 78, 92, 88}; // Size is automatically 5Note: Array literals can only be used at the time of declaration:
int[] marks;
marks = {85, 90, 78, 92, 88}; // COMPILE ERROR!
marks = new int[]{85, 90, 78, 92, 88}; // This works!Method 3: Using a Loop
Accessing Array Elements
Elements are accessed using their index (position number starting from 0).
First fruit: Apple Third fruit: Cherry Last fruit: Elderberry Total fruits: 5
Default Values in Arrays
When you create an array with new, Java automatically assigns default values based on the data type:
| Data Type | Default Value |
|---|---|
byte | 0 |
short | 0 |
int | 0 |
long | 0L |
float | 0.0f |
double | 0.0d |
char | '\u0000' (null character) |
boolean | false |
| Object references (String, etc.) | null |
int default: 0 double default: 0.0 boolean default: false String default: null
Iterating Over Arrays
Using for Loop
Using for loop: Index 0 -> Value: 10 Index 1 -> Value: 20 Index 2 -> Value: 30 Index 3 -> Value: 40 Index 4 -> Value: 50
Using Enhanced for Loop (for-each)
public class ForEachExample {
public static void main(String[] args) {
String[] colors = {"Red", "Green", "Blue", "Yellow"};
System.out.println("Using for-each loop:");
for (String color : colors) {
System.out.println(color);
}
}
}Using for-each loop: Red Green Blue Yellow
When to use which:
- Use for loop when you need the index (modifying elements, comparing adjacent elements)
- Use for-each when you only need to read values (cleaner syntax, no index errors)
Using while Loop
5 10 15 20 25
Types of Arrays in Java
Java supports three main types of arrays:
1. One-Dimensional Array (1D)
A single row of elements — the simplest and most common form.
int[] marks = {85, 90, 78, 92, 88};2. Two-Dimensional Array (2D)
A table-like structure with rows and columns — an array of arrays.
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};3. Jagged Array
A 2D array where each row can have a different number of columns.
Array as an Object
In Java, arrays are objects. This means:
- They are created using
new(like other objects) - They have a
lengthproperty (not a method — no parentheses) - They inherit from
java.lang.Object(have toString(), equals(), etc.) - They are stored in heap memory with a reference in stack
- They can be assigned to Object type variables
public class ArrayAsObject {
public static void main(String[] args) {
int[] arr = {10, 20, 30};
// Array is an instance of Object
System.out.println(arr instanceof Object); // true
// getClass() shows the type
System.out.println(arr.getClass().getName()); // [I means int array
// toString() shows type + hashcode (not elements!)
System.out.println(arr.toString()); // Something like [I@1b6d3586
// Use Arrays.toString() for readable output
System.out.println(java.util.Arrays.toString(arr));
}
}true [I [I@1b6d3586 [10, 20, 30]
Passing Arrays to Methods
Arrays are passed by reference (actually, the reference is passed by value). This means changes made inside the method affect the original array.
Before: [1, 2, 3, 4, 5] After: [2, 4, 6, 8, 10]
Explanation: The method receives a copy of the reference (memory address), so it points to the same array object. Any modification through this reference changes the original array.
Returning Arrays from Methods
Methods can return arrays, which is useful for creating and returning processed data.
[1, 2, 3, 4, 5]
Anonymous Arrays
You can create arrays without assigning them to a variable — useful when passing arrays directly to methods.
public class AnonymousArray {
public static int sum(int[] arr) {
int total = 0;
for (int val : arr) {
total += val;
}
return total;
}
public static void main(String[] args) {
// Anonymous array passed directly to method
int result = sum(new int[]{10, 20, 30, 40});
System.out.println("Sum: " + result);
}
}Sum: 100
Array Advantages and Disadvantages
Advantages
| Advantage | Explanation |
|---|---|
| Fast access | O(1) time to access any element by index |
| Cache friendly | Contiguous memory improves CPU cache performance |
| Memory efficient | No extra pointers or overhead per element |
| Simple syntax | Easy to declare, initialize, and iterate |
| Type safe | Compiler enforces element type |
Disadvantages
| Disadvantage | Explanation |
|---|---|
| Fixed size | Cannot grow or shrink after creation |
| Insertion/Deletion costly | Shifting elements takes O(n) time |
| Wasted memory | If array is half-empty, memory is still allocated |
| Homogeneous only | Cannot mix data types in a single array |
| No built-in bounds checking at compile time | Runtime ArrayIndexOutOfBoundsException |
Array vs ArrayList
| Feature | Array | ArrayList |
|---|---|---|
| Size | Fixed | Dynamic (grows automatically) |
| Type | Can hold primitives and objects | Objects only (uses wrappers for primitives) |
| Performance | Faster (no boxing/unboxing) | Slightly slower |
| Syntax | int[] arr = new int[5] | ArrayList<Integer> list = new ArrayList<>() |
| Methods | Only length property | add(), remove(), get(), size(), etc. |
| Memory | More efficient | Has overhead |
Common Exceptions with Arrays
ArrayIndexOutOfBoundsException
Thrown when you access an invalid index (negative or >= length).
Error: Index 5 out of bounds for length 3 Error: Index -1 out of bounds for length 3
NullPointerException
Thrown when you try to use a null array reference.
public class NullArrayException {
public static void main(String[] args) {
int[] arr = null;
try {
System.out.println(arr.length);
} catch (NullPointerException e) {
System.out.println("Error: Array reference is null!");
}
}
}Error: Array reference is null!
Real-World Use Cases
- Student Grade Management: Store and process marks of students
- Image Processing: 2D arrays represent pixel grids
- Game Development: Game boards (chess, tic-tac-toe) use 2D arrays
- Database Results: Query results are often stored in arrays
- Sorting and Searching: Algorithms operate on arrays
- Buffer Management: Network/file I/O uses byte arrays
- Mathematical Operations: Vectors and matrices
- Caching: LRU cache implementations use arrays
Common Mistakes
1. Confusing length with length()
int[] arr = {1, 2, 3};
System.out.println(arr.length); // Correct: property (no parentheses)
// System.out.println(arr.length()); // WRONG: arrays don't have length() method
String str = "Hello";
System.out.println(str.length()); // Correct: String uses length() method2. Off-by-One Errors
3. Using == Instead of Arrays.equals()
int[] a = {1, 2, 3};
int[] b = {1, 2, 3};
System.out.println(a == b); // false (compares references)
System.out.println(java.util.Arrays.equals(a, b)); // true (compares content)4. Trying to Resize an Array
5. Printing Array Directly
Best Practices
- Always check array bounds before accessing elements
- Use
Arrays.toString()for printing arrays - Prefer for-each when you don't need the index
- Use
Arrays.copyOf()instead of manual copying - Initialize arrays at declaration when values are known
- Use constants for array sizes to improve readability
- Consider ArrayList when size is unknown at compile time
- Validate input before using it as an array index
- Use
Arrays.equals()for content comparison - Document array's purpose when the context isn't obvious
Interview Questions
Q1: What is an array in Java? An array is a fixed-size, contiguous data structure that stores multiple elements of the same data type. It is an object in Java stored in heap memory, with indices starting from 0.
Q2: Where is an array stored in memory? The array object is stored in heap memory. The reference variable pointing to it is stored in stack memory (if local) or heap memory (if it's an instance variable).
Q3: What is the default value of array elements? Numeric types get 0, boolean gets false, char gets '\u0000', and object references get null.
Q4: Can we change the size of an array after creation? No. Arrays are fixed-size. To resize, you must create a new array and copy elements (or use Arrays.copyOf()).
Q5: What is the difference between length and length()? length is a property of arrays (no parentheses). length() is a method of the String class.
Q6: What exception occurs when accessing an invalid index? ArrayIndexOutOfBoundsException (a RuntimeException/unchecked exception).
Q7: Are arrays objects in Java? Yes. Arrays are objects that inherit from java.lang.Object. They are created with new, stored in heap, and have the length property.
Q8: What is an anonymous array? An array created without a reference variable, typically passed directly to a method: method(new int[]{1, 2, 3}).
Q9: Can we store different data types in a single array? Not directly. However, an Object[] array can store any object type (using polymorphism), but primitives must be boxed.
Q10: How are arrays passed to methods in Java? The reference (memory address) is passed by value. This means the method receives a copy of the reference pointing to the same array object, so modifications inside the method affect the original array.
Q11: What is the time complexity of accessing an array element? O(1) — constant time, because elements are at calculated memory offsets.
Q12: How do you compare two arrays for equality? Use java.util.Arrays.equals(arr1, arr2) for content comparison. Using == only compares references.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Array Introduction.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Java Master Course topic.
Search Terms
java-master-course, java master course, java, master, course, fundamentals, arrays, array
Related Java Master Course Topics