Single-Dimensional Array in Java – Explained with Examples
A single-dimensional array (also called a one-dimensional or 1D array) is a simple list of values of the same type, stored one after another and accessed by a single index. It is the most common kind of array: a list of marks, prices, names or temperatures.
This tutorial shows how to declare and fill 1D arrays, read values from the user, solve classic array problems such as reversing and searching, pass arrays to methods, and store objects in arrays. For the basics of arrays in general, see Arrays in Java.
1. Declaration and Initialisation
dataType[] name = new dataType[size]; // empty array with default values
dataType[] name = {value1, value2, ...}; // array with initial values
double[] prices = new double[4];
String[] cities = {"Pune", "Delhi", "Kochi"};
char[] vowels = {'a', 'e', 'i', 'o', 'u'};
2. Reading Values into an Array
A common pattern is to read the number of values first, create an array of that size, and then fill it in a loop. The sample input is 6 followed by 42 17 88 5 63 29:
import java.util.Scanner;
public class ReadIntoArray {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt(); // how many values
int[] values = new int[n];
for (int i = 0; i < n; i++) {
values[i] = in.nextInt();
}
int sum = 0, min = values[0], max = values[0];
for (int v : values) {
sum += v;
min = Math.min(min, v);
max = Math.max(max, v);
}
System.out.println("Read " + n + " values");
System.out.println("sum = " + sum + ", min = " + min + ", max = " + max);
System.out.printf("average = %.2f%n", (double) sum / n);
}
}
Read 6 values sum = 244, min = 5, max = 88 average = 40.67
3. Classic Array Algorithms
Many interview and exam questions are about 1D arrays. Here are four of the most common, each in a few lines:
import java.util.Arrays;
public class ArrayAlgorithms {
static void reverse(int[] a) { // swap from both ends
for (int i = 0, j = a.length - 1; i < j; i++, j--) {
int tmp = a[i]; a[i] = a[j]; a[j] = tmp;
}
}
static int linearSearch(int[] a, int key) {
for (int i = 0; i < a.length; i++) if (a[i] == key) return i;
return -1;
}
static int secondLargest(int[] a) {
int first = Integer.MIN_VALUE, second = Integer.MIN_VALUE;
for (int v : a) {
if (v > first) { second = first; first = v; }
else if (v > second && v != first) second = v;
}
return second;
}
public static void main(String[] args) {
int[] data = {14, 3, 27, 8, 27, 19};
System.out.println("search 8: index " + linearSearch(data, 8));
System.out.println("second largest: " + secondLargest(data));
int count = 0;
for (int v : data) if (v == 27) count++;
System.out.println("27 appears " + count + " times");
reverse(data);
System.out.println("reversed: " + Arrays.toString(data));
}
}
search 8: index 3 second largest: 19 27 appears 2 times reversed: [19, 27, 8, 27, 3, 14]
- Reverse in place: swap the first and last elements, then move inward. It needs no extra array.
- Linear search: check each element in turn; return
-1when not found. For a sorted array,Arrays.binarySearch()is much faster. - Second largest: track the two largest distinct values in one pass.
- Frequency: count matches in a loop.
4. Passing Arrays to Methods and Returning Them
When you pass an array to a method, Java copies the reference, so the method works on the same array object and its changes are visible to the caller. A method can also build and return a new array:
import java.util.Arrays;
public class ArraysAndMethods {
// The method receives a copy of the REFERENCE, so it can change the caller's array
static void applyDiscount(double[] prices, double percent) {
for (int i = 0; i < prices.length; i++) {
prices[i] = prices[i] * (100 - percent) / 100;
}
}
// A method can also create and return a new array
static int[] evensUpTo(int limit) {
int[] result = new int[limit / 2];
for (int i = 0; i < result.length; i++) result[i] = (i + 1) * 2;
return result;
}
public static void main(String[] args) {
double[] prices = {100, 250, 80};
applyDiscount(prices, 10);
System.out.println("after discount: " + Arrays.toString(prices));
System.out.println("evens up to 10: " + Arrays.toString(evensUpTo(10)));
}
}
after discount: [90.0, 225.0, 72.0] evens up to 10: [2, 4, 6, 8, 10]
If a method should not change the caller's data, pass a copy: applyDiscount(prices.clone(), 10).
5. Arrays of Objects
An array can hold objects too. Creating the array only creates empty slots (all null); each object must be created and stored separately:
public class ArrayOfObjects {
record Student(String name, int marks) { }
public static void main(String[] args) {
Student[] students = new Student[3]; // 3 empty slots (null), no objects yet
students[0] = new Student("Asha", 88);
students[1] = new Student("Ravi", 72);
students[2] = new Student("Meera", 95);
Student top = students[0];
for (Student s : students) {
if (s.marks() > top.marks()) top = s;
}
System.out.println("Top student: " + top.name() + " with " + top.marks());
}
}
Top student: Meera with 95
students[1].name() before it is assigned, throws NullPointerException.6. How a 1D Array Is Stored
The array variable holds a reference to an array object on the heap. For primitive types, the object contains the values themselves in one contiguous block, which makes index access very fast. For object types, it contains references to the objects, which live elsewhere on the heap.
7. Tips
- Loop with
i < arr.length, neveri <= arr.length. - Use for-each when you only read values.
- Use
Arrays.toString()to print andArrays.sort()to sort. - Return an empty array (
new int[0]) instead ofnull. - Switch to an
ArrayListwhen the number of elements changes.
8. Summary
- A 1D array is a fixed-size list of same-type values accessed by one index.
- Fill it with a loop, from user input or with an initializer list.
- Reverse, search, find maximums and count with simple loops.
- Methods receive a reference to the array, so they can modify it.
- Arrays of objects start with
nullslots that must be filled.
Related Tutorials
Frequently Asked Questions (FAQ)
Q1. What is a single-dimensional array in Java?
An array with one index, holding a linear list of values of the same type, for example int[] marks = {78, 92, 65};.
Q2. How do I declare a 1D array?
Write the type followed by [] and a name: int[] numbers;. Create it with new int[size] or initialise it with values in braces.
Q3. How do I take array input from the user?
Read the size with a Scanner, create the array, then fill it in a loop: for (int i = 0; i < n; i++) arr[i] = in.nextInt();.
Q4. How do I reverse an array in Java?
Swap elements from both ends moving toward the middle, as in the reverse() method above. For object arrays you can also use Collections.reverse(Arrays.asList(arr)).
Q5. How do I find the largest and smallest elements?
Start with the first element as both minimum and maximum, then loop and update them. With streams: Arrays.stream(arr).max() and min().
Q6. How do I search for an element?
Use a linear search loop for unsorted arrays. For sorted arrays, Arrays.binarySearch(arr, key) is much faster.
Q7. Does passing an array to a method copy it?
No. The method receives a copy of the reference, so it works on the same array. Changes to elements inside the method are visible to the caller.
Q8. Can a method return an array?
Yes. Declare the return type as an array, for example int[] evens(), and return an array of that type.
Q9. How do I create an array of objects?
Create the array (Student[] s = new Student[3];) and then create each object (s[0] = new Student(...);). The array starts with null in every slot.
Q10. How do I count how often a value appears?
Loop through the array and increase a counter for each match. To count every value at once, use a Map with merge(value, 1, Integer::sum).
Q11. How do I remove duplicates from an array?
For an int[]: Arrays.stream(arr).distinct().toArray(). For object arrays, copy them into a LinkedHashSet to keep the original order.
Q12. How do I add an element to an array?
Arrays cannot grow. Create a larger copy with Arrays.copyOf(arr, arr.length + 1) and set the last element, or use an ArrayList instead.
Q13. How do I sum the elements of an array?
Loop and add each element, or use Arrays.stream(arr).sum() for int, long and double arrays.
Q14. How do I sort an array in descending order?
For object arrays: Arrays.sort(arr, Comparator.reverseOrder()). For primitive arrays, sort ascending and then reverse, or use boxed streams.
Q15. What is the time complexity of accessing an element?
O(1). The position of any element is calculated directly from its index, so access time does not depend on the array's size.
Q16. How do I convert a 1D array to a String?
Use Arrays.toString(arr) for a list-like format, or String.join(", ", stringArray) to join strings with a separator.
Q17. Can I use var with arrays?
Yes with an explicit creation: var nums = new int[] {1, 2, 3};. A bare initializer, var nums = {1, 2, 3};, does not compile because the type cannot be inferred.
Q18. How do I check whether an array is empty?
Check arr == null || arr.length == 0. An array with length 0 has no elements; an array with null elements is not empty.
Q19. How do I copy part of an array?
Use Arrays.copyOfRange(arr, from, to), where from is inclusive and to is exclusive, or System.arraycopy() to copy into an existing array.
Q20. What is the difference between length and length()?
Arrays have a length field; strings have a length() method; collections use size().