--> Arrays In Java » The Problem Solution

Arrays in Java

An array in Java is a data structure that allows you to store multiple values of the same type in a single variable. Instead of declaring separate variables for each value, you can use an array to hold all the values together, making your code more organized and efficient. Arrays are a fundamental part of Java programming and are widely used to manage and manipulate collections of data.

Array in java
  • Fixed Size: Once an array is created, its size is fixed. You cannot change the size of an array dynamically.
  • Homogeneous Elements: Arrays can only store elements of the same data type. For example, an array of integers can only store integers.
  • Indexed Access: Each element in an array is assigned a unique index, starting from 0 for the first element, which makes accessing and modifying elements easy.

To use an array, you first need to declare it, specifying the type of elements it will hold, and then allocate memory for it.

Syntax for Declaration:

dataType arrayName[];
// or
dataType[] arrayName; // Recommended

Example

int arr[];
String str[];

long[] lnr;
double[] dbr;

Initialization:

After declaring an array, you need to allocate memory using the new keyword.

arrayName = new dataType[size_of_array];

Example

arr = new int[5];
str = new String[5];

lnr = new long[5];
dbr = new double[5];

Declaration and Initialization Together:

We can declare and initialize the array in one line also.

dataType[] arrayName = new dataType[size_of_array];
//or
dataType arrayName[] = new dataType[size_of_array];

Example

int[] arr = new int[5];
String str = new String[5];

long lnr[] = new long[5];
double dbr[] = new double[5];

// we can also intialize the array in one line with their values.
int[] arr = {10, 20, 30, 40, 50};
String[] str = {"Sachin", "Dhoni", "Virat", "Rohit", "Rahul"};

long lnr[] = {1l, 2l, 3l, 4l ,5l};
double dbr[] = {1.1, 2.2, 3.3, 4.4, 5.5};

An array is an indexed-based data structure and the index of an array always starts with zero. We can access any element in an array by using its index.

public class arraysInJava {
  public static void main(String... args){
    //array declaration and intialization in one line
    int[] arr = {10, 20, 30, 40, 50};
    
    System.out.println(arr[0]);
    System.out.println(arr[2]);
    System.out.println(arr[4]);
  }
}
Output:
10
30
50

1. Single-Dimensional Arrays

A single-dimensional array (or simply a one-dimensional array) is a linear collection of elements of the same type, accessible by a single index. It is often used to store a list of items, where each item can be accessed using a specific position or index number.

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

2. Multi-Dimensional Arrays

A multi-dimensional array is an array of arrays, meaning it allows the storage of data in a matrix-like or tabular format. Each element of a multi-dimensional array is itself an array, which can also be one-dimensional or multi-dimensional. This structure can represent data in two or more dimensions. All elements in a multi-dimensional array must be of the same data type.

  • Two-Dimensional Arrays (Matrix):
public class twoDArray {
  public static void main(String... args){
  // Declaring and initializing a 3x3 two-dimensional array
   int[][] twoD= {
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9}
    };
    
    System.out.println(twoD[0][0]); // first row, first column
    System.out.println(twoD[1][1]); // second row, second column
    System.out.println(twoD[2][2]); // third row, third column
  }
}
Output:
1
5
9
  • Three-Dimensional Arrays:
public class twoDArray {
  public static void main(String... args){
    // Declaring and initializing a three-dimensional array of dimention 3x2x4.
    int[][][] threeDArray = {
      {
        {1, 2, 3, 4},
        {5, 6, 7, 8}
      },
      {
        {9, 10, 11, 12},
        {13, 14, 15, 16}
      },
      {
        {17, 18, 19, 20},
        {21, 22, 23, 24}
      }
    };
  
  System.out.println(threeDArray[0][0][0]);
  System.out.println(threeDArray[1][1][1]);
  System.out.println(threeDArray[2][1][2]);
  System.out.println(threeDArray[2][0][3]);
 }   
}
Output:
1
14
23
20

Iterating over an array in Java can be done in several ways, depending on the type of array and what you need to do with each element. Here are the most common methods to iterate over arrays in Java:

1. Iterating Over a Single-Dimensional Array

public class iterateOneDArray {
  public static void main(String... args){
    //declaration and intialization
    int[] arr = {1, 2, 3, 4, 5};
    
    //iterate using for loop
    for (int i = 0; i < arr.length; i++) {
        System.out.print(arr[i] + " - ");
    }
    
    //iterate using enhanced for each loop
    for (int a : arr) {
        System.out.print(a + " > ");
    }
    
    //iterate using while loop
    int index = 0;
    while(index < arr.length){
      System.out.print(arr[index] + " < ");
      index++;
    }
    
    //iterate using do while loop
    int ind = 0;
    do {
      System.out.print(arr[ind] + " = ");
      ind ++;
    } while(index < arr.length);
  }
}
Output:
1 - 2 - 3 - 4 - 5
1 > 2 > 3 > 4 > 5
1 < 2 < 3 < 4 < 5
1 = 2 = 3 = 4 = 5

2. Iterating Over a Two-Dimensional Array

public class iterateTwoDArray {
  public static void main(String... args){
    //declaration and intialization of 3*3 matrix
    int[][] twoD = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    };
    
    //iterate using for loop
    for (int i = 0; i < twoD.length; i++) { // Iterating over rows
      for (int j = 0; j < twoD[i].length; j++) { // Iterating over columns
          System.out.print(twoD[i][j] + ", ");
      }
    }
    
    //Using Nested for each Loops
    for (int[] row : twoD) {
      for (int element : row) {
          System.out.println(element + ", ");
      }
    }
Output:
1, 2, 3, 4, 5, 6, 7, 8, 9
1, 2, 3, 4, 5, 6, 7, 8, 9

3. Iterating Over a Three-Dimensional Array

public class iterateThreeDArray {
  public static void main(String... args){
    //declaration and intialization of 2*2*3 of 3D array
    int[][][] threeD = {
        {
            {1, 2, 3},
            {4, 5, 6}
        },
        {
            {7, 8, 9},
            {10, 11, 12}
        }
    };
    
    // iterate using for loop
    for (int i = 0; i < threeD.length; i++) { // Iterating over 2D arrays
      for (int j = 0; j < threeD[i].length; j++) { // Iterating over rows
          for (int k = 0; k < threeD[i][j].length; k++) { // Iterating over columns
              System.out.print(threeD[i][j][k] + ", ");
          }
      }
    }
    
   // iterate using Nested for each Loops
   for (int[][] matrix : threeD) {
      for (int[] row : matrix) {
          for (int element : row) {
              System.out.print(element + ", ");
          }
      }
    }
  }
}
Output:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12

4. Iterate using Java 8 Streams

int[] arr = {1, 2, 3, 4, 5};
Arrays.stream(arr).forEach(System.out::print); //12345

There are several ways to copy an array. The method you choose can depend on whether you want a shallow copy (where the new array references the same elements) or a deep copy (where the new array contains copies of the elements).

1. Using a Loop (Manual Copy)

public class copyArray1 {
  public static void main(String... args){
    int[] original = {1, 2, 3, 4, 5};
    int[] copied = new int[original.length];
    
    for (int i = 0; i < original.length; i++) {
        copied[i] = original[i];
    }
    System.out.println(Arrays.toString(original));// [1, 2, 3, 4, 5]
    System.out.println(Arrays.toString(copied));// [1, 2, 3, 4, 5]
  }
}

2. Using System.arraycopy()

public class copyArray2 {
  public static void main(String... args){
    int[] original = {1, 2, 3, 4, 5};
    int[] copied = new int[original.length];

    System.arraycopy(original, 0, copied, 0, original.length);
    
    System.out.println(Arrays.toString(original));// [1, 2, 3, 4, 5]
    System.out.println(Arrays.toString(copied));// [1, 2, 3, 4, 5]
  }
}

3. Using Arrays.copyOf()

import java.util.Arrays;

public class copyArray3 {
  public static void main(String... args){
    int[] original = {1, 2, 3, 4, 5};
    int[] copied = Arrays.copyOf(original, original.length);
    
    System.out.println(Arrays.toString(original));// [1, 2, 3, 4, 5]
    System.out.println(Arrays.toString(copied));// [1, 2, 3, 4, 5]
  }
}

4. Using clone() Method

import java.util.Arrays;

public class copyArray4 {
  public static void main(String... args){
    int[] original = {1, 2, 3, 4, 5};
    int[] copied = original.clone();
    
    System.out.println(Arrays.toString(original));// [1, 2, 3, 4, 5]
    System.out.println(Arrays.toString(copied));// [1, 2, 3, 4, 5]
  }
}

5. Using Arrays.copyOfRange()

import java.util.Arrays;

public class copyArray5 {
  public static void main(String... args){
    int[] original = {1, 2, 3, 4, 5};
    int[] copied = Arrays.copyOfRange(original, 1, 4); // copying from index 1 to 3
    
    System.out.println(Arrays.toString(original));// [1, 2, 3, 4, 5]
    System.out.println(Arrays.toString(copied));// [1, 2, 3]
  }
}

6. Using ArrayList to Copy Elements

import java.util.ArrayList;
import java.util.Arrays;
public class copyArray6 {
  public static void main(String... args){
    int[] original = {1, 2, 3, 4, 5};
    ArrayList<Integer> copiedList = new ArrayList<>();
    
    for (int num : original) {
        copiedList.add(num);
    }
    // Convert back to array if needed by using java 8 stream API
    int[] copied = copiedList.stream().mapToInt(i -> i).toArray();
    
     System.out.println(Arrays.toString(original));// [1, 2, 3, 4, 5]
    System.out.println(Arrays.toString(copied));// [1, 2, 3, 4, 5]
  }
}

We can sort an array using several built-in methods provided by the java.util.Arrays class. These methods allow you to sort arrays of different types, such as arrays of primitive data types (e.g., int, char) or arrays of objects (e.g., String, Integer).

1. Sorting an Array in Ascending Order

import java.util.Arrays;

public class sortArray1 {
    public static void main(String[] args) {
        int[] nums = {5, 2, 8, 3, 1};
        String[] names = {"Sachin", "Dhoni", "Virat", "Rohit"};
        
        Arrays.sort(nums);
        Arrays.sort(names); 
        
        System.out.println(Arrays.toString(nums)); // [1, 2, 3, 5, 8]
        System.out.println(Arrays.toString(names)); // ["Dhoni", "Rohit", "Sachin", "Virat"]
    }
}

2. Sorting an Array in Descending Order

import java.util.Arrays;

public class sortArray2 {
    public static void main(String[] args) {
        // Here we are using wrapper class because collection only supports wrapper classes
        Integer[] nums = {5, 2, 8, 3, 1};
        String[] names = {"Sachin", "Dhoni", "Virat", "Rohit"};
        
        Arrays.sort(nums, Collections.reverseOrder());
        Arrays.sort(names, Collections.reverseOrder());
        
        System.out.println(Arrays.toString(nums)); // [8, 5, 3, 2, 1]
        System.out.println(Arrays.toString(names)); // [Virat, Sachin, Rohit, Dhoni]
    }
}

3. Sorting Part of an Array

import java.util.Arrays;

public class sortArray3 {
    public static void main(String[] args) {
        int[] nums = {5, 2, 8, 3, 1, 7, 4};
        
        // sort the array from index 1 to 4 by using Arrays.sort(array, fromIndex, toIndex)
        Arrays.sort(nums, 1, 5);
        
        System.out.println(Arrays.toString(nums)); // Output: [5, 1, 2, 3, 8, 7, 4]
    }
}

4. Sorting Arrays of Custom Objects

import java.util.Arrays;
import java.util.Comparator;

class Cricket {
    String name;
    String role;
    int age;

    Person(String name, String role, int age) {
        this.name = name;
        this.role = role;
        this.age = age;
    }

    @Override
    public String toString() {
        return name + " (" + role+ ") - " + age;
    }
}

public class Main {
    public static void main(String[] args) {
        Cricket[] crick = {
            new Cricket("Dhoni", "Keeper-Batsman" + 40),
            new Cricket("Virat", "Batsman" + 36),
            new Cricket("Bumrah", "Bowler" + 30)
        };
        
        Arrays.sort(crick, Comparator.comparingInt(com -> com.age));
        
        System.out.println(Arrays.toString(crick));
        // [Bumrah (30) - Bowler, Virat (36) - Batsman, Dhoni (40) - Keeper-Batsman]
    }
}
  • Memory Efficiency: Arrays store elements in contiguous memory locations, making access fast and memory usage efficient.
  • Easy Access: Using an index, you can quickly access any element in the array.
  • Convenient Grouping: Arrays allow you to group multiple values of the same type under a single variable name, simplifying code management.
  • Fixed Size: Once defined, the size of an array cannot be changed. If you need a resizable structure, consider using collections like ArrayList.
  • Single Data Type: Arrays can only store elements of the same type, which can be a limitation if you need to store different types of data together.

What are the different types of arrays?

  • Single-Dimensional Arrays: Basic arrays with a single row of elements.
  • Multi-Dimensional Arrays: Arrays with more than one dimension, such as 2D arrays (matrices) or 3D arrays.
  • Jagged Arrays: Arrays where each element is itself an array of varying lengths.

How do arrays work in programming languages?

  • Arrays work by allocating a contiguous block of memory for storing elements of the same type. Elements are accessed using zero-based indices, allowing constant time retrieval and modification. The size of the array is typically fixed once created, though some languages offer dynamic arrays or lists with resizable capabilities.
  • Benefits such as ease of access to elements via indexing, efficient storage of data, and contiguous memory allocation.
  • Limitations include fixed size (in many languages), lack of flexibility for dynamic resizing, and the need for contiguous memory allocation.

Arrays and lists differ primarily in their structure and flexibility:

  • Arrays: Fixed-size, contiguous memory allocation, efficient access by index, but cannot easily resize after creation.
  • Lists: Dynamic size, often implemented as linked lists or dynamic arrays (e.g., ArrayList in Java), can grow or shrink as needed, but may have higher overhead for access and operations compared to arrays.

Leave a Reply

Your email address will not be published. Required fields are marked *