Working with One-Dimensional Arrays in Java
Course: Core Java Training
Topic: Working with One-Dimensional Arrays
Course Link: Core Java Training Course
Demo Link: Register for a Course Demo
Website: JustAcademy
1. Introduction to One-Dimensional Arrays
A one-dimensional array in Java is a data structure used to store multiple values of the same data type under a single variable name. Each value is stored at a numbered position called an index. Arrays are useful when a program needs to manage related data, such as student marks, employee salaries, product prices, or daily temperatures.
Instead of declaring multiple variables for similar values, a programmer can use one array and access each element through its index. Java arrays have a fixed length that is determined when the array is created.
For example, an array can store five student marks using a single variable named marks. The first element is accessed using marks[0], the second using marks[1], and so on.
2. Learning Objectives
- Understand the meaning and purpose of one-dimensional arrays.
- Learn array declaration, creation, and initialization.
- Understand zero-based indexing and array length.
- Access, modify, and display array elements.
- Traverse arrays using different types of loops.
- Perform calculations such as sum, average, maximum, and minimum.
- Search, reverse, copy, and sort array elements.
- Understand default values and common array exceptions.
- Apply arrays to practical Java programming problems.
3. What Is a One-Dimensional Array?
A one-dimensional array is a linear collection of elements stored in a sequence. Each element is accessed using one index.
Example
int[] numbers = {10, 20, 30, 40, 50};
The array contains five integer values. Each value has a unique index, starting from zero.
| Index |
Value |
Expression |
| 0 |
10 |
numbers[0] |
| 1 |
20 |
numbers[1] |
| 2 |
30 |
numbers[2] |
| 3 |
40 |
numbers[3] |
| 4 |
50 |
numbers[4] |
4. Features of One-Dimensional Arrays
- Fixed length: The size is established when the array is created.
- Same component type: An array stores elements compatible with its declared component type.
- Zero-based indexing: The first element is at index zero.
- Direct element access: Elements can be accessed by their indexes.
- Automatic default initialization: Java initializes array elements with type-specific default values.
- Object in Java: Arrays are objects and can be passed to methods or assigned to reference variables.
- Length property: The number of elements is available through the
length property.
5. Declaring a One-Dimensional Array
Array declaration specifies the data type of the elements and the name of the array variable. It does not, by itself, create the array object.
Syntax
dataType[] arrayName;
Examples
int[] numbers;
double[] prices;
char[] letters;
boolean[] status;
String[] names;
In these examples, the variables are declared to hold references to arrays of the specified component types. The array objects have not yet been created.
Java also permits the syntax int numbers[];, but the form int[] numbers; is generally preferred because it clearly associates the array type with the declaration.
6. Creating an Array Using the new Keyword
The new keyword creates an array object with a specified number of element positions.
Syntax
dataType[] arrayName = new dataType[size];
Example
public class ArrayCreationExample {
public static void main(String[] args) {
int[] numbers = new int[5];
System.out.println("Array created successfully");
System.out.println("Length: " + numbers.length);
}
}
Output:
Array created successfully
Length: 5
Explanation: The statement new int[5] creates an integer array with five positions. The length is five, and every element initially contains zero.
7. Initializing an Array with Values
Array initialization means assigning values to array elements. Java allows values to be supplied directly through an array initializer.
Example
public class ArrayInitializationExample {
public static void main(String[] args) {
int[] marks = {85, 90, 78, 92, 88};
System.out.println(marks[0]);
System.out.println(marks[2]);
System.out.println(marks[4]);
}
}
Output:
85
78
88
The array initializer automatically determines the length from the number of supplied elements. Here, five values create an array with a length of five.
Declaration and Initialization in Separate Statements
int[] values;
values = new int[]{10, 20, 30, 40};
When the array variable has already been declared, use new int[]{...} to assign an array initializer in a separate statement.
8. Understanding Zero-Based Indexing
Java arrays use zero-based indexing. This means the first element is stored at index zero rather than index one.
For an array of length n, the valid indexes range from 0 to n - 1, provided the array is not empty.
int[] values = {100, 200, 300};
System.out.println(values[0]); // 100
System.out.println(values[1]); // 200
System.out.println(values[2]); // 300
Important: Attempting to access values[3] causes an ArrayIndexOutOfBoundsException, because index three is outside the valid range.
9. Accessing Array Elements
An individual array element can be accessed by writing the array name followed by an index in square brackets.
Syntax
arrayName[index]
Example
public class ArrayAccessExample {
public static void main(String[] args) {
String[] languages = {"Java", "Python", "JavaScript"};
System.out.println("First: " + languages[0]);
System.out.println("Second: " + languages[1]);
System.out.println("Third: " + languages[2]);
}
}
Output:
First: Java
Second: Python
Third: JavaScript
Direct indexing is useful when a particular element is needed. Loops are more convenient when processing every element.
10. Modifying Array Elements
Array elements can be changed by assigning new values to their indexes. The array length remains unchanged when an element is updated.
public class ArrayUpdateExample {
public static void main(String[] args) {
int[] numbers = {10, 20, 30};
numbers[1] = 200;
System.out.println(numbers[0]);
System.out.println(numbers[1]);
System.out.println(numbers[2]);
}
}
Output:
10
200
30
The original value at index one was 20. After the assignment, it becomes 200. The other elements remain unchanged.
11. Understanding Array Length
The length property returns the total number of elements in an array. It is commonly used to determine how many iterations a loop should perform.
int[] numbers = {5, 10, 15, 20};
System.out.println(numbers.length); // 4
Remember these rules:
- Array length is a property, not a method.
- Use
array.length, not array.length().
- The length is fixed after the array is created.
- The last valid index is
array.length - 1 for a non-empty array.
- An empty array has a length of zero.
12. Default Values in One-Dimensional Arrays
When Java creates an array using a specified size, it automatically initializes each element with a default value based on the component type.
| Data Type |
Default Value |
byte |
0 |
short |
0 |
int |
0 |
long |
0L |
float |
0.0f |
double |
0.0d |
char |
'\u0000' |
boolean |
false |
Reference types, such as String |
null |
Example
public class DefaultValuesExample {
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
null
Default values do not necessarily indicate that a value has not been processed. For example, zero may be a valid score or quantity in an application.
13. Traversing an Array Using a for Loop
Array traversal means visiting array elements one by one. A standard for loop is useful when the index is needed for processing or updating elements.
public class ForLoopArrayExample {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
for (int i = 0; i < numbers.length; i++) {
System.out.println("Index " + i + ": " + numbers[i]);
}
}
}
Output:
Index 0: 10
Index 1: 20
Index 2: 30
Index 3: 40
Index 4: 50
Explanation: The loop begins at index zero and continues while i is less than the array length. This visits every valid element without accessing an invalid index.
14. Traversing an Array Using an Enhanced for Loop
The enhanced for loop, also known as the for-each loop, provides a simple way to read every element when the index is not required.
Syntax
for (dataType element : arrayName) {
// Process element
}
Example
public class EnhancedForExample {
public static void main(String[] args) {
String[] names = {"Aarav", "Priya", "Rahul"};
for (String name : names) {
System.out.println(name);
}
}
}
Output:
Aarav
Priya
Rahul
Use the enhanced loop when you need to read or process elements in sequence. A standard indexed loop is more appropriate when you need the index or want to assign values directly to array positions.
15. Traversing an Array Using a while Loop
A while loop can traverse an array by maintaining an index variable and increasing it after each iteration.
public class WhileLoopArrayExample {
public static void main(String[] args) {
int[] numbers = {11, 22, 33, 44};
int i = 0;
while (i < numbers.length) {
System.out.println(numbers[i]);
i++;
}
}
}
Output:
11
22
33
44
Always update the index in a way that allows the loop to terminate. If the index never changes and the condition remains true, the program may enter an infinite loop.
16. Calculating the Sum of Array Elements
To calculate the sum of an integer array, initialize a variable to zero and add each element during traversal.
public class ArraySumExample {
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 += numbers[i];
}
System.out.println("Sum: " + sum);
}
}
Output:
Sum: 150
The statement sum += numbers[i] adds the current element to the running total. For very large numeric totals, consider whether the chosen numeric type can represent the result without overflow.
17. Calculating the Average of Array Elements
The average is calculated by dividing the sum of all elements by the number of elements. An empty array must be handled separately to avoid division by zero.
public class ArrayAverageExample {
public static void main(String[] args) {
int[] marks = {80, 75, 90, 85};
int sum = 0;
if (marks.length == 0) {
System.out.println("No marks available");
return;
}
for (int mark : marks) {
sum += mark;
}
double average = (double) sum / marks.length;
System.out.println("Total: " + sum);
System.out.println("Average: " + average);
}
}
Output:
Total: 330
Average: 82.5
Casting the sum to double ensures that the division can produce a fractional result instead of integer division.
18. Finding the Largest Element
To find the maximum value, start with the first element as the current maximum and compare the remaining elements against it.
public class MaximumArrayExample {
public static void main(String[] args) {
int[] numbers = {45, 12, 89, 34, 67};
if (numbers.length == 0) {
System.out.println("Array is empty");
return;
}
int max = numbers[0];
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] > max) {
max = numbers[i];
}
}
System.out.println("Maximum: " + max);
}
}
Output:
Maximum: 89
Initializing the maximum from the first element allows the algorithm to work correctly when all values are negative. Always handle an empty array before accessing index zero.
19. Finding the Smallest Element
Finding the minimum follows the same pattern as finding the maximum, but the comparison checks whether the current value is smaller.
public class MinimumArrayExample {
public static void main(String[] args) {
int[] numbers = {45, 12, 89, 34, 67};
if (numbers.length == 0) {
System.out.println("Array is empty");
return;
}
int min = numbers[0];
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] < min) {
min = numbers[i];
}
}
System.out.println("Minimum: " + min);
}
}
Output:
Minimum: 12
20. Searching for an Element in an Array
Linear search checks array elements one by one until the target value is found or all elements have been examined.
public class LinearSearchExample {
public static void main(String[] args) {
int[] numbers = {10, 25, 30, 45, 50};
int target = 30;
int foundIndex = -1;
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] == target) {
foundIndex = i;
break;
}
}
if (foundIndex != -1) {
System.out.println("Found at index: " + foundIndex);
} else {
System.out.println("Element not found");
}
}
}
Output:
Found at index: 2
The variable foundIndex begins at -1, which indicates that the target has not been found. When the target is located, its index is stored and the loop stops.
21. Counting Even and Odd Numbers
Arrays can be used to count values that satisfy a condition. For integer values, the remainder operator % helps identify even and odd numbers.
public class EvenOddCountExample {
public static void main(String[] args) {
int[] numbers = {10, 15, 22, 31, 40, 47};
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: 3
22. Reversing an Array
Reversing an array means changing the order of its elements so that the last element becomes the first and the first becomes the last.
import java.util.Arrays;
public class ReverseArrayExample {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
int left = 0;
int right = numbers.length - 1;
while (left < right) {
int temp = numbers[left];
numbers[left] = numbers[right];
numbers[right] = temp;
left++;
right--;
}
System.out.println(Arrays.toString(numbers));
}
}
Output:
[50, 40, 30, 20, 10]
Explanation: The program swaps the first and last elements, then moves inward until the two pointers meet or cross. The reversal is performed in the original array without creating another array.
23. Copying an Array
Array copying creates a separate array containing the same element values. For primitive arrays, the values are copied. For arrays of objects, the references are copied, so the copy is shallow rather than a deep copy of the referenced objects.
Using Arrays.copyOf()
import java.util.Arrays;
public class CopyArrayExample {
public static void main(String[] args) {
int[] original = {10, 20, 30};
int[] copied = Arrays.copyOf(original, original.length);
copied[0] = 100;
System.out.println("Original: " + Arrays.toString(original));
System.out.println("Copied: " + Arrays.toString(copied));
}
}
Output:
Original: [10, 20, 30]
Copied: [100, 20, 30]
The copied array is a different array object. Updating an element in the copied primitive array does not change the corresponding element in the original array.
24. Comparing Arrays
Using == on array variables compares whether both variables refer to the same array object. It does not compare all elements. Use Arrays.equals() to compare corresponding elements in one-dimensional arrays.
import java.util.Arrays;
public class CompareArraysExample {
public static void main(String[] args) {
int[] first = {10, 20, 30};
int[] second = {10, 20, 30};
int[] third = first;
System.out.println(first == second);
System.out.println(Arrays.equals(first, second));
System.out.println(first == third);
}
}
Output:
false
true
true
Explanation: The first two arrays contain the same values but are separate objects. The third variable refers to the same array as first.
25. Sorting Array Elements
Sorting arranges array elements in a defined order. The Java utility class Arrays provides the sort() method for many common array types.
import java.util.Arrays;
public class SortArrayExample {
public static void main(String[] args) {
int[] numbers = {50, 10, 40, 20, 30};
Arrays.sort(numbers);
System.out.println(Arrays.toString(numbers));
}
}
Output:
[10, 20, 30, 40, 50]
The Arrays.sort() method modifies the array by sorting its elements in ascending order. For object arrays, ordering depends on natural ordering or a supplied comparator.
26. Displaying Array Elements with Arrays.toString()
For quick debugging and output, Arrays.toString() converts a one-dimensional array into a readable string representation.
import java.util.Arrays;
public class DisplayArrayExample {
public static void main(String[] args) {
int[] numbers = {5, 10, 15, 20};
System.out.println(Arrays.toString(numbers));
}
}
Output:
[5, 10, 15, 20]
Remember to import java.util.Arrays. Printing an array variable directly does not display its elements in this readable format.
27. Passing an Array to a Method
Arrays can be passed to methods, making it possible to reuse logic for calculations and other operations. Java passes the array reference value to the method, so changes to array elements inside the method can affect the same array object.
public class ArrayMethodExample {
static int calculateSum(int[] numbers) {
int sum = 0;
for (int number : numbers) {
sum += number;
}
return sum;
}
public static void main(String[] args) {
int[] values = {10, 20, 30};
System.out.println("Sum: " + calculateSum(values));
}
}
Output:
Sum: 60
The method accepts an integer array and returns the sum of its elements. For production code, define how the method should handle a null array reference if callers might pass one.
28. Common Errors When Working with Arrays
| Error |
Cause |
Solution |
ArrayIndexOutOfBoundsException |
Accessing an index outside the valid range. |
Use indexes from zero through length - 1. |
NullPointerException |
Accessing an array through a null reference. |
Initialize the array and check for null when necessary. |
| Incorrect loop limit |
Using an index less than or equal to the length. |
Use i < array.length for forward traversal. |
| Wrong default-value assumption |
Assuming every array element starts as null or an empty string. |
Remember the defaults for primitive and reference types. |
| Unintended shared array |
Assigning one array variable to another and assuming it copies the array. |
Use a copying method when a separate array is required. |
| Integer overflow |
A calculated sum exceeds the range of the chosen numeric type. |
Choose an appropriate numeric type and validate expected ranges. |
29. Practical Project: Student Marks Analyzer
In this project, a one-dimensional array stores student marks and the program calculates the total, average, maximum, and minimum marks.
public class StudentMarksAnalyzer {
public static void main(String[] args) {
int[] marks = {85, 90, 76, 92, 88};
if (marks.length == 0) {
System.out.println("No marks available");
return;
}
int total = 0;
int highest = marks[0];
int lowest = marks[0];
for (int mark : marks) {
total += mark;
if (mark > highest) {
highest = mark;
}
if (mark < lowest) {
lowest = mark;
}
}
double average = (double) total / marks.length;
System.out.println("Number of students: " + marks.length);
System.out.println("Total marks: " + total);
System.out.println("Average marks: " + average);
System.out.println("Highest marks: " + highest);
System.out.println("Lowest marks: " + lowest);
}
}
Output:
Number of students: 5
Total marks: 431
Average marks: 86.2
Highest marks: 92
Lowest marks: 76
Project Explanation
- The
marks array stores the five student scores.
- The program checks for an empty array before reading the first element.
- The loop calculates the total while updating the highest and lowest scores.
- The average is calculated by dividing the total by the array length.
- The results are displayed with descriptive labels.
30. Practice Exercises
Beginner-Level Exercises
- Declare an integer array containing five numbers and print every element.
- Create a string array containing five programming languages.
- Print the first and last elements of an array.
- Display the length of an array without counting its elements manually.
- Modify the value at a selected index and print the updated array.
Intermediate-Level Exercises
- Calculate the sum and average of an integer array.
- Find the largest and smallest values in an array.
- Count the even and odd numbers in an array.
- Search for a target number using linear search.
- Reverse an array without creating another array.
- Copy an array and verify that changes to the copied primitive array do not affect the original.
- Sort an integer array in ascending order.
Advanced-Level Exercises
- Build a student marks analyzer that displays the total, average, highest mark, and lowest mark.
- Write a method that accepts an array and returns the second-largest distinct value. Define how it handles empty arrays and arrays without a second distinct value.
- Merge two sorted integer arrays into one sorted array.
- Remove duplicate values from an array by creating a new array containing distinct values.
- Write a program that counts the frequency of each value in an integer array.
31. Interview Questions and Answers
Q1. What is a one-dimensional array in Java?
Answer: A one-dimensional array is an indexed collection of elements of the same declared component type, accessed using one index.
Q2. How do you declare an array in Java?
Answer: Use syntax such as int[] numbers; to declare an integer array variable.
Q3. How do you create an array?
Answer: Use the new keyword with a component type and size, for example, int[] numbers = new int[5];.
Q4. What is zero-based indexing?
Answer: It means the first element has index zero, the second has index one, and the last valid index is the array length minus one.
Q5. Can an array's length change after creation?
Answer: No. An array has a fixed length. A new array or a resizable collection is needed to accommodate a different number of elements.
Q6. What are the default values of array elements?
Answer: Primitive array elements receive type-specific defaults, such as zero for integer types and false for boolean. Reference type elements receive null.
Q7. What is the difference between a for loop and an enhanced for loop?
Answer: A standard for loop provides explicit index control, while an enhanced for loop directly visits elements when index-based operations are unnecessary.
Q8. How do you find the length of an array?
Answer: Use the length property, as in numbers.length.
Q9. What causes ArrayIndexOutOfBoundsException?
Answer: It occurs when code accesses an index smaller than zero or greater than or equal to the array length.
Q10. How can you find the largest element in an array?
Answer: Initialize a maximum variable with the first element, then compare each remaining element and update the maximum when a larger value is found.
Q11. How do you compare the contents of two arrays?
Answer: Use Arrays.equals() for a one-dimensional array of primitive values or object references according to the method's equality rules. The == operator compares array references.
Q12. How can you sort an array in Java?
Answer: Use Arrays.sort(array) for supported array types.
Q13. What is linear search?
Answer: Linear search checks each element in sequence until the target is found or the array has been fully examined.
Q14. What is the difference between an array and an ArrayList?
Answer: An array has a fixed length, while an ArrayList can grow or shrink as elements are added or removed. An ArrayList stores objects and wrapper types rather than primitive values directly.
Q15. Can an array store objects?
Answer: Yes. An array declared with a reference type, such as String[] or Student[], can store references to compatible objects.
32. Quick Revision Checklist
- A one-dimensional array stores elements in a linear sequence.
- Array indexes start at zero.
- Use
dataType[] arrayName to declare an array variable.
- Use
new dataType[size] to create an array of a specified size.
- Use an array initializer to supply values directly.
- Use
array.length to determine the number of elements.
- Use
i < array.length for safe forward traversal.
- Primitive array elements receive type-specific default values.
- Reference type array elements initially contain null references.
- Use loops for repeated calculations and element processing.
- Use
Arrays.toString() to display a one-dimensional array clearly.
- Use
Arrays.equals() to compare array contents.
- Use
Arrays.copyOf() when a separate copied array is required.
- Use
Arrays.sort() to sort supported arrays.
- Handle empty arrays and possible null references appropriately.
33. Conclusion
One-dimensional arrays are a fundamental part of Core Java programming. They make it possible to store and process multiple related values efficiently through a single array variable. By understanding declaration, creation, initialization, indexing, traversal, and length, developers can work with arrays confidently.
Practical operations such as calculating totals, finding maximum and minimum values, searching, sorting, reversing, and copying arrays provide a foundation for more advanced programming tasks. Careful handling of indexes, default values, empty arrays, and reference types helps prevent common errors.
Continue practising these examples and exercises to strengthen your Core Java fundamentals and prepare for programming assignments and technical interviews.
Learn more: Visit the Core Java Training Course, register for a course demo, or explore the JustAcademy website.