Table of Contents
Arrays are where Java gets real. One variable suddenly holds a whole class of marks, a list of names, an entire matrix, and every serious program you write afterwards leans on them. They are also the most heavily searched Java topic among students, for a simple reason: array questions decide marks, in ICSE, CBSE, and first-year college alike.
This page is 20 solved Java array programs for beginners, from storing your first five numbers to transposing a matrix. Every program was compiled and executed before being published, and the output under each is the real one it printed.
New to arrays entirely? Read the first section slowly, the index picture is the whole game. Preparing for boards? Jump to sorting and searching, then drill the wider families in our 50-program ICSE bank.
The One Picture Behind Every Array
An array is a fixed row of boxes, numbered from 0. The number of boxes is arr.length, the first box is arr[0], and the last is arr[length - 1]. Almost every array error in exams is a program knocking on a box that does not exist.
First Steps With Arrays
Five programs that build the reflexes: index from 0, stop at length - 1, and let the loop do the walking.
1. Store and print elements
Question: Write a program to store five numbers in an array and print them with their positions.
public class StoreAndPrint {
public static void main(String[] args) {
int[] arr = {12, 45, 7, 89, 23};
for (int i = 0; i < arr.length; i++)
System.out.println("Index " + i + " holds " + arr[i]);
}
}
Index 0 holds 12
Index 1 holds 45
Index 2 holds 7
Index 3 holds 89
Index 4 holds 23
2. Sum and average
Question: Write a program to find the sum and average of the elements of an array.
public class SumAvg {
public static void main(String[] args) {
int[] marks = {72, 85, 90, 66, 78};
int sum = 0;
for (int i = 0; i < marks.length; i++)
sum = sum + marks[i];
System.out.println("Sum = " + sum);
System.out.println("Average = " + (double) sum / marks.length);
}
}
Sum = 391
Average = 78.2
3. Count even and odd
Question: Write a program to count the even and odd numbers in an array.
public class CountEvenOdd {
public static void main(String[] args) {
int[] arr = {11, 24, 36, 41, 58, 63};
int even = 0, odd = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] % 2 == 0)
even++;
else
odd++;
}
System.out.println("Even: " + even + ", Odd: " + odd);
}
}
Even: 3, Odd: 3
4. Print in reverse order
Question: Write a program to print the elements of an array in reverse order.
public class PrintReverse {
public static void main(String[] args) {
int[] arr = {5, 10, 15, 20, 25};
for (int i = arr.length - 1; i >= 0; i--)
System.out.print(arr[i] + " ");
System.out.println();
}
}
25 20 15 10 5
5. Copy one array into another
Question: Write a program to copy the elements of one array into another and print the copy.
public class CopyArray {
public static void main(String[] args) {
int[] a = {3, 6, 9, 12};
int[] b = new int[a.length];
for (int i = 0; i < a.length; i++)
b[i] = a[i];
for (int i = 0; i < b.length; i++)
System.out.print(b[i] + " ");
System.out.println();
}
}
3 6 9 12
Searching and Extremes
Finding things is what arrays are for. Linear search reads everything; binary search halves a sorted array each step; and the largest, second largest, and frequency questions are all one careful pass.
6. Largest element
Question: Write a program to find the largest element in an array.
public class Largest {
public static void main(String[] args) {
int[] arr = {41, 78, 12, 95, 60};
int max = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] > max)
max = arr[i];
}
System.out.println("Largest = " + max);
}
}
Largest = 95
7. Second largest element
Question: Write a program to find the second largest element in an array.
public class SecondLargest {
public static void main(String[] args) {
int[] arr = {41, 78, 12, 95, 60};
int max = Integer.MIN_VALUE, second = Integer.MIN_VALUE;
for (int i = 0; i < arr.length; i++) {
if (arr[i] > max) {
second = max;
max = arr[i];
} else if (arr[i] > second && arr[i] != max) {
second = arr[i];
}
}
System.out.println("Second largest = " + second);
}
}
Second largest = 78
8. Linear search
Question: Write a program to search for a value in an array using linear search.
public class LinSearch {
public static void main(String[] args) {
int[] arr = {18, 32, 7, 54, 21};
int key = 54, pos = -1;
for (int i = 0; i < arr.length; i++) {
if (arr[i] == key) {
pos = i;
break;
}
}
if (pos == -1)
System.out.println(key + " not found");
else
System.out.println(key + " found at index " + pos);
}
}
54 found at index 3
9. Binary search
Question: Write a program to search a sorted array using binary search, printing the steps.
public class BinSearch {
public static void main(String[] args) {
int[] arr = {6, 14, 27, 39, 51, 68, 80};
int key = 51, low = 0, high = arr.length - 1, pos = -1;
while (low <= high) {
int mid = (low + high) / 2;
System.out.println("Checking index " + mid + " (value " + arr[mid] + ")");
if (arr[mid] == key) {
pos = mid;
break;
} else if (arr[mid] < key)
low = mid + 1;
else
high = mid - 1;
}
System.out.println(key + " found at index " + pos);
}
}
Checking index 3 (value 39)
Checking index 5 (value 68)
Checking index 4 (value 51)
51 found at index 4
10. Frequency of a value
Question: Write a program to count how many times a value occurs in an array.
public class CountOccur {
public static void main(String[] args) {
int[] arr = {4, 7, 4, 9, 4, 2, 7};
int key = 4, count = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] == key)
count++;
}
System.out.println(key + " occurs " + count + " times");
}
}
4 occurs 3 times
Sorting and Rearranging
The syllabus names bubble sort and selection sort, and examiners like flipping the order to descending to check you understand rather than memorise. Reversing in place and merging round out the family.
11. Bubble sort, ascending
Question: Write a program to sort an array in ascending order using bubble sort.
import java.util.Arrays;
public class Bubble {
public static void main(String[] args) {
int[] arr = {52, 17, 88, 4, 36};
for (int i = 0; i < arr.length - 1; i++) {
for (int j = 0; j < arr.length - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
int t = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = t;
}
}
}
System.out.println(Arrays.toString(arr));
}
}
[4, 17, 36, 52, 88]
12. Selection sort, descending
Question: Write a program to sort an array in descending order using selection sort.
import java.util.Arrays;
public class Selection {
public static void main(String[] args) {
int[] arr = {23, 61, 9, 47, 30};
for (int i = 0; i < arr.length - 1; i++) {
int maxIndex = i;
for (int j = i + 1; j < arr.length; j++) {
if (arr[j] > arr[maxIndex])
maxIndex = j;
}
int t = arr[i];
arr[i] = arr[maxIndex];
arr[maxIndex] = t;
}
System.out.println(Arrays.toString(arr));
}
}
[61, 47, 30, 23, 9]
13. Reverse the array itself
Question: Write a program to reverse an array in place by swapping ends toward the middle.
import java.util.Arrays;
public class ReverseInPlace {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5, 6};
int i = 0, j = arr.length - 1;
while (i < j) {
int t = arr[i];
arr[i] = arr[j];
arr[j] = t;
i++;
j--;
}
System.out.println(Arrays.toString(arr));
}
}
[6, 5, 4, 3, 2, 1]
14. Merge two arrays
Question: Write a program to merge two arrays into a third and print it.
import java.util.Arrays;
public class MergeTwo {
public static void main(String[] args) {
int[] a = {2, 4, 6};
int[] b = {1, 3, 5, 7};
int[] c = new int[a.length + b.length];
for (int i = 0; i < a.length; i++)
c[i] = a[i];
for (int i = 0; i < b.length; i++)
c[a.length + i] = b[i];
System.out.println(Arrays.toString(c));
}
}
[2, 4, 6, 1, 3, 5, 7]
15. Separate even and odd into two arrays
Question: Write a program to copy the even and odd numbers of an array into two separate arrays.
public class SeparateEvenOdd {
public static void main(String[] args) {
int[] arr = {12, 5, 8, 21, 34, 9};
int e = 0, o = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] % 2 == 0) e++; else o++;
}
int[] even = new int[e];
int[] odd = new int[o];
e = 0; o = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] % 2 == 0)
even[e++] = arr[i];
else
odd[o++] = arr[i];
}
System.out.print("Even: ");
for (int i = 0; i < even.length; i++) System.out.print(even[i] + " ");
System.out.print("\nOdd : ");
for (int i = 0; i < odd.length; i++) System.out.print(odd[i] + " ");
System.out.println();
}
}
Even: 12 8 34
Odd : 5 21 9
String Arrays and Two Dimensions
Arrays hold more than numbers. String arrays bring compareTo into play, and double dimensional arrays add the row-and-column questions: printing, diagonals, and the transpose.
16. Longest name in a String array
Question: Write a program to find the longest name stored in a String array.
public class LongestName {
public static void main(String[] args) {
String[] names = {"Asha", "Balasubramaniam", "Meera", "Zoya"};
String longest = names[0];
for (int i = 1; i < names.length; i++) {
if (names[i].length() > longest.length())
longest = names[i];
}
System.out.println("Longest name: " + longest);
}
}
Longest name: Balasubramaniam
17. Sort names alphabetically
Question: Write a program to arrange a String array in alphabetical order using compareTo.
public class AlphaSortNames {
public static void main(String[] args) {
String[] names = {"Rohan", "Asha", "Zoya", "Meera"};
for (int i = 0; i < names.length - 1; i++) {
for (int j = 0; j < names.length - 1 - i; j++) {
if (names[j].compareTo(names[j + 1]) > 0) {
String t = names[j];
names[j] = names[j + 1];
names[j + 1] = t;
}
}
}
for (int i = 0; i < names.length; i++)
System.out.println(names[i]);
}
}
Asha
Meera
Rohan
Zoya
18. Create and print a 2D array
Question: Write a program to store numbers in a 3 by 3 double dimensional array and print them row by row.
public class Matrix2D {
public static void main(String[] args) {
int[][] m = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++)
System.out.print(m[i][j] + " ");
System.out.println();
}
}
}
1 2 3
4 5 6
7 8 9
19. Sum of the diagonal
Question: Write a program to find the sum of the left diagonal of a square matrix.
public class DiagonalSum {
public static void main(String[] args) {
int[][] m = {
{5, 1, 3},
{2, 8, 4},
{6, 7, 9}
};
int sum = 0;
for (int i = 0; i < 3; i++)
sum = sum + m[i][i];
System.out.println("Diagonal sum = " + sum);
}
}
Diagonal sum = 22
20. Transpose of a matrix
Question: Write a program to print the transpose of a 3 by 3 matrix, turning rows into columns.
public class Transpose {
public static void main(String[] args) {
int[][] m = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
for (int j = 0; j < 3; j++) {
for (int i = 0; i < 3; i++)
System.out.print(m[i][j] + " ");
System.out.println();
}
}
}
1 4 7
2 5 8
3 6 9
The Errors That Follow Beginners Around
- Walking one step too far: i <= arr.length visits a box that does not exist. The last index is length - 1, so the condition is i < arr.length.
- length vs length(): arrays use the field arr.length with no brackets; strings use the method s.length() with brackets. Mixing them up is a compile error.
- Integer division in averages: sum / count truncates when both are int. Cast one side: (double) sum / count.
- Forgetting binary search needs sorted data: on an unsorted array it returns nonsense without any error to warn you.
- Swapping without a temp variable: a[i] = a[j]; a[j] = a[i]; destroys one value. The three-line temp swap is the pattern.
The dry-run habit
For every sorting question, trace one full pass on paper with five numbers before writing code. Examiners often ask for the array's state after each pass, and students who dry-run collect those marks in seconds.
Frequently Asked Questions
A fixed-size collection of values of one type, stored in numbered boxes starting from index 0. You declare the size once, reach any box instantly with arr[i], and get the box count from arr.length.
The index measures the offset from the start of the array, and the first element sits at offset zero. Practically, remember the pair: first element arr[0], last element arr[arr.length - 1].
Arrays expose a field: arr.length, no brackets. Strings expose a method: s.length(), with brackets. Java refuses to compile the wrong one, which at least makes this mistake loud.
Linear search checks every element from the start and works on any array. Binary search repeatedly halves a SORTED array, making it far faster on large data. If the array is not sorted, binary search silently gives wrong answers.
Bubble sort and selection sort, on single dimensional arrays, sometimes in descending order to test understanding. Both appear above with executed output, and the ICSE bank drills them further.
An array of arrays, written int[][], that behaves like a grid with rows and columns. You reach a cell with m[row][col], and the classic questions are row-by-row printing, diagonal sums, and the transpose.
Keep every index between 0 and length - 1. In practice that means loop conditions of i < arr.length, never i <= arr.length, and checking positions arithmetic like mid, i + 1, or i - 1 near the edges.
Twenty Programs, One Reflex
Everything above compresses to one reflex: see the boxes, respect the edges, and let the loop walk. From here, the natural next steps are the string handling guide, since string arrays combine both topics, and the full 50-program ICSE bank if boards are coming.
And when you want someone to watch your loops walk and catch the off-by-one before the examiner does, our live Java classes for beginners do exactly that, with courses for learners aged 6 to 67.