How to Use Arrays in Java (with Code Examples for Beginners)

Arrays in Java

Why You Should Master Arrays in Java

If you’re learning Java, one of the first real challenges you’ll face is understanding arrays. Arrays are more than just a collection of variables—they’re the foundation of efficient data handling in your applications.

Whether you’re building games, banking systems, or web apps, knowing how to use arrays in Java will unlock a new level of problem-solving power. So, let’s break it all down in plain English—with code examples, tips, and common pitfalls. If you are new to Java first learn How to Write Your First Java Program in 5 Minutes ?

What are arrays in Java?

An array in Java is a data structure that stores multiple values of the same type in a single variable.

Imagine you’re storing marks for 5 students. Instead of creating five separate variables, you can store them in one array.

int[] marks = {85, 90, 78, 92, 88};

Simple, right?

Why Are Arrays Important?

  • They make your code cleaner and more scalable
  • Arrays are indexed, making data retrieval super fast
  • You can loop through them, sort them, and manipulate them with ease

How to Declare Arrays in Java

In Java, there are two ways to declare arrays:

// Option 1: Declaration first
int[] numbers;
String[] names;

// Option 2: Declaration with initialization
int[] scores = new int[5]; // Array of 5 integers

You can also declare arrays using square brackets after the variable:

int numbers[];  // Valid but less preferred

Best Practice: Always use the int[] numbers format for readability.

How to Initialize Arrays in Java | How do you define an Array?

There are multiple ways to initialize arrays.

1. Static Initialization

This is when you already know the values:

String[] colors = {"Red", "Green", "Blue"};

2. Dynamic Initialization

When you don’t know the values yet:

int[] ages = new int[3];
ages[0] = 20;
ages[1] = 25;
ages[2] = 30;

Remember: Array indices start at 0.

Accessing Elements in an Array

You can access or update array elements using their index.

System.out.println(ages[1]);  // Output: 25
ages[1] = 26; // Updates value at index 1

If you try to access an index out of range, Java throws an:

ArrayIndexOutOfBoundsException

Looping Through Arrays in Java

Let’s look at different ways to iterate through arrays.

1. Using a for loop

int[] nums = {10, 20, 30, 40, 50};

for (int i = 0; i < nums.length; i++) {
System.out.println(nums[i]);
}

2. Using a for-each loop

for (int num : nums) {
System.out.println(num);
}

Best for readability when you don’t need the index.

Multi-Dimensional Arrays

Java also supports 2D arrays—basically arrays inside arrays.

Example: 2D Arrays in Java

int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

Accessing values:

System.out.println(matrix[0][2]); // Output: 3

Nested loop to print 2D array:

for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}

Common Array Operations in Java

1. Sorting an Array

import java.util.Arrays;

int[] data = {4, 1, 7, 2};
Arrays.sort(data);

System.out.println(Arrays.toString(data)); // [1, 2, 4, 7]

2. Copying an Array

int[] copy = Arrays.copyOf(data, data.length);

3. Searching in an Array

int index = Arrays.binarySearch(data, 4); // Make sure array is sorted!

Common Mistakes with Arrays in Java

Accessing index out of range

int[] nums = new int[3];
System.out.println(nums[5]); // Throws exception

Mixing up length and indices

Remember:

  • nums.length gives you the total number of elements.
  • Indexing starts at 0, ends at length - 1.

When Should You Use Arrays?

Use Arrays when:

  • You have fixed-size collections
  • You want fast access to elements
  • Memory efficiency is a priority

If your collection size changes frequently, consider ArrayList instead.

Arrays in Java programs: Finding the Average of Student Marks

public class AverageMarks {
public static void main(String[] args) {
int[] marks = {80, 85, 90, 95, 100};
int sum = 0;

for (int mark : marks) {
sum += mark;
}

double average = (double) sum / marks.length;
System.out.println("Average marks = " + average);
}
}

✅ Output:

Average marks = 90.0

Advanced Tip: Using Arrays with Functions

You can pass arrays as arguments to methods:

public static void printArray(int[] arr) {
for (int num : arr) {
System.out.print(num + " ");
}
}

And call it like this:

int[] numbers = {1, 2, 3, 4};
printArray(numbers);

Should You Use Arrays or ArrayList?

FeatureArraysArrayList
Fixed Size✅ Yes❌ No
Memory Usage✅ Less❌ More
Built-in Methods❌ Few✅ Many
Performance✅ Faster❌ Slightly Slower

So, use Arrays when size is known and performance matters.

FAQ’s on Arrays: Interview Questions

1. What is an array in Java? How is it different from other data structures?

An array in Java is like a row of mailboxes—you get a fixed number of boxes, each of which holds a value of the same data type. It’s different from structures like ArrayLists or HashMaps because it has a fixed size and doesn’t come with built-in resizing or advanced features.

2. How do you declare and initialize an array in Java?

You can declare an array like this:

int[] numbers;

Then initialize it with:

numbers = new int[5];

Or you can do both at once:

int[] numbers = {10, 20, 30, 40, 50};

3. What is the default value of elements in an array?

Java is kind enough to initialize array elements for you. Numbers default to 0, booleans to false, and objects (like Strings) to null.

4. How do you find the length of an array in Java?

Just use the .length property. For example:

int size = numbers.length;

This gives you the total number of elements.

5. Can you change the size of an array once it is created? Why or why not?

Nope, arrays in Java are like concrete blocks—once the size is set, it’s fixed. To have a dynamic size, you’d want to use ArrayList.

6. What are the different types of arrays in Java?

You’ve got:

  • Single-dimensional arrays: like a simple list.
  • Multi-dimensional arrays: think of them as arrays within arrays. Most common is the 2D array.

7. How do you iterate over an array in Java?

You can use:

  • for loop:
for (int i = 0; i < arr.length; i++) {
    System.out.println(arr[i]);
}
  • for-each loop:
for (int value : arr) {
    System.out.println(value);
}

8. How do you copy one array into another in Java?

Use Arrays.copyOf():

int[] newArr = Arrays.copyOf(original, original.length);

9. What is Arrays.toString() and how is it used?

It gives you a readable version of your array:

System.out.println(Arrays.toString(arr));

Without this, printing an array gives a weird memory reference.

10. How do you sort an array in Java?

Just call:

Arrays.sort(arr);

It sorts numbers in ascending order by default.

11. How do you find the largest/smallest element in an array?

Loop through it and track the max or min:

int max = arr[0];
for (int i : arr) {
    if (i > max) max = i;
}

12. How can you remove duplicates from an array?

You can use a Set:

Set<Integer> set = new HashSet<>(Arrays.asList(arr));

Or use a loop with a temp array if Sets aren’t allowed.

13. How do you reverse an array in Java?

Swap elements from both ends:

for (int i = 0; i < arr.length / 2; i++) {
    int temp = arr[i];
    arr[i] = arr[arr.length - 1 - i];
    arr[arr.length - 1 - i] = temp;
}

14. Write a program to find the second largest number in an array.

int first = Integer.MIN_VALUE;
int second = Integer.MIN_VALUE;
for (int n : arr) {
    if (n > first) {
        second = first;
        first = n;
    } else if (n > second && n != first) {
        second = n;
    }
}

15. How do you perform a binary search on an array?

First, sort the array. Then:

int index = Arrays.binarySearch(arr, key);

It returns the index or a negative value if not found.

16. What is a 2D array in Java?

A 2D array is like a table with rows and columns:

int[][] matrix = new int[3][3];

Think of it as an array of arrays.

17. How do you declare and initialize a 2D array?

int[][] matrix = {
  {1, 2, 3},
  {4, 5, 6},
  {7, 8, 9}
};

18. How do you traverse a 2D array?

Use nested loops:

for (int i = 0; i < matrix.length; i++) {
    for (int j = 0; j < matrix[i].length; j++) {
        System.out.print(matrix[i][j] + " ");
    }
    System.out.println();
}

19. Write a program to find the sum of all elements in a 2D array.

int sum = 0;
for (int[] row : matrix) {
    for (int val : row) {
        sum += val;
    }
}
System.out.println("Total: " + sum);

20. What are the limitations of arrays in Java?

  • Fixed size
  • Same data type only
  • No built-in methods like dynamic collections (ArrayList, etc.)

21. How is ArrayList different from an array?

ArrayList is flexible and resizable. Arrays are fixed in size and simpler. Choose ArrayList when the number of elements can change.

22. Can you store different data types in an array?

Not in a standard typed array. But you could use Object[] if needed—though it’s usually not recommended unless absolutely necessary.

23. Explain shallow copy vs. deep copy in the context of arrays.

  • Shallow copy: Copies references (changes affect both arrays)
  • Deep copy: Copies values (changes don’t affect the original)

24. How do you merge two sorted arrays into a single sorted array?

Use a merge technique (like in merge sort):

int[] merged = new int[arr1.length + arr2.length];
// Fill in values by comparing elements of both arrays one by one

Or use System.arraycopy + Arrays.sort() if performance isn’t critical.

25. What are array types?

Arrays in Java are primarily categorized into two types: single-dimensional and multi-dimensional. A single-dimensional array holds a series of elements in a straight line, all of the same data type. In contrast, a multi-dimensional array (like 2D or 3D arrays) organizes data in rows and columns, allowing you to work with complex, grid-like structures where each element is accessed using multiple indices.

26. When to use arrays?

You should use arrays in Java when:

  • You need to store multiple values of the same data type (like a list of integers or strings).
  • The number of elements is known and fixed at the time of creation.
  • You want fast access to elements using an index.
  • Memory efficiency matters more than flexibility.

Arrays are ideal for things like storing test scores, processing large datasets, or implementing basic algorithms like sorting and searching. If you need a dynamic or flexible collection, consider using ArrayList instead.

Conclusion: Arrays Are Your Java Superpower

By now, you should feel confident using arrays in Java. From declaration and initialization to looping and sorting, you’ve covered it all with real, runnable examples.

Arrays help you write faster, cleaner, and more scalable code—so keep practicing and try creating your own array-based mini-projects!

Want to go further? Try implementing:

  • Bubble Sort using arrays
  • Finding duplicate elements
  • Reversing an array without extra space

Download Java and Learn Arrays.

Also Read :