Single Dimensional Array in Java
Run each complete program separately. Its required helper classes and imports are included in the same code block. Short syntax fragments explain individual operations.
Introduction
A one-dimensional array gives each element a numbered position. For example, we can keep a week's reading times in one int array and use an index to choose a day. The array keeps its length after creation; changing an element does not change that length.
Suppose we want to store the marks of five students.
Without an array, we might write:
int mark1 = 80;
int mark2 = 75;
int mark3 = 90;
int mark4 = 85;
int mark5 = 70;This approach becomes difficult to manage when the number of values increases.
Using an array, we can store all the values using a single variable:
int[] marks = {80, 75, 90, 85, 70};Now the values are stored inside the marks array.
Index: 0 1 2 3 4
↓ ↓ ↓ ↓ ↓
+----+----+----+----+----+
marks → | 80 | 75 | 90 | 85 | 70 |
+----+----+----+----+----+Java arrays use zero-based indexing, which means the first element is stored at index 0.
What is a Single Dimensional Array?
A Single Dimensional Array is an array where elements are arranged in a single sequence.
For example:
int[] numbers = {10, 20, 30, 40, 50};The array can be represented as:
Index: 0 1 2 3 4
Value: 10 20 30 40 50To access an element, use:
arrayName[index]For example:
numbers[0]returns:
10and:
numbers[3]returns:
40Why Do We Need Arrays?
Arrays are useful when we need to store multiple values of the same type.
For example, suppose we need to store the temperatures of seven days.
Without an array:
double day1 = 32.5;
double day2 = 31.8;
double day3 = 33.1;
double day4 = 34.0;
double day5 = 32.9;
double day6 = 31.5;
double day7 = 30.8;Using an array:
double[] temperatures = {
32.5, 31.8, 33.1, 34.0, 32.9, 31.5, 30.8
};Now all seven values are represented by:
temperaturesThis makes the program easier to manage and process.
Declaring a Single Dimensional Array
There are two valid ways to declare an array.
Syntax 1
dataType[] arrayName;Example
int[] numbers;Syntax 2
dataType arrayName[];Example
int numbers[];Both are valid, but the first form is generally preferred:
int[] numbers;because it clearly indicates that numbers is an array of int.
Creating an Array
After declaring an array, we can create it using the new keyword.
int[] numbers = new int[5];Here:
int → element data type
[] → indicates an array
numbers → array variable
new → creates an array object
int[5] → creates space for 5 integersThe array contains five positions:
Index: 0 1 2 3 4
Value: 0 0 0 0 0The values are 0 because int array elements receive their default value when the array is created.
Program 1: Creating an Array
public class HelloWorld {
public static void main(String[] args) {
int[] numbers = new int[5];
System.out.println(numbers.length);
}
}Output
5The length property tells us how many elements the array can contain.
Initializing an Array
We can assign values to an array using indexes.
int[] numbers = new int[5];
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;The array becomes:
Index: 0 1 2 3 4
Value: 10 20 30 40 50Program 2: Initializing an Array Using Index
public class HelloWorld {
public static void main(String[] args) {
int[] numbers = new int[5];
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;
System.out.println(numbers[0]);
System.out.println(numbers[1]);
System.out.println(numbers[2]);
System.out.println(numbers[3]);
System.out.println(numbers[4]);
}
}Output
10
20
30
40
50Initializing an Array Using Array Literal
If the values are already known, we can initialize the array directly.
int[] numbers = {10, 20, 30, 40, 50};Java automatically determines the array size from the number of elements.
The above statement creates an array of length 5.
Program 3: Array Initialization Using Array Literal
public class HelloWorld {
public static void main(String[] args) {
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
50Accessing Array Elements
An array element can be accessed using its index.
arrayName[index]For example:
int[] numbers = {10, 20, 30, 40, 50};
System.out.println(numbers[0]);Output:
10The first element is always at index 0.
Program 4: Accessing an Array Element
public class HelloWorld {
public static void main(String[] args) {
int[] marks = {80, 75, 90, 85, 70};
System.out.println("First Mark: " + marks[0]);
System.out.println("Third Mark: " + marks[2]);
System.out.println("Last Mark: " + marks[4]);
}
}Output
First Mark: 80
Third Mark: 90
Last Mark: 70Modifying an Array Element
Array elements can be changed after the array has been created.
For example:
int[] numbers = {10, 20, 30};
numbers[1] = 100;The array changes from:
10 20 30to:
10 100 30Program 5: Modifying an Array Element
public class HelloWorld {
public static void main(String[] args) {
int[] numbers = {10, 20, 30};
System.out.println("Before: " + numbers[1]);
numbers[1] = 100;
System.out.println("After: " + numbers[1]);
}
}Output
Before: 20
After: 100Array Index
Array indexing starts from 0.
For:
int[] numbers = {10, 20, 30, 40};the indexes are:
Index: 0 1 2 3
Value: 10 20 30 40Therefore:
numbers[0] → 10
numbers[1] → 20
numbers[2] → 30
numbers[3] → 40The last valid index is:
array.length - 1For an array of length 4:
Last index = 4 - 1 = 3Program 6: Accessing the Last Element
Instead of directly writing the last index, we can use:
numbers[numbers.length - 1]Example
public class HelloWorld {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
int lastElement = numbers[numbers.length - 1];
System.out.println("Last Element: " + lastElement);
}
}Output
Last Element: 50Array Length
Every Java array has a length property.
Example
int[] numbers = {10, 20, 30, 40};
System.out.println(numbers.length);Output:
4Remember:
numbers.lengthis correct.
Do not write:
numbers.length()For arrays, length is a property.
Program 7: Using Array Length
public class HelloWorld {
public static void main(String[] args) {
String[] languages = {
"Java",
"Python",
"C++",
"JavaScript"
};
System.out.println("Number of Languages: " + languages.length);
}
}Output
Number of Languages: 4Traversing an Array Using for Loop
Traversing an array means accessing each element one by one.
A for loop is commonly used for this purpose.
int[] numbers = {10, 20, 30, 40, 50};
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}Here:
irepresents the current index.
Program 8: Traversing an Array
public class HelloWorld {
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
50How the Loop Works
For an array of length 5:
i = 0 → numbers[0]
i = 1 → numbers[1]
i = 2 → numbers[2]
i = 3 → numbers[3]
i = 4 → numbers[4]When:
i = 5the condition:
i < numbers.lengthbecomes:
5 < 5which is false.
Therefore, the loop stops.
Traversing an Array Using Enhanced for Loop
Java also provides the enhanced for loop.
Syntax:
for (dataType variable : array) {
// statements
}Example
for (int number : numbers) {
System.out.println(number);
}Program 9: Enhanced for Loop
public class HelloWorld {
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
50The enhanced for loop is useful when we need the values but do not need their indexes.
Difference Between for Loop and Enhanced for Loop
Traditional for loop
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}Useful when the index is required.
Enhanced for loop
for (int number : numbers) {
System.out.println(number);
}Useful when only the values are required.
Program 10: Display Index and Value
If we want both the index and the value, use a traditional for loop.
public class HelloWorld {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40};
for (int i = 0; i < numbers.length; i++) {
System.out.println(
"Index = " + i + ", Value = " + numbers[i]
);
}
}
}Output
Index = 0, Value = 10
Index = 1, Value = 20
Index = 2, Value = 30
Index = 3, Value = 40Default Values of an Array
When an array is created using new, Java automatically initializes its elements with default values.
Example
int[] numbers = new int[3];Initially:
0 0 0For a boolean array:
boolean[] flags = new boolean[3];the values are:
false false falseFor a String array:
String[] names = new String[3];the values are:
null null nullProgram 11: Default Values
public class HelloWorld {
public static void main(String[] args) {
int[] numbers = new int[3];
boolean[] flags = new boolean[3];
String[] names = new String[3];
System.out.println(numbers[0]);
System.out.println(flags[0]);
System.out.println(names[0]);
}
}Output
0
false
nullTaking Array Input from the User
We can use the Scanner class to create an array based on user input.
Program 12: Read Array Elements from User
import java.util.Scanner;
public class HelloWorld {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter array size: ");
int size = scanner.nextInt();
int[] numbers = new int[size];
System.out.println("Enter " + size + " numbers:");
for (int i = 0; i < numbers.length; i++) {
numbers[i] = scanner.nextInt();
}
System.out.println("Array elements:");
for (int number : numbers) {
System.out.println(number);
}
scanner.close();
}
}Example Input
Enter array size: 5
Enter 5 numbers:
10
20
30
40
50Output
Array elements:
10
20
30
40
50This is a common pattern for accepting array input:
int[] numbers = new int[size];
for (int i = 0; i < numbers.length; i++) {
numbers[i] = scanner.nextInt();
}Program 13: Find the Sum of Array Elements
We can calculate the sum by adding each element to a variable.
public class HelloWorld {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
int sum = 0;
for (int number : numbers) {
sum = sum + number;
}
System.out.println("Sum = " + sum);
}
}Output
Sum = 150The calculation is:
10 + 20 + 30 + 40 + 50 = 150Program 14: Find the Average
The average can be calculated using:
Average = Sum / Number of ElementsExample
public class HelloWorld {
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("Total Marks = " + sum);
System.out.println("Average Marks = " + average);
}
}Output
Total Marks = 400
Average Marks = 80.0The cast:
(double) sumensures that the division can produce a decimal result.
Program 15: Find the Largest Element
We can find the largest element by comparing every element with the current largest value.
public class HelloWorld {
public static void main(String[] args) {
int[] numbers = {25, 10, 45, 30, 15};
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 = 45Initially:
largest = numbers[0];So:
largest = 25Then the remaining elements are compared with 25.
When 45 is encountered:
45 > 25so:
largest = 45Program 16: Find the Smallest Element
The same logic can be used to find the smallest element.
public class HelloWorld {
public static void main(String[] args) {
int[] numbers = {25, 10, 45, 30, 15};
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 = 10Program 17: Search for an Element
We can search for an element by comparing the search value with every array element.
public class HelloWorld {
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 foundThis is an example of Linear Search because the elements are checked sequentially.
Program 18: Find the Index of an Element
Sometimes we need to know the position of the searched element.
public class HelloWorld {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
int search = 40;
int index = -1;
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] == search) {
index = i;
break;
}
}
if (index != -1) {
System.out.println(
"Element found at index: " + index
);
} else {
System.out.println("Element not found");
}
}
}Output
Element found at index: 3We use -1 to represent "not found" because valid array indexes start from 0.
Program 19: Count Even and Odd Numbers
An array can also be used to solve simple data-processing problems.
public class HelloWorld {
public static void main(String[] args) {
int[] numbers = {10, 15, 20, 25, 30, 35};
int evenCount = 0;
int oddCount = 0;
for (int number : numbers) {
if (number % 2 == 0) {
evenCount++;
} else {
oddCount++;
}
}
System.out.println("Even Numbers = " + evenCount);
System.out.println("Odd Numbers = " + oddCount);
}
}Output
Even Numbers = 3
Odd Numbers = 3Program 20: Print Only Even Numbers
public class HelloWorld {
public static void main(String[] args) {
int[] numbers = {10, 15, 20, 25, 30, 35};
System.out.println("Even Numbers:");
for (int number : numbers) {
if (number % 2 == 0) {
System.out.println(number);
}
}
}
}Output
Even Numbers:
10
20
30Program 21: Print Array in Reverse Order
We can traverse the array from the last index to the first index.
public class HelloWorld {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
for (int i = numbers.length - 1; i >= 0; i--) {
System.out.println(numbers[i]);
}
}
}Output
50
40
30
20
10This program prints the elements in reverse order but does not modify the original array.
Program 22: Reverse the Array
If we want to actually reverse the array, we can swap elements from both ends.
public class HelloWorld {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
int start = 0;
int end = numbers.length - 1;
while (start < end) {
int temp = numbers[start];
numbers[start] = numbers[end];
numbers[end] = temp;
start++;
end--;
}
System.out.println("Reversed Array:");
for (int number : numbers) {
System.out.println(number);
}
}
}Output
Reversed Array:
50
40
30
20
10The swapping happens like this:
10 20 30 40 50
↑ ↑
start endAfter the first swap:
50 20 30 40 10Then the next pair is swapped:
50 40 30 20 10Program 23: Sort an Array
Java provides the Arrays utility class to perform common array operations.
We can use:
Arrays.sort()to sort an array in ascending order.
import java.util.Arrays;
public class HelloWorld {
public static void main(String[] args) {
int[] numbers = {50, 20, 40, 10, 30};
Arrays.sort(numbers);
System.out.println(Arrays.toString(numbers));
}
}Output
[10, 20, 30, 40, 50]Program 24: Print an Array Using Arrays.toString()
If we write:
System.out.println(numbers);Java does not provide the elements in the usual array-list format.
Instead, use:
Arrays.toString(numbers)Example
import java.util.Arrays;
public class HelloWorld {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
System.out.println(Arrays.toString(numbers));
}
}Output
[10, 20, 30, 40, 50]Program 25: Copy an Array
Java provides Arrays.copyOf() to create a copy of an array.
import java.util.Arrays;
public class HelloWorld {
public static void main(String[] args) {
int[] original = {10, 20, 30, 40, 50};
int[] copy = Arrays.copyOf(
original,
original.length
);
System.out.println("Original: " + Arrays.toString(original));
System.out.println("Copy: " + Arrays.toString(copy));
}
}Output
Original: [10, 20, 30, 40, 50]
Copy: [10, 20, 30, 40, 50]Program 26: Compare Two Arrays
Using == compares the array references, not the contents.
int[] first = {10, 20, 30};
int[] second = {10, 20, 30};
System.out.println(first == second);Output:
falseTo compare the contents, use:
Arrays.equals()Example
import java.util.Arrays;
public class HelloWorld {
public static void main(String[] args) {
int[] first = {10, 20, 30};
int[] second = {10, 20, 30};
boolean result = Arrays.equals(first, second);
System.out.println(result);
}
}Output
trueProgram 27: Pass an Array to a Method
An array can be passed as an argument to a method.
public class HelloWorld {
static void printArray(int[] numbers) {
for (int number : numbers) {
System.out.println(number);
}
}
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40};
printArray(numbers);
}
}Output
10
20
30
40The method parameter:
int[] numbersmeans that the method accepts an integer array.
Program 28: Return an Array from a Method
A method can also return an array.
public class HelloWorld {
static int[] createArray() {
int[] numbers = {10, 20, 30, 40};
return numbers;
}
public static void main(String[] args) {
int[] result = createArray();
for (int number : result) {
System.out.println(number);
}
}
}Output
10
20
30
40The return type:
int[]indicates that the method returns an integer array.
Program 29: Array of Strings
Arrays can store reference types such as String.
public class HelloWorld {
public static void main(String[] args) {
String[] languages = {
"Java",
"Python",
"C++",
"JavaScript"
};
for (String language : languages) {
System.out.println(language);
}
}
}Output
Java
Python
C++
JavaScriptProgram 30: Array of Characters
A char array can store individual characters.
public class HelloWorld {
public static void main(String[] args) {
char[] letters = {'J', 'a', 'v', 'a'};
for (char letter : letters) {
System.out.println(letter);
}
}
}Output
J
a
v
aProgram 31: Array of Objects
Arrays can also store references to objects.
Consider a Student class:
class Student {
String name;
Student(String name) {
this.name = name;
}
}We can create an array of Student objects.
class Student {
String name;
Student(String name) {
this.name = name;
}
}
public class HelloWorld {
public static void main(String[] args) {
Student[] students = new Student[3];
students[0] = new Student("Amit");
students[1] = new Student("Priya");
students[2] = new Student("Rahul");
for (Student student : students) {
System.out.println(student.name);
}
}
}Output
Amit
Priya
RahulHere, the array stores references to Student objects.
ArrayIndexOutOfBoundsException
Java throws an ArrayIndexOutOfBoundsException when we try to access an invalid index.
Consider:
int[] numbers = {10, 20, 30};Valid indexes are:
0
1
2If we write:
System.out.println(numbers[3]);index 3 is outside the valid range.
Therefore, Java throws:
ArrayIndexOutOfBoundsExceptionProgram 32: Invalid Array Index
public class HelloWorld {
public static void main(String[] args) {
int[] numbers = {10, 20, 30};
System.out.println(numbers[3]);
}
}The program throws an exception because the last valid index is 2.
Remember:
First Index = 0
Last Index = length - 1Fixed Size of an Array
Once an array is created, its size cannot be changed.
For example:
int[] numbers = new int[5];The length is permanently:
5We cannot write:
numbers.length = 10;This is not allowed.
If the size needs to grow or shrink dynamically, a collection such as ArrayList may be more suitable.
Complete Practical Program
Let's combine several array concepts into one practical program.
The program will:
- Read the number of elements.
- Read the elements.
- Display the array.
- Calculate the sum.
- Calculate the average.
- Find the largest value.
- Find the smallest value.
import java.util.Scanner;
import java.util.Arrays;
public class HelloWorld {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter number of elements: ");
int size = scanner.nextInt();
int[] numbers = new int[size];
System.out.println("Enter " + size + " numbers:");
for (int i = 0; i < numbers.length; i++) {
numbers[i] = scanner.nextInt();
}
int sum = 0;
int largest = numbers[0];
int smallest = numbers[0];
for (int number : numbers) {
sum += number;
if (number > largest) {
largest = number;
}
if (number < smallest) {
smallest = number;
}
}
double average = (double) sum / numbers.length;
System.out.println();
System.out.println("Array: " + Arrays.toString(numbers));
System.out.println("Sum: " + sum);
System.out.println("Average: " + average);
System.out.println("Largest: " + largest);
System.out.println("Smallest: " + smallest);
scanner.close();
}
}Example Input
Enter number of elements: 5
Enter 5 numbers:
25
10
45
30
15Output
Array: [25, 10, 45, 30, 15]
Sum: 125
Average: 25.0
Largest: 45
Smallest: 10Common Mistakes
Mistake 1: Starting the Index from 1
Incorrect:
for (int i = 1; i <= numbers.length; i++) {
System.out.println(numbers[i]);
}This can cause an exception because the last valid index is:
numbers.length - 1Correct:
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}Mistake 2: Using length()
Incorrect:
numbers.length()Correct:
numbers.lengthMistake 3: Accessing an Invalid Index
For:
int[] numbers = new int[5];valid indexes are:
0, 1, 2, 3, 4This is invalid:
numbers[5]Mistake 4: Assuming Array Size Can Change
Once created:
int[] numbers = new int[5];the array size remains 5.
An array does not automatically expand when additional elements are needed.
Advantages of Single Dimensional Arrays
1. Simple Structure
Arrays provide a straightforward way to store multiple values.
2. Fast Access
Elements can be accessed directly using their indexes.
numbers[3]3. Easy Traversal
Arrays can easily be processed using loops.
4. Useful for Fixed-Size Data
Arrays are suitable when the number of elements is known in advance.
5. Supports Primitive Types
Arrays can directly store primitive values such as:
int
double
char
booleanLimitations of Single Dimensional Arrays
1. Fixed Size
The size cannot be changed after creation.
2. Same Element Type
The elements must be compatible with the array's declared type.
For example:
int[] numbers = {10, 20, 30};cannot directly contain a String.
3. No Built-In add() or remove()
Arrays do not provide methods such as:
add()
remove()For dynamically changing collections, classes such as ArrayList can be used.
Array vs ArrayList
| Feature | Array | ArrayList |
|---|---|---|
| Size | Fixed | Dynamic |
| Index-based access | Yes | Yes |
length | Yes | No |
size() | No | Yes |
add() | No | Yes |
remove() | No | Yes |
| Primitive types directly | Yes | No |
| Collections Framework | No | Yes |
Example
int[] numbers = new int[5];versus:
ArrayList<Integer> numbers = new ArrayList<>();An array is useful when the size is fixed or known. An ArrayList is useful when the collection needs to grow or shrink dynamically.
Key Points to Remember
- A Single Dimensional Array stores elements in a single sequence.
- An array stores elements of the same declared type.
- Array indexing starts from
0. - The first element is at index
0. - The last element is at index
array.length - 1. - Use
array[index]to access an element. - Use
array.lengthto get the number of elements. - An array has a fixed size after creation.
- Arrays can store primitive values and object references.
- Use a
forloop when the index is required. - Use an enhanced
forloop when only the values are required. ArrayIndexOutOfBoundsExceptionoccurs when an invalid index is accessed.Arrays.toString()can be used to display a one-dimensional array.Arrays.sort()can be used to sort an array.Arrays.equals()can be used to compare array contents.- Arrays can be passed to methods and returned from methods.
- Use
ArrayListwhen a dynamically sized collection is required.
See you in next page....🙂