Arrays
java arrays fixed size zero-based indexing length multidimensional matrix ArrayIndexOutOfBoundsException for-each loop contiguous memory
Introduction
In the previous lesson, you learned how loops help execute a block of code repeatedly.
However, what if you need to store the marks of 1,000 students?
Creating separate variables would be inefficient:
int mark1 = 85;int mark2 = 90;int mark3 = 78;...
Managing hundreds or thousands of variables quickly becomes impossible.
Java solves this problem using Arrays.
An array allows you to store multiple values of the same data type in a single variable.
Arrays are one of the most fundamental data structures in Java and are widely used in:
- Banking Systems
- E-commerce Applications
- Game Development
- Data Processing
- Machine Learning
- Spring Boot Applications
- Collections Framework (internally)
In this lesson, you'll learn:
- What is an Array?
- Why Arrays are Needed
- Declaring Arrays
- Creating Arrays
- Initializing Arrays
- Accessing Elements
- Updating Elements
- Array Length
- Iterating Arrays
- Multidimensional Arrays
- Arrays vs Variables
- Real-world Examples
- Best Practices
- Common Mistakes
- Hands-on Exercises
- Professional Interview Questions
What is an Array?
An array is a fixed-size collection of elements of the same data type stored in contiguous memory locations.
Instead of creating multiple variables:
int s1 = 80;int s2 = 85;int s3 = 90;
We can write:
int[] marks = {80, 85, 90};
Now all student marks are stored in a single variable.
Why Do We Need Arrays?
Imagine storing monthly sales for a company.
Without arrays:
double janSales = 12000;double febSales = 15000;double marSales = 18000;
With arrays:
double[] monthlySales = {12000,15000,18000};
Arrays make programs:
- Easier to maintain
- More readable
- Memory efficient
- Easy to process using loops
Declaring an Array
Syntax:
dataType[] arrayName;
Example:
int[] numbers;String[] names;double[] salaries;
At this stage, memory is not allocated.
Creating an Array
Memory allocation uses the new keyword.
int[] numbers = new int[5];
This creates an array capable of storing 5 integers.
Memory Layout:
Index0 1 2 3 4|0|0|0|0|0|
Each element is initialized with its default value.
Default Values
| Data Type | Default Value |
|---|---|
int | 0 |
double | 0.0 |
boolean | false |
char | '\u0000' |
Object | null |
Example:
int[] numbers = new int[3];System.out.println(numbers[0]);
Output:
0
Initializing Arrays
Initialization can happen during declaration.
String[] cities = {"Delhi","Mumbai","Hyderabad","Bangalore"};
Accessing Array Elements
Arrays use zero-based indexing.
String[] fruits = {"Apple","Banana","Orange"};System.out.println(fruits[0]);System.out.println(fruits[2]);
Output:
AppleOrange
Updating Array Elements
Elements can be modified using their index.
int[] ages = {20, 25, 30};ages[1] = 28;System.out.println(ages[1]);
Output:
28
Array Length
Every array has a built-in property called length.
int[] marks = {80, 90, 70, 95};System.out.println(marks.length);
Output:
4
Note: length is a property, not a method.
Correct:
marks.length
Wrong:
marks.length()
Iterating Through Arrays
Using a for loop:
int[] numbers = {10,20,30,40};for(int i = 0; i < numbers.length; i++){System.out.println(numbers[i]);}
Output:
10203040
Using Enhanced for Loop
String[] names = {"John","David","Alex"};for(String name : names){System.out.println(name);}
Output:
JohnDavidAlex
Use enhanced for loops when you only need to read elements.
Multidimensional Arrays
Arrays can contain other arrays.
Example:
int[][] matrix = {{1,2,3},{4,5,6},{7,8,9}};
Accessing elements:
System.out.println(matrix[1][2]);
Output:
6
Memory Representation
numbers↓+----+----+----+----+|10 |20 |30 |40 |+----+----+----+----+Index0 1 2 3
Arrays occupy contiguous memory, enabling fast index-based access.
ArrayIndexOutOfBoundsException
Accessing an invalid index causes an exception.
int[] arr = {10,20,30};System.out.println(arr[5]);
Output:
Exception in thread "main"java.lang.ArrayIndexOutOfBoundsException
Always ensure the index is within 0 to length - 1.
Arrays vs Individual Variables
| Individual Variables | Arrays |
|---|---|
| Difficult to manage | Easy to manage |
| More code | Less code |
| Cannot iterate easily | Loop-friendly |
| Poor scalability | Highly scalable |
Real-World Example: Student Marks
int[] marks = {85,90,78,92,88};int total = 0;for(int mark : marks){total += mark;}double average = (double) total / marks.length;System.out.println("Average = " + average);
Real-World Example: Online Shopping Cart
String[] cart = {"Laptop","Mouse","Keyboard"};for(String item : cart){System.out.println(item);}
Best Practices
Use Meaningful Names
int[] employeeIds;
Better than:
int[] x;
Avoid Magic Numbers
Instead of:
for(int i=0;i<5;i++)
Use:
for(int i=0;i<array.length;i++)
Prefer Enhanced for Loop for Reading
Cleaner and less error-prone.
Validate Indexes
Always ensure indexes remain within bounds.
Keep Arrays Immutable if Possible
Avoid modifying shared arrays unnecessarily.
Common Mistakes
Starting Index from 1
Arrays start at 0, not 1.
Accessing Invalid Index
Results in ArrayIndexOutOfBoundsException.
Forgetting Array Length
Hardcoding loop limits makes code fragile.
Confusing length with length()
Arrays use length; strings use length().
Mixing Data Types
An array stores only one data type.
Hands-on Exercise
Create a Java program that:
- Stores 10 student marks in an array.
- Prints all marks using both
forand enhancedforloops. - Finds the highest mark.
- Finds the lowest mark.
- Calculates the average mark.
- Creates a 3×3 matrix and prints its elements.
- Demonstrates
ArrayIndexOutOfBoundsExceptionand then fixes it.
Summary
Arrays provide an efficient way to store and manage multiple values of the same type. They simplify repetitive data handling, integrate seamlessly with loops, and form the basis for advanced data structures such as ArrayList, collections, and matrices.
Key Takeaways
- Arrays store multiple elements of the same type.
- Arrays use zero-based indexing.
- Array size is fixed after creation.
- Use
lengthto determine array size. - Enhanced for loops simplify traversal.
- Multidimensional arrays represent tables and matrices.
- Invalid indexes throw
ArrayIndexOutOfBoundsException. - Arrays are the foundation of many advanced Java data structures.
Professional Interview Questions
1What is an array in Java?
Professional Answer
An array is a fixed-size data structure that stores multiple elements of the same data type in contiguous memory locations. It provides fast index-based access and is commonly used when the number of elements is known in advance.
Follow-up Questions
- Why are arrays faster than linked lists for random access?
- Can an array store objects?
Interview Tip: Mention that arrays provide O(1) random access using indexes.
2What is the difference between length and length()?
Professional Answer
length is a property of arrays that returns the number of elements, while length() is a method of the String class that returns the number of characters in a string.
Follow-up Questions
- Does ArrayList use length or size()?
- Why is length not a method for arrays?
Interview Tip: Remember: Arrays → length, String → length(), Collections → size().
3What is ArrayIndexOutOfBoundsException?
Professional Answer
It is a runtime exception thrown when a program attempts to access an array index that is less than 0 or greater than or equal to the array's length. Proper index validation and loop conditions prevent this exception.
Follow-up Questions
- How do you avoid this exception?
- Can it be caught using a try-catch block?
Interview Tip: Always iterate from 0 to array.length - 1 to avoid index-related errors.