Java Array Tool

In Java, the array object is used to store several pieces of information. This utility sequentially assigns certain memory regions based on the array size. In Java, an array object can hold any form of primitive or non-primitive data. That is, it can hold a list of integers, strings, objects, and so on. As a result, all of the values in an array can be data of a specific datatype. In some programming languages, the index value of an array starts at 0. In Java, you can declare both single-dimensional and multi-dimensional arrays. Using an array, you may easily arrange and sort a list of data.

The biggest disadvantage of arrays is that they are fixed and cannot be modified at runtime. This article will show you how to declare, initialize, access, and modify array objects.

Advantages

Code Optimization: It optimizes the code to get and sort data quickly. As a result, we can get any data placed at an index location using random access.

Disadvantages

Size Limit: In the array, we can only store elements of a fixed size. It does not expand in size during use. In Java, a collection framework is employed to handle this problem, which grows automatically.

Array types in Java

Arrays can be divided into two types.

  • Single Dimensional Array
  • Multidimensional Array

One-dimensional Array: Syntax

datatype array_name[]; or datatype[] array_name;

Any specific datatype is specified at the time of array declaration, and the array will store data in that format.

Two-dimensional Array: Syntax

datatype array_name[][]; or datatype[][] array_name;

A two-dimensional array, like a one-dimensional array, requires the data type to be specified and two pairs of third brackets to define the declaration. Data is stored in a tabular style with a defined number of rows and columns in this sort of array.

One-dimensional Array: Declare, Initialize, and Access

In Java, the following example explains how to use several one-dimensional arrays. First, a two-element numeric array object is declared and initialized with two integer values. Next, a three-element character array object is declared, with two characters allocated to the first and third indexes. After that, a four-element string array is declared, and three values are serially allocated to the three indexes. The index is used to print the values of the integer and character arrays, and the ‘for’ loop is used to print the values of the string arrays.

// arrayOneDimensional.java

public class arrayOneDimensional {
 
	   public static void main(String[] args) {

	   //first declare an array of numeric values
	   int number_array[] = new int[2];

	   //value assignment to array
	   number_array[0] = 24;
	   number_array[1] = 36;

	   //Declare a character array
	   char character_array[] = new char[3];

	   //Assign values
	   character_array[0] = 'X';
	   character_array[1] = 'W';
	   character_array[2] = 'Z';

	   //String array declaration
	   String[] string_array = new String[6];

	   //Assign values
	   string_array[0] = "Lenovo";
	   string_array[1] = "HP";
	   string_array[2] = "Microsoft";

	  System.out.print("\nNumeric array values : "+number_array[0]+" "+number_array[1]+"\n");
	  System.out.print("Character array values : "+character_array[0]+" "+character_array[2]+"\n");
	  System.out.print("The values of string array are : ");

	   //Iterate the array using a for loop
	   for (int j = 0; j < string_array.length; j++){
		  System.out.print(string_array[j]+" ");

	  }
	}
}

The code’s output is seen in the image below. The first two arrays’ values are printed based on the index value assigned. The null value is assigned by default on the last index of the printed string array, and the last index of the third array is not assigned.

One-dimensional Array
One-dimensional Array

Create a Values Array and Sort the Array

In the previous example, the index is used to initialize the array values independently. This example demonstrates how array values can be initialized when the array is declared. In this case, the code declares an eight-element numeric array containing values. The ‘for’ loop is then used to output the values. The Java array offers a built-in sort() method to sort array values. This function sorts the array values before printing them using the ‘for’ loop once again.

// createValuesArrayAndSort.java

import java.util.Arrays;
public class array2 {

public static void main(String[] args) {

    // numeric array initialization
    int arr_vals[] = {72, 94, 25, 66, 80, 54, 41, 20};

    System.out.print("Before sorting the Array \n");

    //use a for loop to iterate through the array
    for (int j = 0; j < arr_vals.length; j++)
        System.out.print(arr_vals[j]+" ");

    // use the sort() method to sort the array
    Arrays.sort(arr_vals);

    System.out.print("\n\nAfter sorting the Array \n");

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

The code’s output is seen in the image below. The array’s contents are printed first, followed by the sorted array values shown in ascending order.

Create  and Sort the Array
Create and Sort the Array

Two-dimensional Array: Declare, Initialize, and Access

This example shows how to declare, initialize, and access a two-dimensional array using Java. To specify the array’s two dimensions, you must use two ‘[]’ brackets. The first pair of third brackets defines the row numbers, whereas the second pair of third brackets defines the column numbers.

Two methods for declaring a two-dimensional array are shown in the code. First, a two-dimensional array named score with two rows and two columns is declared. Four numeric values are later assigned in the four indices, and two are printed. Following that, a two-dimensional array named customers with four rows and three columns is declared with values.

Each value of the array is read using a ‘for’ loop. The loop will read four rows of the array and the values of each column four times, displaying the prepared result after each iteration.

// twoDimensionalArray.java


public class twoDimensionalArray {

public static void main(String[] args) {

    // two-dimensional numeric array declaration with length
    int[][] score=new int[2][2];

    //Initialize the  array with values
    score[0][0] = 991;
    score[0][1] = 600;
    score[1][0] = 992;
    score[1][1] = 800;

    // printing the array values
    System.out.print("The score of " + score[1][0] + " is " + score[1][1]);

    // two-dimensional string array declaration with values
    String customer_info[][]={{"25453","Tom Clint","Chairman"},
                         {"25368","Sam Bright","Director"},
                         {"25443","Ann Faith","GM"},
                         {"25332","Joy Brown","MD"}};  

    // using for loop to iterate through the array values
    for(int i=0; i<4; i++)
    {
        System.out.print("\nThe position of: " + customer_info[i][1]+"("+customer_info[i][0]+")" +
                    " is " + customer_info[i][2]);

    }
}
}

The code’s output is seen in the image below. The top line displays the score array’s output, while the subsequent four lines display the customer array’s result.

Two-dimensional Array
Two-dimensional Array

Java’s Jagged Array

A jagged array is created when the number of columns in a 2D array is odd. To put it another way, it’s an array of arrays with varying numbers of columns.

//JaggedArrayInJava.java
// jagged array Java Program
class JaggedArrayInJava{

  public static void main(String[] args){
//declaring a 2D array with odd columns
  
int jagged_arr[][] = new int[3][];
jagged_arr[0] = new int[3];
jagged_arr[1] = new int[4];
jagged_arr[2] = new int[2];
  
//initializing a jagged array  
    int count = 0;  
    for (int i=0; i<jagged_arr .length; i++)  
        for(int j=0; j<jagged_arr[i].length; j++)  
            arr[i][j] = count++;  

    //jagged array  data printing
    for (int i=0; i<arr.length; i++){  
        for (int j=0; j<jagged_arr[i].length; j++){  
            System.out.print(jagged_arr[i][j]+" ");  
        }  
        System.out.println();
    }  
}
}
Java's Jagged Array
Java’s Jagged Array

Cloning an array in Java

We can create a clone of the Java array because it implements the Cloneable interface. When we make a deep duplicate of a single-dimensional array, we’re making a deep copy of the Java array. It will copy the actual value. If we create the clone of a multidimensional array, it creates the shallow copy of the Java array, which means it copies the references.

// CloneArray.java
// clone the array  Java Program
class CloneArray{  
  
public static void main(String args[]){  
  
int arr_vals[]={12,89,41,98};  
System.out.println("The original array:");  

for(int i:arr_vals)  
System.out.println(i);  
  
System.out.println("The array clone:");  
int clone_arr[]=arr_vals .clone();  
for(int i:clone_arr)  
System.out.println(i);  
  
System.out.println("Are they equal to each other?");  
System.out.println(arr_vals==clone_arr);  
  
}}  
Cloning an array In Java
Cloning an array In Java

Array Copying in Java

The arraycopy() function of the System class is used to copy an array to another.

// ArrayCopyExample.java
//Java Program to copy a source array into a destination array in Java  
class ArrayCopyExample {
  
    public static void main(String[] args) {  
        // source array declaration
        char[] sourceArray = { 'c', 'o', 'd', 'e', 'u', 'n', 'd', 'e', 'r', 's', 'c', 'o', 'r', 'e', 'd' };  
       
       // destination array declaration
        char[] destinationArray = new char[9];  

        //copying array using System.arraycopy() method  
        System.arraycopy(sourceArray, 2, destinationArray, 0, 9);  

        //destination array printing
        System.out.println(String.valueOf(destinationArray));  
    }  
}  
Array Copying in Java
Array Copying in Java

Conclusion

In most cases, an array is a collection of similar-type elements stored in a single memory address. An array in Java is an object that includes components of the same data type. Furthermore, the items of an array are kept in a single memory address. It’s a data structure where we save comparable items. In a Java array, we can only store a fixed number of elements.

The array’s initial element is located at the arrays’ 0th index, and the second element is stored at the 1st index, and so on. This tutorial demonstrates the basic uses of one-dimensional and two-dimensional arrays in Java using simple examples. This tutorial will teach novice Java programmers how to utilize arrays and use them correctly in their code.

Similar Posts

Leave a Reply

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