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.