Introduction
A one-dimensional array (1D array) stores multiple values of the same declared element type in a single sequence. Instead of creating a separate variable for every value, you can keep related values under one array name and access each value by its index.
Premium Video
This video is available to Premium members or users who have purchased the course.
Sign in to UnlockFor example, a program that stores five exam marks could use five separate variables. That approach quickly becomes difficult to manage if there are hundreds of marks. An array groups the values together, and loops let a program process all of them with a small amount of code.
Arrays are commonly used for student marks, product prices, daily temperatures, employee IDs, stock quantities, and other sequences of data.
This ExamAdda guide covers array declaration, creation, initialization, indexing, updating, traversal, user input, common errors, time complexity, and exam practice. Every Java program uses public class Main and public static void main(String[] args). Copy and run each program separately.
Learning objectives
By the end of this lesson, you will be able to:
- Explain what a 1D array is and when to use one.
- Declare, create, and initialize an array.
- Understand indexes, array length, and default values.
- Access and update array elements safely.
- Traverse an array using standard and enhanced
forloops. - Read array elements from user input.
- Recognize common errors and estimate basic time complexity.
1. Understanding a one-dimensional array
Consider the following array:
It contains five integer values. Each value occupies a position identified by an index.
| Index | 0 | 1 | 2 | 3 | 4 |
|---|---|---|---|---|---|
| Value | 78 | 85 | 92 | 67 | 88 |
The index and value are different concepts. Index 2 refers to the third position; the value at that position is 92.
Java arrays use zero-based indexing:
- The first element is at index
0. - The second element is at index
1. - The last element is at index
array.length - 1. - An array with length
nhas valid indexes from0throughn - 1.
For an array of length 5, index 4 is valid but index 5 is not. Trying to access an invalid index causes ArrayIndexOutOfBoundsException.
2. Declaring an array
An array declaration specifies the type of elements the array can hold and the variable name.
General syntax
Examples:
int[] marks;— an array variable intended for integers.double[] prices;— an array variable intended for decimal numbers.String[] names;— an array variable intended for string references.
Java also accepts int marks[];, but int[] marks; is the commonly recommended style because it clearly shows that the type is an array of integers.
Important: declaration alone does not create an array object. It introduces a variable that must be assigned an array before its elements can be used. Local variables inside a method must be assigned before use.
3. Creating an array with new
Use new to create an array with a specified length.
General syntax
For example, new int[5] creates five integer slots. The size determines the array's length, and Java initializes the elements to their default values.
The array's length is fixed when the array object is created. You can replace the value in an existing slot, but you cannot resize that same array object. If a program needs a collection that can grow or shrink, ArrayList may be more suitable.
Default values
Java initializes array elements automatically when an array is created with new.
| Element type | Default value |
|---|---|
byte, short, int, long | 0 |
float, double | 0.0 |
char | '\u0000' (null character) |
boolean | false |
Reference types, such as String | null |
A null reference is not the same as an empty string (""). An empty string is a real string with zero characters. null means the slot does not refer to a string object. Calling a method on a null element causes NullPointerException.
4. Initializing an array
When values are already known, you can initialize an array in the declaration:
Java determines the length from the number of values. This array has length 5.
You may also write new int[] {10, 20, 30}. The explicit form is especially useful when assigning a new array to a variable declared earlier. The shorter brace form is usually used directly with the declaration.
Use initialization with values when the data is known in advance. Use new int[size] when you know how many slots you need but will fill them later.
5. Accessing and updating array elements
To access an element, write the array name followed by an index in square brackets: arrayName[index].
For example:
numbers[0]accesses the first element.numbers[2]accesses the third element.numbers[numbers.length - 1]accesses the last element when the array is not empty.
To update an element, assign a new value to a valid index. If numbers contains {10, 20, 30}, the statement numbers[1] = 99; changes it to {10, 99, 30}. The other elements remain unchanged.
Always check the index range. An index must be at least 0 and less than the array length.
6. Finding the array length
Use the length field to find the number of elements in an array. Write numbers.length, without parentheses.
This is different from a string, which uses the method text.length().
If an array has length 5:
- Number of elements:
5 - First valid index:
0 - Last valid index:
4
An empty array has length 0, so it has no valid element indexes. Check that the array is not empty before accessing its first or last element.
7. Traversing an array with a standard for loop
Traversal means visiting array elements one by one. A standard for loop is useful when you need both the index and the value, such as when displaying positions or updating particular elements.
Complete example: declaration, access, update, and traversal
Output
Number of marks: 5
First mark: 78
Marks after updating the third element:
Index 0: 78
Index 1: 85
Index 2: 95
Index 3: 67
Index 4: 88
How it works
- The array initializer creates five elements.
marks.lengthreports5.marks[0]reads the first element.marks[2] = 95replaces the value at index2.- The loop starts at
i = 0, prints the element at the current index, and incrementsi. - The loop stops when
iis no longer less than the array length.
Use i < marks.length, not i <= marks.length. The latter eventually tries to read the element at index 5, which is outside this array.
8. Traversing with an enhanced for loop
The enhanced for loop, also called a for-each loop, is convenient when you need each value but do not need its index.
Complete example: for-each traversal
Output
Java
Mathematics
Science
Read for (String subject : subjects) as “for each subject in subjects.” The loop visits each value in order.
| Task | Recommended loop | Reason |
|---|---|---|
| Display every value | Enhanced for | Short and readable |
| Display indexes with values | Standard for | Provides the index |
| Update array elements | Standard for | Lets you assign to array[i] |
| Traverse backward | Standard for | Gives control over the index |
| Read values only | Enhanced for | Avoids index bookkeeping |
Common mistake: changing only the loop variable
For a primitive array, the enhanced loop variable receives a copy of the current value. Assigning a new value to that local variable does not update the array element. To modify the array, use an indexed loop and assign to array[i].
9. Reading array values from user input
The Scanner class can read values entered by the user. The following program reads five integers, stores them in an array, and then prints the values.
Complete example: input and output
Sample input
10 20 30 40 50Output
Enter five integers:
Array elements:
10
20
30
40
50
The first loop reads five integers because the array length is five. Each value is stored at the current index. The second loop prints the stored values.
When using an online judge, match the expected input format. If the platform expects only numbers and no prompt text, remove System.out.println("Enter five integers:"); to avoid extra output.
10. Flowchart: traversing a 1D array
The flowchart below shows the logic of a standard array traversal loop.
The loop checks the condition before every iteration. If the index is valid, the program processes the element and increments the index. Once i becomes equal to the length, the condition is false and the loop ends.
11. Accessing the first and last elements safely
For a non-empty array, the first element is at index 0, and the last element is at index array.length - 1.
For example, an array with length 4 has indexes 0, 1, 2, and 3. Its last element is at index 3, not 4.
An empty array has length 0. In that case, neither array[0] nor array[array.length - 1] is valid. Check array.length > 0 before reading either end.
12. Common mistakes to avoid
Using i <= array.length: the final valid index is array.length - 1. Use i < array.length for ordinary forward traversal.
Confusing length and length(): arrays use the field array.length; strings use the method text.length().
Using an array before assigning it: declaring int[] numbers; does not create an array object. A local variable must be assigned before use.
Accessing a null array reference: if the reference itself is null, reading numbers.length or numbers[0] causes NullPointerException.
Expecting an array to resize: array length is fixed after creation. Consider ArrayList if the number of elements must change.
Assuming an enhanced loop updates primitive elements: assigning to value in for (int value : numbers) does not update the corresponding array slot. Use numbers[i] = ... in an indexed loop.
Accessing the first element of an empty array: check the length before using index 0.
13. Time complexity of common array operations
Let n be the number of elements in the array.
| Operation | Time complexity | Explanation |
|---|---|---|
| Read an element by index | O(1) | Access a known position |
| Update an element by index | O(1) | Assign to a known position |
Read array.length | O(1) | Length is directly available |
| Traverse every element | O(n) | Visits all elements |
| Search through an unsorted array | O(n) worst case | May inspect every element |
These are standard asymptotic estimates describing how work grows as the input grows, not exact execution times.
14. Best practices
- Use an enhanced
forloop when you only need to read values. - Use a standard
forloop when you need indexes or must update array slots. - Prefer
int[] numbersoverint numbers[]for consistency and readability. - Check array length before accessing the first or last element.
- Keep loop boundaries clear and use
i < array.length. - Remember that array length is fixed after creation.
- Use meaningful variable names such as
marks,temperatures, orproductPrices.
15. Practice questions
Try answering these before looking at the answers.
- What is a one-dimensional array?
- What is the output of
numbers[1]ifint[] numbers = {5, 15, 25};? - How many elements does
new int[8]create? - What is the last valid index of an array whose length is
8? - Is array
lengtha field or a method? - Which loop is convenient when you need each value but not its index?
- What exception can occur when you access an index outside the valid range?
- Can the length of an existing array object be changed?
- What is the time complexity of traversing all elements?
Answers
- A sequence of values of the same declared element type, accessed by index.
15- Eight elements.
7- A field.
- The enhanced
forloop. ArrayIndexOutOfBoundsException.- No, its length is fixed after creation.
- O(n).
16. Frequently asked questions (FAQs)
What is a 1D array in Java?
A one-dimensional array stores multiple elements of the same declared type in a sequence. Each element is accessed using an integer index.
Why does array indexing start at zero?
Java uses zero-based indexing. For an array of length n, valid indexes are 0 through n - 1.
What is the difference between declaration and initialization?
Declaration introduces the array variable, such as int[] numbers;. Initialization supplies values, such as int[] numbers = {10, 20, 30};. Creating an array with new int[3] allocates three slots and fills them with default values.
Can a Java array grow automatically?
No. The length of an array object is fixed. Use a resizable collection such as ArrayList when the number of elements must change.
How do I print all array elements?
Use a standard for loop if you need the index, or an enhanced for loop if you only need the values.
What is the difference between array.length and String.length()?
For arrays, length is a field and has no parentheses. For strings, length() is a method and requires parentheses.
Quick revision
- A 1D array stores multiple values of the same declared element type.
- Indexing starts at
0; the last valid index isarray.length - 1. - Use
new int[size]to create an array of a given length. - Use an array initializer when values are known in advance.
- Use
array[index]to read or update an element. - Use
array.lengthto get the number of elements. - Use a standard
forloop when you need the index. - Use an enhanced
forloop for simple value-by-value traversal. - Check empty arrays before accessing the first or last element.
- Array access and updates by index take O(1) time; full traversal takes O(n).
Conclusion
One-dimensional arrays are a foundation of Java programming. They store related values under one variable name and allow programs to read, update, and process those values using indexes and loops. Once declaration, creation, initialization, indexing, and traversal are clear, you are ready to study array operations such as summing values, searching, sorting, reversing, and finding minimums or maximums.