In Java, the array object is used to store multiple pieces of information. This utility assigns certain memory areas sequentially based on the size of the array. In Java, an array object can hold any form of primitive or non-primitive data. That is, it can contain a list of integers, strings, objects and so on. As a result, all values in an array can be data of a specific data type. In some programming languages, the index value of an array starts at 0. In Java, one-dimensional arrays can be declared as well as multi-dimensional arrays. Using an array, you can easily arrange and sort a list of data.
The biggest disadvantage of arrays is that they are fixed and cannot be changed while running. This article will show you how to declare, initialize, access and modify array objects.
Code optimization: It optimizes the code to get and sort data quickly. As a result, we can get all data located in an index position using random access.
Size limit: In an array, we can only store fixed size elements. It does not expand in size during use. In Java, a collection framework is used to address this problem, which has grown automatically.
Types of arrays in Java
Arrays can be divided into two types.
- A one-dimensional array
- Multidimensional array
One-dimensional array: syntax
datatype array_name; or datatype array_name;
Each specific data type is specified at the time of the array statement, and the array will store data in this format.
Two-dimensional array: syntax
datatype array_name; or datatype array_name;
A two-dimensional array, like a one-dimensional array, requires specifying the data type and two pairs of third parentheses to define the statement. The data is stored in a tabular style with a defined number of rows and columns in this type of array.
One-dimensional array: announcement, boot and access
In Java, the following example explains how to use multiple one-dimensional arrays. First, a two-element numeric array object is declared and initialized with two integer values. Next, a three-element character set object is declared, with two characters assigned to the first and third indexes. Next, a string set of four elements is declared, and three values are sequentially assigned to the three indexes. The index is used to print the values of the integer and character sets, 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; //value assignment to array number_array = 24; number_array = 36; //Declare a character array char character_array = new char; //Assign values character_array = 'X'; character_array = 'W'; character_array = 'Z'; //String array declaration String string_array = new String; //Assign values string_array = "Lenovo"; string_array = "HP"; string_array = "Microsoft"; System.out.print("nNumeric array values : "+number_array+" "+number_array+"n"); System.out.print("Character array values : "+character_array+" "+character_array+"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 output of the code is shown in the image below. The values of the first two arrays are printed based on the assigned index value. The null value is assigned by default in the last index of the printed string array, and the last index of the third array is not assigned.
Create an array of values and sort the array
In the previous example, the index is used to initialize the array values independently. This example demonstrates how to initialize array values when the array is declared. In this case, the code declares an eight-element numeric array containing values. Then, the ‘for’ loop is used to output the values. The Java array offers a built-in sort () method for sorting array values. This function sorts the array values before printing using the ‘for’ loop once more.
// 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("nnAfter sorting the Array n"); for (int j = 0; j < arr_vals.length; i++) System.out.print(arr_vals[j]+" ");
The output of the code is shown in the image below. The contents of the array are printed first, followed by the sorted array values displayed in ascending order.
Two-dimensional array: announcement, boot and access
This example shows how to declare, initialize, and access a two-dimensional array using Java. To specify the two dimensions of the array, you must use two ‘’In parentheses. The first pair of third parentheses defines the row numbers, while the second pair of third parentheses defines the column numbers.
Two methods for declaring a two-dimensional array are shown in the code. First, a two-dimensional array called a score with two rows and two columns is declared. Four numerical values are later assigned to the four indices, and two are printed. Then, a two-dimensional array called clients with four rows and three columns is declared with values.
Each value of the array is called using a ‘for’ loop. The loop will read four rows of the array and the values of each column four times, and will display 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; //Initialize the array with values score = 991; score = 600; score = 992; score = 800; // printing the array values System.out.print("The score of " + score + " is " + score); // 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]+"("+customer_info[i]+")" + " is " + customer_info[i]);
The output of the code is shown in the image below. The top line shows the output of the score set, while the next four lines show the result of the customer set.
Java serrated array
A serrated array is created when the number of columns in a two-dimensional array is odd. In other words, it is an array of arrays with a variable number 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; jagged_arr = new int; jagged_arr = new int; jagged_arr = new int; //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();
Array cloning in Java
We can create a clone of a Java array because it implements the Cloneable interface. When we create a deep duplication of a one-dimensional array, we create a deep copy of a Java array. This will copy the true value. If we create the clone of a multidimensional array, it creates the shallow copy of the Java array, which means that 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);
Copy an array in Java
The arraycopy () function of the System class is used to copy an array after.
// 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; //copying array using System.arraycopy() method System.arraycopy(sourceArray, 2, destinationArray, 0, 9); //destination array printing System.out.println(String.valueOf(destinationArray));
In most cases, an array is a collection of similar elements stored in a single memory address. An array in Java is an object that includes elements of the same type of data. Furthermore, the array items are stored in a single memory address. This is a data structure where we store similar items. In a Java array, we can only store a fixed number of elements.
The primary element of the array is located in the 0th index of the arrays, and the second element is stored in the first index, and so on. This guide demonstrates the basic uses of one-dimensional and two-dimensional arrays in Java using simple examples. This tutorial will teach beginner Java programmers how to use arrays and use them correctly in their code.