Java Notes
Complete guide to one-dimensional arrays in Java covering declaration, initialization, memory layout, traversal techniques, input/output operations, and practical programs with detailed explanations.
What is a One-Dimensional Array?
A one-dimensional array (also called a linear array or 1D array) is the simplest form of an array. It is a single row of elements arranged sequentially in memory, where each element is identified by a single index number starting from 0.
Think of a 1D array as a train with numbered compartments. Each compartment can hold one passenger (value), and you identify each compartment by its number (index). The train has a fixed number of compartments that cannot change after it is built.
Visual Representation:
In this example:
- Array name:
marks - Size: 5 elements
- First element:
marks[0]= 85 - Last element:
marks[4]= 88 - Valid indices: 0 to 4 (i.e., 0 to length-1)
Declaration of One-Dimensional Array
Declaration creates a reference variable that will eventually point to an array. No memory is allocated for elements at this point.
Syntax Options
Examples of Declaration
int[] marks; // Array of integers
double[] prices; // Array of doubles
String[] names; // Array of Strings
char[] vowels; // Array of characters
boolean[] attendance; // Array of booleans
float[] temperatures; // Array of floats
long[] populations; // Array of longsImportant: After declaration, the variable has the value null (for instance/class variables) or is uninitialized (for local variables).
public class DeclarationDemo {
static int[] classLevel; // Initialized to null automatically
public static void main(String[] args) {
int[] localArr; // NOT initialized — using it causes compile error
System.out.println(classLevel); // Prints: null
// System.out.println(localArr); // Compile error!
}
}null
Creation (Memory Allocation)
The new keyword allocates memory in the heap for the array elements.
Syntax
Size Rules
- Size must be a non-negative integer (0 is valid — creates an empty array)
- Size can be a variable, expression, or constant
- Size is fixed once created — cannot be changed later
arr1 length: 5 arr2 length: 10 arr3 length: 20 arr4 length: 0
Memory Layout After Creation
Memory Diagram:
| +----------+ Address | 0x7A20 0x7A24 0x7A28 0x7A2C |
| Index | [0] [1] [2] [3] |
| - Class | int[] |
| - Length | 4 |
| - Element size | 4 bytes (int) |
| - Total data | 16 bytes |
Initialization Techniques
Technique 1: Individual Assignment
2 3 5 7 11
Technique 2: Array Literal (Static Initialization)
public class ArrayLiteral {
public static void main(String[] args) {
// Declaration + initialization in one line
int[] fibonacci = {0, 1, 1, 2, 3, 5, 8, 13, 21, 34};
String[] days = {"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"};
char[] grades = {'A', 'B', 'C', 'D', 'F'};
System.out.println("Fibonacci: " + java.util.Arrays.toString(fibonacci));
System.out.println("Days: " + java.util.Arrays.toString(days));
System.out.println("Grades: " + java.util.Arrays.toString(grades));
}
}Fibonacci: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] Days: [Mon, Tue, Wed, Thu, Fri, Sat, Sun] Grades: [A, B, C, D, F]
Technique 3: Using Loop Initialization
Squares of 1-10: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] Random: [42, 87, 15, 63, 91]
Technique 4: Using Arrays.fill()
All fives: [5, 5, 5, 5, 5, 5, 5, 5] Partial fill: [0, 0, 99, 99, 99, 99, 99, 0, 0, 0]
Reading Array Input from User
Using Scanner
Enter array size: 5 Enter 5 elements: 10 20 30 40 50 You entered: [10, 20, 30, 40, 50]
Reading String Array
How many names? 3 Enter 3 names: Alice Bob Charlie Names: [Alice, Bob, Charlie]
Array Traversal Methods
Forward Traversal
Forward traversal: 10 20 30 40 50
Reverse Traversal
Reverse traversal: 50 40 30 20 10
Using Enhanced For Loop
public class EnhancedForLoop {
public static void main(String[] args) {
double[] temperatures = {36.5, 37.2, 38.0, 36.8, 37.5};
double sum = 0;
for (double temp : temperatures) {
sum += temp;
}
System.out.printf("Average temperature: %.2f%n", sum / temperatures.length);
}
}Average temperature: 37.20
Array Copying
Shallow Copy (Reference Copy)
Original: [99, 2, 3, 4, 5] Copy: [99, 2, 3, 4, 5] Same object? true
Deep Copy Methods
Original: [99, 2, 3, 4, 5] Copy1 (copyOf): [1, 2, 3, 4, 5] Copy2 (arraycopy): [1, 2, 3, 4, 5] Copy3 (clone): [1, 2, 3, 4, 5] Copy4 (manual): [1, 2, 3, 4, 5]
Copying a Range
Sub-array [2, 5): [30, 40, 50] Expanded: [10, 20, 30, 40, 50, 60, 70, 0, 0, 0]
java.util.Arrays Utility Class
The Arrays class provides many useful static methods for working with arrays.
Original: [34, 12, 56, 78, 23, 45, 89, 1] Sorted: [1, 12, 23, 34, 45, 56, 78, 89] 56 found at index: 5 Arrays equal? true Filled: [7, 7, 7, 7, 7]
Passing 1D Array to Methods
Array: [45, 23, 78, 12, 56, 89, 34] Maximum: 89 Average: 48.14 Reversed: [34, 89, 56, 12, 78, 23, 45]
Variable-Length Arguments (Varargs)
Java allows passing a variable number of arguments using varargs, which internally creates an array.
public class VarargsDemo {
public static int sum(int... numbers) { // Varargs = array
int total = 0;
for (int num : numbers) {
total += num;
}
return total;
}
public static void main(String[] args) {
System.out.println("Sum(1,2,3): " + sum(1, 2, 3));
System.out.println("Sum(10,20): " + sum(10, 20));
System.out.println("Sum(5): " + sum(5));
System.out.println("Sum(): " + sum());
// Can also pass an array
int[] arr = {1, 2, 3, 4, 5};
System.out.println("Sum(array): " + sum(arr));
}
}Sum(1,2,3): 6 Sum(10,20): 30 Sum(5): 5 Sum(): 0 Sum(array): 15
Practical Programs
Program 1: Find Second Largest Element
public class SecondLargest {
public static void main(String[] args) {
int[] arr = {45, 78, 23, 89, 56, 12, 89, 67};
int first = Integer.MIN_VALUE;
int second = Integer.MIN_VALUE;
for (int num : arr) {
if (num > first) {
second = first;
first = num;
} else if (num > second && num != first) {
second = num;
}
}
System.out.println("Array: " + java.util.Arrays.toString(arr));
System.out.println("Largest: " + first);
System.out.println("Second Largest: " + second);
}
}Array: [45, 78, 23, 89, 56, 12, 89, 67] Largest: 89 Second Largest: 78
Program 2: Count Even and Odd Numbers
Array: [12, 7, 34, 55, 8, 91, 24, 3, 60, 17] Even count: 5 Odd count: 5
Program 3: Linear Search
78 found at index 3
Common Mistakes
1. Forgetting that Indices Start at 0
2. ArrayIndexOutOfBoundsException in Loops
3. Reference Copy vs Value Copy
4. Using Uninitialized Local Array
5. Trying to Print Array with println()
Best Practices
- Use
arr.lengthin loop conditions — never hardcode array size - Prefer for-each when only reading elements (cleaner, no index errors)
- Validate array bounds before accessing computed indices
- Use
Arrays.toString()for debugging and printing - Use
Arrays.sort()instead of writing your own sort for production code - Consider ArrayList if size is unknown at compile time
- Use
Arrays.copyOf()for safe copies instead of manual loops - Initialize arrays in constructors or at declaration for class fields
- Avoid magic numbers — use named constants for array sizes
- Check for null before operating on arrays received as parameters
Interview Questions
Q1: What is a one-dimensional array? A 1D array is a linear data structure storing elements of the same type in contiguous memory, accessed by a single integer index starting from 0.
Q2: What happens if we access index -1 or index >= length? Java throws ArrayIndexOutOfBoundsException at runtime.
Q3: How do you resize an array in Java? You cannot resize. Create a new array with the desired size and copy elements using Arrays.copyOf() or System.arraycopy().
Q4: What is the difference between int[] a = b and int[] a = b.clone()? a = b makes both variables point to the same array (reference copy). a = b.clone() creates a new array with the same values (deep copy for primitives).
Q5: Can array size be 0? Yes. new int[0] creates a valid array with length 0. Useful as return value when no results exist.
Q6: What is the maximum size of an array in Java? Theoretically Integer.MAX_VALUE (2^31 - 1 ≈ 2.1 billion), but practically limited by available heap memory.
Q7: How does for-each loop work with arrays? The compiler converts for(int x : arr) to a regular for loop with index. You cannot modify the array or know the current index with for-each.
Q8: What is System.arraycopy() and how is it different from Arrays.copyOf()? System.arraycopy(src, srcPos, dest, destPos, length) copies elements between existing arrays. Arrays.copyOf(src, newLength) creates a new array and copies elements. Both use native memory operations and are faster than manual loops.
Q9: What are varargs and how do they relate to arrays? Varargs (int... args) allow passing variable number of arguments to a method. Internally, Java creates an array from the arguments.
Q10: Why is array access O(1)? Because elements are in contiguous memory. The address of element i is calculated as: baseAddress + i * elementSize. This formula gives instant access regardless of array size.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for One Dimensional Array.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Java Master Course topic.
Search Terms
java-master-course, java master course, java, master, course, fundamentals, arrays, one
Related Java Master Course Topics