DevAcademia
C++C#CPythonJava
  • Java Basics

  • Java Introduction
  • Java Get Started
  • Java Syntax
  • Java Output
  • Java Comments
  • Java Variables
  • Java Data Types
  • Java Type Casting
  • Java Operators
  • Java Strings
  • Java If...Else
  • Java Switch Statement
  • Java Loops
  • Java Math
  • Java Arrays
  • Java Date
  • Java OOP

  • Java Classes/Objects
  • Java Class Attributes
  • Java Class Methods
  • Java Constructors
  • Java Destructors
  • Java this Keyword
  • Java Modifiers
  • Java Non Modifiers
  • Java Encapsulation
  • Java Packages & API
  • Java Inheritance
  • Java Polymorphism
  • Java Super Keyword
  • Java Inner Classes
  • Java Exception Handling
  • Java Abstraction
  • Java Interfaces
  • Java Enums
  • Java User Input
  • Java Quiz

  • Java Fundamentals Quiz
  • Java Basics

  • Java Introduction
  • Java Get Started
  • Java Syntax
  • Java Output
  • Java Comments
  • Java Variables
  • Java Data Types
  • Java Type Casting
  • Java Operators
  • Java Strings
  • Java If...Else
  • Java Switch Statement
  • Java Loops
  • Java Math
  • Java Arrays
  • Java Date
  • Java OOP

  • Java Classes/Objects
  • Java Class Attributes
  • Java Class Methods
  • Java Constructors
  • Java Destructors
  • Java this Keyword
  • Java Modifiers
  • Java Non Modifiers
  • Java Encapsulation
  • Java Packages & API
  • Java Inheritance
  • Java Polymorphism
  • Java Super Keyword
  • Java Inner Classes
  • Java Exception Handling
  • Java Abstraction
  • Java Interfaces
  • Java Enums
  • Java User Input
  • Java Quiz

  • Java Fundamentals Quiz

Loading Java tutorial…

Loading content
Java BasicsTopic 36 of 59
←PreviousPrevNextNext→

Java Arrays - Complete Guide

Introduction to Arrays

In Java, an array is a container object that holds a fixed number of values of a single type. Each element in an array is accessed using its index, starting from 0.

Arrays provide a convenient way to group related data, especially when the number of elements is known in advance. They are commonly used for data storage, iteration, and as the basis for more complex data structures.

Creating and Initializing Arrays

There are several ways to declare, create, and initialize arrays in Java. Choosing the correct approach depends on whether you already know the values or just the required size.

Example
public class ArrayCreation {
    public static void main(String[] args) {
        // Method 1: Declaration and then creation
        int[] numbers1;
        numbers1 = new int[5]; // Array of 5 integers, default values = 0
        
        // Method 2: Declaration and creation in one line
        int[] numbers2 = new int[5];
        
        // Method 3: Initialize directly with values
        int[] numbers3 = {1, 2, 3, 4, 5};
        
        // Method 4: Using new with values
        int[] numbers4 = new int[]{1, 2, 3, 4, 5};
        
        // Arrays of other data types
        double[] prices = new double[3];
        boolean[] flags = new boolean[3];
        char[] letters = new char[2];
        String[] names = {"Alice", "Bob", "Charlie"};
        
        // Default values
        System.out.println("Default int value: " + numbers1[0]); // 0
        System.out.println("Default double value: " + prices[0]); // 0.0
        System.out.println("Default boolean value: " + flags[0]); // false
        System.out.println("Default char value: " + (int)letters[0]); // 0 (null character)
        System.out.println("Default String value: " + names[0]); // "Alice" (explicit)
        
        // Array length
        System.out.println("Length of numbers3: " + numbers3.length);
        System.out.println("Length of names: " + names.length);
        
        // Accessing elements
        System.out.println("First element: " + numbers3[0]);
        System.out.println("Last element: " + numbers3[numbers3.length - 1]);
        
        // Modifying an element
        numbers3[0] = 10;
        System.out.println("Modified first element: " + numbers3[0]);
    }
}
Output
Default int value: 0
Default double value: 0.0
Default boolean value: false
Default char value: 0
Default String value: Alice
Length of numbers3: 5
Length of names: 3
First element: 1
Last element: 5
Modified first element: 10

Array Properties and Characteristics

Arrays in Java are fixed in size, indexed from 0, and enforce type consistency. They also perform bounds checking at runtime, preventing access to invalid indexes.

Example
public class ArrayProperties {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4, 5};
        
        // Valid access
        System.out.println("Valid access: " + numbers[2]); // 3
        
        // Invalid index
        try {
            System.out.println(numbers[10]);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Error: " + e.getMessage());
        }
        
        // Negative index
        try {
            System.out.println(numbers[-1]);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Error: " + e.getMessage());
        }
        
        // Array reference assignment
        int[] arr1 = {1, 2, 3};
        int[] arr2 = arr1;
        arr2[0] = 100;
        System.out.println("arr1[0]: " + arr1[0]); // 100
        
        // Copying arrays
        int[] original = {1, 2, 3, 4, 5};
        int[] copy = new int[original.length];
        
        for (int i = 0; i < original.length; i++) {
            copy[i] = original[i];
        }
        
        copy[0] = 999;
        System.out.println("Original[0]: " + original[0]);
        System.out.println("Copy[0]: " + copy[0]);
        
        // Using System.arraycopy
        int[] copy2 = new int[original.length];
        System.arraycopy(original, 0, copy2, 0, original.length);
        
        // Using Arrays.copyOf
        int[] copy3 = java.util.Arrays.copyOf(original, original.length);
    }
}
Output
Valid access: 3
Error: Index 10 out of bounds for length 5
Error: Index -1 out of bounds for length 5
arr1[0]: 100
Original[0]: 1
Copy[0]: 999

Common Array Operations

Some of the most common operations on arrays include searching, finding maximum and minimum values, calculating aggregates such as sum or average, reversing, and sorting.

Example
public class ArrayOperations {
    public static void main(String[] args) {
        int[] numbers = {5, 2, 8, 1, 9, 3};
        
        // Maximum
        int max = numbers[0];
        for (int num : numbers) {
            if (num > max) max = num;
        }
        System.out.println("Max: " + max);
        
        // Minimum
        int min = numbers[0];
        for (int num : numbers) {
            if (num < min) min = num;
        }
        System.out.println("Min: " + min);
        
        // Sum and average
        int sum = 0;
        for (int num : numbers) sum += num;
        double avg = (double) sum / numbers.length;
        System.out.println("Sum: " + sum);
        System.out.println("Average: " + avg);
        
        // Searching
        int searchValue = 3;
        int index = -1;
        for (int i = 0; i < numbers.length; i++) {
            if (numbers[i] == searchValue) {
                index = i;
                break;
            }
        }
        System.out.println(index >= 0 ? "Found at index " + index : "Not found");
        
        // Reversing
        for (int i = 0; i < numbers.length / 2; i++) {
            int temp = numbers[i];
            numbers[i] = numbers[numbers.length - 1 - i];
            numbers[numbers.length - 1 - i] = temp;
        }
        System.out.println("Reversed: " + java.util.Arrays.toString(numbers));
        
        // Sorting
        java.util.Arrays.sort(numbers);
        System.out.println("Sorted: " + java.util.Arrays.toString(numbers));
    }
}
Output
Max: 9
Min: 1
Sum: 28
Average: 4.666666666666667
Found at index 5
Reversed: [3, 9, 1, 8, 2, 5]
Sorted: [1, 2, 3, 5, 8, 9]

Best Practices for Working with Arrays

  • ✅ Always check array bounds to avoid ArrayIndexOutOfBoundsException
  • ✅ Use enhanced for loops when index is not needed
  • ✅ Prefer ArrayList when you need a resizable collection
  • ✅ Use Arrays.toString() for readable array output
  • ✅ Use Arrays.sort() for sorting
  • ✅ Use System.arraycopy() or Arrays.copyOf() for copying arrays
  • ✅ Initialize arrays with clear default values when possible
  • ✅ Encapsulate common array operations in helper methods
Test your knowledge: Java Arrays - Complete Guide
Quiz Configuration
4 of 10 questions
Sequential
Previous allowed
Review enabled
Early close allowed
Estimated time: 5 min
Java BasicsTopic 36 of 59
←PreviousPrevNextNext→