Java Arrays
Introduction
An array in Java is a collection of elements of the same data type stored under a single variable name.
An array is useful when we need to store multiple values of the same type.
Example
Instead of creating separate variables:
int mark1 = 80; int mark2 = 75; int mark3 = 90; int mark4 = 85;
We can use an array:
int[] marks = {80, 75, 90, 85};
Features of Arrays
- An array stores multiple values.
- All elements must have the same data type.
- Array size is fixed after creation.
- Array elements are stored using indexes.
- Array indexing starts from
0. - Arrays can store primitive values and object references.
- Arrays can be one-dimensional or multidimensional.
- The
lengthproperty gives the size of an array.
Array Index
Each element of an array has an index.
For example:
int[] numbers = {10, 20, 30, 40, 50};
The indexes are:
| Index | Value |
|---|---|
| 0 | 10 |
| 1 | 20 |
| 2 | 30 |
| 3 | 40 |
| 4 | 50 |
Remember:
The first index of a Java array is always
0.
So:
numbers[0]
returns 10.
Declaring an Array
There are two common ways to declare an array.
Method 1
int[] numbers;
Method 2
int numbers[];
The first style is generally preferred:
int[] numbers;
Creating an Array
After declaration, we can create an array using the new keyword.
int[] numbers = new int[5];
This creates an integer array capable of storing 5 elements.
The indexes will be:
0 1 2 3 4
Declaring and Initializing an Array
We can declare and initialize an array at the same time.
int[] numbers = {10, 20, 30, 40, 50};
Another form is:
int[] numbers = new int[]{10, 20, 30, 40, 50};
Accessing Array Elements
We can access an array element using its index.
int[] numbers = {10, 20, 30, 40, 50}; System.out.println(numbers[0]); System.out.println(numbers[2]); System.out.println(numbers[4]);
Output
10 30 50
Changing Array Elements
Array elements can be changed using their index.
int[] numbers = {10, 20, 30, 40, 50}; numbers[2] = 100; System.out.println(numbers[2]);
Output
100
The original array:
10 20 30 40 50
After changing index 2:
10 20 100 40 50
Array Length
The length property returns the number of elements in an array.
int[] numbers = {10, 20, 30, 40, 50}; System.out.println(numbers.length);
Output
5
Important
Use:
array.length
not:
array.length()
length is a property, not a method.
One-Dimensional Array
A one-dimensional array stores data in a single row or list.
Example
public class OneDArray { public static void main(String[] args) { int[] numbers = {10, 20, 30, 40, 50}; for (int i = 0; i < numbers.length; i++) { System.out.println(numbers[i]); } } }
Output
10 20 30 40 50
Using Enhanced for Loop
The enhanced for loop can be used to easily access every element.
Example
public class ArrayForEach { public static void main(String[] args) { int[] numbers = {10, 20, 30, 40, 50}; for (int number : numbers) { System.out.println(number); } } }
Output
10 20 30 40 50
Syntax
for (dataType variable : array) { // statements }
Taking Array Input from User
We can use the Scanner class to take array elements from the user.
import java.util.Scanner; public class ArrayInput { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter array size: "); int size = sc.nextInt(); int[] numbers = new int[size]; System.out.println("Enter " + size + " numbers:"); for (int i = 0; i < size; i++) { numbers[i] = sc.nextInt(); } System.out.println("Array elements:"); for (int i = 0; i < size; i++) { System.out.println(numbers[i]); } sc.close(); } }
Example Output
Enter array size: 5 Enter 5 numbers: 10 20 30 40 50 Array elements: 10 20 30 40 50
Finding Sum of Array Elements
public class ArraySum { public static void main(String[] args) { int[] numbers = {10, 20, 30, 40, 50}; int sum = 0; for (int i = 0; i < numbers.length; i++) { sum = sum + numbers[i]; } System.out.println("Sum = " + sum); } }
Output
Sum = 150
Finding Average of Array Elements
public class ArrayAverage { public static void main(String[] args) { int[] marks = {80, 70, 90, 85, 75}; int sum = 0; for (int mark : marks) { sum += mark; } double average = (double) sum / marks.length; System.out.println("Average = " + average); } }
Output
Average = 80.0
Finding Largest Element
public class LargestElement { public static void main(String[] args) { int[] numbers = {25, 10, 50, 30, 40}; int largest = numbers[0]; for (int i = 1; i < numbers.length; i++) { if (numbers[i] > largest) { largest = numbers[i]; } } System.out.println("Largest = " + largest); } }
Output
Largest = 50
Finding Smallest Element
public class SmallestElement { public static void main(String[] args) { int[] numbers = {25, 10, 50, 30, 40}; int smallest = numbers[0]; for (int i = 1; i < numbers.length; i++) { if (numbers[i] < smallest) { smallest = numbers[i]; } } System.out.println("Smallest = " + smallest); } }
Output
Smallest = 10
Searching an Element
We can search for an element using a loop.
public class ArraySearch { public static void main(String[] args) { int[] numbers = {10, 20, 30, 40, 50}; int search = 30; boolean found = false; for (int number : numbers) { if (number == search) { found = true; break; } } if (found) { System.out.println("Element found"); } else { System.out.println("Element not found"); } } }
Output
Element found
Two-Dimensional Array
A two-dimensional array stores data in rows and columns.
It can be visualized as a table.
10 20 30 40 50 60 70 80 90
This is a 3 × 3 array.
Declaring a 2D Array
int[][] matrix;
Creating a 2D array:
int[][] matrix = new int[3][3];
Initializing a 2D Array
int[][] matrix = { {10, 20, 30}, {40, 50, 60}, {70, 80, 90} };
Accessing 2D Array Elements
int[][] matrix = { {10, 20, 30}, {40, 50, 60}, {70, 80, 90} }; System.out.println(matrix[0][0]); System.out.println(matrix[1][2]); System.out.println(matrix[2][1]);
Output
10 60 80
Printing a 2D Array
Nested loops are commonly used to print a two-dimensional array.
public class TwoDArray { public static void main(String[] args) { int[][] matrix = { {10, 20, 30}, {40, 50, 60}, {70, 80, 90} }; for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[i].length; j++) { System.out.print(matrix[i][j] + " "); } System.out.println(); } } }
Output
10 20 30 40 50 60 70 80 90
Jagged Array
A jagged array is a two-dimensional array in which each row can have a different number of elements.
Example
public class JaggedArray { public static void main(String[] args) { int[][] numbers = { {10, 20}, {30, 40, 50}, {60, 70, 80, 90} }; for (int i = 0; i < numbers.length; i++) { for (int j = 0; j < numbers[i].length; j++) { System.out.print(numbers[i][j] + " "); } System.out.println(); } } }
Output
10 20 30 40 50 60 70 80 90
Array of Strings
Arrays can also store strings.
public class StringArray { public static void main(String[] args) { String[] names = { "Anu", "Ram", "Sita", "Hari" }; for (String name : names) { System.out.println(name); } } }
Output
Anu Ram Sita Hari
Default Values of Arrays
When an array is created using new, its elements receive default values.
| Data Type | Default Value |
|---|---|
int | 0 |
long | 0L |
float | 0.0f |
double | 0.0d |
char | '\u0000' |
boolean | false |
| Reference types | null |
Example
int[] numbers = new int[3]; System.out.println(numbers[0]); System.out.println(numbers[1]); System.out.println(numbers[2]);
Output
0 0 0
ArrayIndexOutOfBoundsException
If we try to access an index that does not exist, Java throws an ArrayIndexOutOfBoundsException.
Example:
int[] numbers = {10, 20, 30}; System.out.println(numbers[3]);
The valid indexes are:
0 1 2
Therefore, index 3 is invalid.
Passing an Array to a Method
An array can be passed as an argument to a method.
public class ArrayMethod { static void display(int[] numbers) { for (int number : numbers) { System.out.println(number); } } public static void main(String[] args) { int[] values = {10, 20, 30, 40}; display(values); } }
Output
10 20 30 40
Returning an Array from a Method
A method can also return an array.
public class ReturnArray { static int[] getNumbers() { int[] numbers = {10, 20, 30, 40}; return numbers; } public static void main(String[] args) { int[] result = getNumbers(); for (int number : result) { System.out.println(number); } } }
Useful Array Properties
The most commonly used array property is:
array.length
Example:
int[] numbers = {10, 20, 30, 40}; System.out.println(numbers.length);
Output:
4
Array vs Normal Variable
| Normal Variable | Array |
|---|---|
| Stores one value | Stores multiple values |
| Uses one variable name | Uses one variable name for many elements |
| No index required | Uses indexes |
Example: int age = 20; | Example: int[] ages = {20, 21, 22}; |
Advantages of Arrays
- Stores multiple values using one variable.
- Easy to access elements using indexes.
- Makes repetitive data processing easier.
- Works efficiently with loops.
- Useful for storing lists of similar data.
- Supports multidimensional data.
Disadvantages of Arrays
- Array size is fixed after creation.
- An array normally stores elements of the same type.
- Inserting and deleting elements can require additional work.
- Invalid indexes can cause exceptions.
- Arrays do not automatically grow or shrink.
Real-Life Applications of Arrays
Arrays are commonly used for:
- Student marks
- Employee salaries
- Product prices
- Monthly sales
- Temperature records
- Names of students
- Matrix operations
- Searching and sorting
- Storing collections of data
Complete Example
The following program stores student marks and calculates the total and average.
public class StudentMarks { public static void main(String[] args) { int[] marks = {80, 75, 90, 85, 70}; int total = 0; System.out.println("Student Marks:"); for (int mark : marks) { System.out.println(mark); total += mark; } double average = (double) total / marks.length; System.out.println("Total = " + total); System.out.println("Average = " + average); } }
Output
Student Marks: 80 75 90 85 70 Total = 400 Average = 80.0
Summary
An array is a collection of elements of the same data type stored under one variable name.
Important points:
- Array indexing starts from
0. - Array size is fixed after creation.
- Use
array.lengthto find the number of elements. - Use loops to process array elements.
- A one-dimensional array stores data in a list.
- A two-dimensional array stores data in rows and columns.
- A jagged array can have different numbers of elements in each row.
- Arrays can be passed to and returned from methods.
- Invalid indexes cause
ArrayIndexOutOfBoundsException.