Java Tutorial

Operators

Flow Control

String

Number and Date

Built-in Classes

Array

Class and Object

Inheritance and Polymorphism

Exception Handling

Collections, Generics and Enumerations

Reflection

Input/Output Stream

Annotation

Java Arrays: What Is An Array?

In this tutorial, we will discuss arrays in Java. Arrays are fixed-size, homogeneous data structures that can store multiple values of the same data type.

  • Declare and Initialize an Array:

To declare an array, you must specify its data type, followed by square brackets, and then the name of the array. To initialize an array, you can either use the new keyword or directly assign values using curly braces.

// Declare an int array
int[] intArray;

// Initialize the array with the new keyword
intArray = new int[5]; // Array of size 5

// Declare and initialize an array directly with values
int[] intArray2 = {1, 2, 3, 4, 5};
  • Access Array Elements:

You can access array elements using their index, which starts from 0.

int[] intArray = {1, 2, 3, 4, 5};
int firstElement = intArray[0]; // firstElement = 1
int thirdElement = intArray[2]; // thirdElement = 3

// Modify an element
intArray[1] = 10; // intArray becomes {1, 10, 3, 4, 5}
  • Loop Through an Array:

You can use a for loop or a for-each loop to iterate through the elements of an array.

int[] intArray = {1, 2, 3, 4, 5};

// Using a for loop
for (int i = 0; i < intArray.length; i++) {
    System.out.println(intArray[i]);
}

// Using a for-each loop
for (int element : intArray) {
    System.out.println(element);
}
  • Multidimensional Arrays:

Java supports multidimensional arrays, usually represented as arrays of arrays.

// Declare and initialize a 2D array
int[][] matrix = {
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9}
};

// Access an element
int element = matrix[1][2]; // element = 6

// Iterate through a 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();
}
  • Array Manipulation:

Java provides the java.util.Arrays class, which contains useful methods for array manipulation, such as sorting, searching, and comparing arrays.

import java.util.Arrays;

int[] intArray = {5, 3, 1, 4, 2};

// Sort the array
Arrays.sort(intArray); // intArray becomes {1, 2, 3, 4, 5}

// Search for an element (binary search)
int index = Arrays.binarySearch(intArray, 4); // index = 3

// Compare two arrays
int[] array1 = {1, 2, 3};
int[] array2 = {1, 2, 3};
boolean isEqual = Arrays.equals(array1, array2); // isEqual = true

Remember that arrays in Java are objects, and their reference is passed when used as a method argument. If you modify the array inside the method, the original array will also be modified.

  1. Declaring Arrays in Java: Arrays in Java can be declared using the square brackets notation.

    int[] numbers;
    
  2. Initializing Arrays in Java: Arrays can be initialized at the time of declaration or later using the new keyword.

    int[] numbers = {1, 2, 3, 4, 5};
    
  3. Accessing Elements in Java Arrays: Elements in an array can be accessed using their index.

    int thirdElement = numbers[2]; // Accessing the third element (index 2)
    
  4. Java Array Length and Size: The length of an array can be obtained using the length property.

    int arrayLength = numbers.length;
    
  5. Multidimensional Arrays in Java: Arrays can have multiple dimensions.

    int[][] matrix = {{1, 2}, {3, 4}};
    
  6. Java Arrays vs. ArrayList: Arrays have a fixed size, while ArrayList is dynamic and provides additional methods for manipulation.

    int[] array = {1, 2, 3};
    ArrayList<Integer> arrayList = new ArrayList<>(Arrays.asList(1, 2, 3));
    
  7. Copying Arrays in Java: Arrays can be copied using methods like System.arraycopy or Arrays.copyOf.

    int[] copy = Arrays.copyOf(numbers, numbers.length);
    
  8. Sorting Arrays in Java: Arrays can be sorted using the Arrays.sort method.

    Arrays.sort(numbers);
    
  9. Searching in Arrays with Java: Arrays can be searched using methods like Arrays.binarySearch.

    int index = Arrays.binarySearch(numbers, 3);
    
  10. Dynamic Arrays in Java: While arrays have a fixed size, dynamic behavior can be achieved using ArrayList or other dynamic data structures.

    ArrayList<Integer> dynamicArray = new ArrayList<>();
    
  11. Java Arrays and Loops: Loops can be used to iterate through array elements.

    for (int i = 0; i < numbers.length; i++) {
        System.out.println(numbers[i]);
    }
    
  12. Java Arrays and Enhanced For Loop: Enhanced for loop simplifies array iteration.

    for (int num : numbers) {
        System.out.println(num);
    }
    
  13. Java Arrays and Varargs: Varargs allow a variable number of arguments in a method.

    public void printNumbers(int... nums) {
        for (int num : nums) {
            System.out.println(num);
        }
    }
    
  14. Java Arrays and Method Arguments: Arrays can be passed as arguments to methods.

    public void processArray(int[] array) {
        // Code to process the array
    }
    
  15. Common Pitfalls with Java Arrays: Be cautious of issues like index out of bounds and null pointer exceptions.

    int[] arr = new int[5];
    int value = arr[5]; // Index out of bounds
    
  16. Null in Java Arrays: Arrays can contain null values.

    String[] names = new String[3];
    names[0] = "John";
    names[1] = null;
    
  17. Array Manipulation in Java: Various array manipulation techniques include adding, removing, and updating elements.

    // Adding an element
    numbers = Arrays.copyOf(numbers, numbers.length + 1);
    numbers[numbers.length - 1] = 6;
    
    // Removing an element (by creating a new array)
    numbers = Arrays.copyOfRange(numbers, 0, numbers.length - 1);
    
    // Updating an element
    numbers[2] = 100;