One-Dimensional Arrays
A one-dimensional array (1D array) in Java is a linear data structure used to store multiple values of the same data type in a contiguous memory sequence, accessed using an index. This is a foundational Core Java topic and appears frequently in interviews, algorithms, and real-time applications.
What Is a One-Dimensional Array?
- Stores multiple values of the same type
- Uses a single index for access
- Index starts from 0
- Size is fixed once created
Why Use Arrays?
- Avoids creating multiple variables
- Efficient data storage
- Enables iteration and bulk processing
- Base for collections and algorithms
Declaration of 1D Array
Syntax
dataType[] arrayName;
or
dataType arrayName[];
Preferred (industry standard):
int[] numbers;
Array Creation (Instantiation)
int[] numbers = new int[5];
- Allocates memory for 5 elements
- Default values are assigned automatically
Default Values in Arrays
| Data Type | Default Value |
|---|---|
| int | 0 |
| double | 0.0 |
| boolean | false |
| char | '\u0000' |
| Object | null |
Array Initialization
1. Static Initialization
int[] numbers = {10, 20, 30, 40};
2. Dynamic Initialization
int[] numbers = new int[4];
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
Accessing Array Elements
int x = numbers[2]; // 30
⚠️ Accessing invalid index causes:
ArrayIndexOutOfBoundsException
Length of Array
int size = numbers.length;
Important: length is a property, not a method.
Traversing a 1D Array
Using for Loop
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
Using Enhanced for-each Loop
for (int num : numbers) {
System.out.println(num);
}
Example Program
int[] marks = {85, 90, 78};
int total = 0;
for (int m : marks) {
total += m;
}
System.out.println("Total: " + total);
Common Operations on 1D Arrays
Find Maximum Element
int max = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
Search an Element
int key = 20;
boolean found = false;
for (int n : arr) {
if (n == key) {
found = true;
break;
}
}
Memory Representation (Conceptual)
- Array stores elements contiguously
- Single reference points to the array
- All elements are of same data type
Limitations of 1D Arrays
- Fixed size
- Cannot grow or shrink dynamically
- Stores only same-type elements
Alternative: Use ArrayList for dynamic sizing.
Common Beginner Mistakes
- Using invalid index
- Confusing length with length()
- Forgetting array initialization
- Off-by-one errors in loops
- Expecting dynamic resizing
Interview-Ready Answers
Short Answer
A one-dimensional array stores multiple values of the same type using a single index.
Detailed Answer
In Java, a one-dimensional array is a linear data structure that holds fixed-size elements of the same data type. It allows indexed access starting from zero and supports traversal using loops.
Key Takeaway
One-dimensional arrays are simple, fast, and memory-efficient, making them ideal for fixed-size sequential data. Mastering them is essential before moving to 2D arrays and collections.
One-Dimensional Array Examples
1. Declare and Initialize a One-Dimensional Array
int[] nums = {10, 20, 30, 40};
Explanation
- Declares an integer array.
- Stores multiple values of the same type.
- Index starts from 0.
2. Declare Array First, Initialize Later
int[] nums;
nums = new int[]{5, 10, 15};
Explanation
- Useful when initialization happens dynamically.
- Common in real applications.
3. Create Array with Fixed Size
int[] nums = new int[3];
nums[0] = 10;
nums[1] = 20;
nums[2] = 30;
Explanation
- Allocates memory for 3 elements.
- Default value for int is 0.
4. Access Array Elements Using Index
int[] nums = {10, 20, 30};
System.out.println(nums[0]);
System.out.println(nums[1]);
Explanation
- Accessed using index.
- Output: 10 20
5. Iterate Array Using for Loop
int[] nums = {10, 20, 30};
for (int i = 0; i < nums.length; i++) {
System.out.println(nums[i]);
}
Explanation
- Uses index-based iteration.
- .length prevents out-of-bounds errors.
6. Iterate Array Using Enhanced for-each Loop
int[] nums = {10, 20, 30};
for (int n : nums) {
System.out.println(n);
}
Explanation
- Cleaner syntax.
- Best for read-only traversal.
7. Find Length of One-Dimensional Array
int[] nums = {1, 2, 3, 4};
System.out.println(nums.length);
Explanation
- .length is a property (not a method).
- Output: 4
8. Sum of Array Elements
int[] nums = {1, 2, 3, 4};
int sum = 0;
for (int n : nums) {
sum += n;
}
System.out.println(sum);
Explanation
- Accumulates all elements.
- Output: 10
9. Find Maximum Element in Array
int[] nums = {5, 2, 9, 1};
int max = nums[0];
for (int n : nums) {
if (n > max) {
max = n;
}
}
System.out.println(max);
Explanation
- Initializes max with first element.
- Output: 9
10. Find Minimum Element in Array
int[] nums = {5, 2, 9, 1};
int min = nums[0];
for (int n : nums) {
if (n < min) {
min = n;
}
}
System.out.println(min);
Explanation
- Tracks smallest value.
- Output: 1
11. Search Element in Array (Linear Search)
int[] nums = {10, 20, 30};
int target = 20;
boolean found = false;
for (int n : nums) {
if (n == target) {
found = true;
break;
}
}
System.out.println(found);
Explanation
- Checks each element sequentially.
- Output: true
12. Count Even Numbers in Array
int[] nums = {1, 2, 3, 4, 5};
int count = 0;
for (int n : nums) {
if (n % 2 == 0) {
count++;
}
}
System.out.println(count);
Explanation
- Counts values matching a condition.
- Output: 2
13. Copy One Array to Another
int[] src = {1, 2, 3};
int[] dest = new int[src.length];
for (int i = 0; i < src.length; i++) {
dest[i] = src[i];
}
Explanation
- Manual array copy.
- Both arrays are independent.
14. Reverse a One-Dimensional Array
int[] nums = {1, 2, 3, 4};
for (int i = nums.length - 1; i >= 0; i--) {
System.out.println(nums[i]);
}
Explanation
- Traverses array backward.
- Output: 4 3 2 1
15. Modify Array Elements Using Index Loop
int[] nums = {1, 2, 3};
for (int i = 0; i < nums.length; i++) {
nums[i] = nums[i] * 2;
}
for (int n : nums) {
System.out.println(n);
}
Explanation
- Index loop allows modification.
- Output: 2 4 6
16. Default Values in One-Dimensional Array
int[] nums = new int[3];
String[] names = new String[2];
System.out.println(nums[0]);
System.out.println(names[0]);
Explanation
- int default → 0
- String default → null
17. Array Index Out of Bounds (Runtime Error)
int[] nums = {1, 2, 3};
// System.out.println(nums[3]); // Runtime Exception
Explanation
- Valid indices: 0 to length - 1
- Accessing beyond causes ArrayIndexOutOfBoundsException.
18. One-Dimensional Array of Strings
String[] langs = {"Java", "Python", "C"};
for (String lang : langs) {
System.out.println(lang);
}
Explanation
- Stores reference types.
- Common in configuration and test data.
19. One-Dimensional Array with User-Defined Objects
class Employee {
String name;
Employee(String name) {
this.name = name;
}
}
Employee[] emp = {
new Employee("John"),
new Employee("Alice")
};
for (Employee e : emp) {
System.out.println(e.name);
}
Explanation
- Very common real-world use case.
- Array holds object references.
20. Interview Summary Example (One-Dimensional Array)
int[] nums = {10, 20, 30};
for (int i = 0; i < nums.length; i++) {
System.out.println(nums[i]);
}
Explanation
- Demonstrates:
- Declaration
- Indexing
- Traversal
- Extremely common interview question.