Table of Contents
The array data structure in Java maintains a fixed-size sequential collection of items of the same type. A collection of data is stored in an array, although it is generally more convenient to conceive of an array as a collection of variables of the same type. Instead of defining individual variables such as number0, number1,…, and number99, you declare one array variable such as numbers and represent individual variables with numbers[0], numbers[1,…, numbers[99]. This article will teach you how to define array variables, build arrays, and process arrays using indexed variables.
What are Arrays In Java?Â
In Java, an array is a collection of variables with similar types that share a name. Arrays in Java behave differently from arrays in C/C++. The following are some key features concerning Java arrays. All arrays in Java are allocated dynamically. (See discussion below.) Contagious memory [consecutive memory regions] is where arrays are stored. Because arrays are objects in Java, we may use the object attribute length to determine their length. This differs from C/C++, where we use sizeof to get the length. A Java array variable may be declared similarly to other variables by adding [] after the data type. The array’s variables are sorted, each with an index starting at 0. A static field, a local variable, or a method parameter can all be utilized with a Java array.
An array’s size must be supplied as an int or short number, not as a long value. The object is the array type’s direct superclass. Every array type implements the Cloneable and java.io interfaces. Serializable. This array storage allows us to access array items at random [Support Random Access]. The array’s size cannot be changed (once initialized). On the other hand, an array reference may be used to point to another array. Depending on the specification of the array, an array can include primitives (int, char, etc.) as well as object (or non-primitive) pointers to a class. The actual values of primitive data types are stored in contiguous memory regions. The real objects of class objects are kept in a heap section.
Learn Coding in your Language! Enroll Here!
Declaring Array Variables
1: What is the default value of a boolean in Java?
To utilize an array in a program, you must define a variable to refer to the array and specify the kind of array that the variable may refer to. The syntax for defining an array variable is as follows:
Syntax
dataType[] arrayRefVar; // preferred way. or dataType arrayRefVar[]; // works but not preferred way.
Note − The style dataType[] arrayRefVar is preferred. The style dataType arrayRefVar[] comes from the C/C++ language and was adopted in Java to accommodate C/C++ programmers.
Example
The following code snippets are examples of this syntax −
double[] myList; // preferred way. or double myList[]; // works but not preferred way.
Power up your career with Entri Elevate – Full Stack Development Course!
Creating Arrays
You can make an array with the new operator and the following syntax:
Syntax
arrayRefVar = new dataType[arraySize];
The above sentence accomplishes two objectives.
It constructs an array with new dataType[arraySize].
It assigns the freshly generated array’s reference to the variable arrayRefVar.
Declaring an array variable, generating an array, and assigning the array’s reference to the variable can all be done in a single statement, as demonstrated below.
dataType[] arrayRefVar = new dataType[arraySize];
Alternatively, you can create arrays as follows −
dataType[] arrayRefVar = {value0, value1, ..., valuek};
The index is used to access the array of items. Array indices are 0-based, ranging from 0 to arrayRefVar.length-1.
Example
The following statement defines an array variable, myList, constructs a double-type array of 10 members, and assigns its reference to myList.
double[] myList = new double[10];
The image below depicts the array myList. MyList has 10 double values with indexes ranging from 0 to 9.
Power up your career with Entri Elevate – Full Stack Development Course!
Processing Arrays
Because all of the elements in an array are of the same type and the array’s size is known, we frequently use either a for loop or a foreach loop when processing array elements.
Example
Here is an example of how to construct, initialize, and handle arrays.
public class TestArray { public static void main(String[] args) { double[] myList = {1.9, 2.9, 3.4, 3.5}; // Print all the array elements for (int i = 0; i < myList.length; i++) { System.out.println(myList[i] + " "); } // Summing all elements double total = 0; for (int i = 0; i < myList.length; i++) { total += myList[i]; } System.out.println("Total is " + total); // Finding the largest element double max = myList[0]; for (int i = 1; i < myList.length; i++) { if (myList[i] > max) max = myList[i]; } System.out.println("Max is " + max); } }
This will produce the following result −
Output
1.9 2.9 3.4 3.5 Total is 11.7 Max is 3.5
Learn Coding in your Language! Enroll Here!
The foreach Loops
JDK 1.5 added a new for loop called foreach loop or extended for loop that allows you to explore the entire array sequentially without needing an index variable.
Example
The code below displays all of the elements in the array myList.
public class TestArray { public static void main(String[] args) { double[] myList = {1.9, 2.9, 3.4, 3.5}; // Print all the array elements for (double element: myList) { System.out.println(element); } } }
This will produce the following result −
Output
1.9 2.9 3.4 3.5
Passing Arrays to Methods
Arrays can be sent to methods in the same way that primitive-type values can. The following technique, for example, displays the elements of an int array.
Example
public static void printArray(int[] array) { for (int i = 0; i < array.length; i++) { System.out.print(array[i] + " "); } }
You can invoke it by passing an array. For example, the following statement invokes the printArray method to display 3, 1, 2, 6, 4, and 2 −
Example
printArray(new int[]{3, 1, 2, 6, 4, 2});
Returning an Array from a Method
An array can also be returned by a method. The following function, for example, returns an array that is the inverse of another array
Example
public static int[] reverse(int[] list) { int[] result = new int[list.length]; for (int i = 0, j = result.length - 1; i < list.length; i++, j--) { result[j] = list[i]; } return result;
Learn Coding in your Language! Enroll Here!
The Arrays Class
The static methods in the java.util.Arrays classes are used for sorting and searching arrays, comparing arrays, and filling array items. All primitive types have these methods overloaded.
public static int binarySearch(Object[] a, Object key)
The binary search algorithm is used to search the supplied array of Objects (Byte, Inte, Double, etc.) for the specified value. Prior to performing this call, the array must be sorted. If the search key is found in the list, it returns the index; otherwise, it returns (- (insertion point + 1)).
public static boolean equals(long[] a, long[] a2)
If the two supplied long arrays are equal, this function returns true. If two arrays have the same number of items and all related pairs of elements in the two arrays are equal, they are deemed equal. If the two arrays are equal, this function returns true. All other basic data types might utilize the same way (Byte, short, Int, etc.)
public static void fill(int[] a, int val)
The supplied int value is assigned to each element of the specified array of ints. All other basic data types might utilize the same way (Byte, short, Int, etc.)
public static void sort(Object[] a)
Sorts the supplied array of items in ascending order according to their natural ordering. All other basic data types might utilize the same way ( Byte, short, Int, etc.)
One-Dimensional Arrays:Â
The general form of a one-dimensional array declaration is
type var-name[]; OR type[] var-name;
An array declaration consists of two parts: the type and the name. type specifies the array’s element type. The data type of each array element is determined by the element type. We may generate an array of other primitive data types, such as char, float, double, and so on, in the same way, that we can make an array of integers (objects of a class). As a result, the array’s element type decides what type of data the array will carry.
Example:
// both are valid declarations int intArray[]; or int[] intArray; byte byteArray[]; short shortsArray[]; boolean booleanArray[]; long longArray[]; float floatArray[]; double doubleArray[]; char charArray[]; // an array of references to objects of // the class MyClass (a class created by // user) MyClass myClassArray[]; Object[] ao, // array of Object Collection[] ca; // array of Collection // of unknown type
Despite the fact that the initial declaration specifies intArray as an array variable, no real array exists. It just informs the compiler that this variable (intArray) will contain an array of integers. To connect intArray to a physical array of integers, allocate one using new and assign it to intArray.
Learn Coding in your Language! Enroll Here!
Instantiating an Array in Java
Only a reference to an array is created when it is defined. To generate or allocate memory to the array, construct an array in the following manner: The general form of new in the context of one-dimensional arrays is as follows:
var-name = new type [size]; where type defines the type of data being allocated, size provides the number of array elements, and var-name is the name of the array variable that is connected to the array. You must provide the type and number of items to allocate when using new to allocate an array.
Example:
int intArray[]; //declaring array intArray = new int[20]; // allocating memory to array
OR
int[] intArray = new int[20]; // combining both statements in one
The array items allocated by new are immediately initialized to zero (for numeric types), false (for boolean types), or null (for reference types). In Java, use the default array values.
Getting an array requires two steps. First, create a variable of the required array type. Second, you must use new to allocate memory for the array and assign it to the array variable. As a result, all arrays in Java are dynamically allocated.
Accessing Java Array Elements using for Loop
Each array entry is accessed by its index. The index ranges from 0 to (total array size)-1. Using Java for Loop, all array items may be retrieved.
// accessing the elements of the specified array for (int i = 0; i < arr.length; i++) System.out.println("Element at index " + i + " : "+ arr[i]);
Implementation:
- Java
// Java program to illustrate creating an array // of integers, puts some values in the array, // and prints each value to standard output.  class GFG {     public static void main(String[] args)     {         // declares an Array of integers.         int [] arr;          // allocating memory for 5 integers.         arr = new int [ 5 ];          // initialize the first elements of the array         arr[ 0 ] = 10 ;          // initialize the second elements of the array         arr[ 1 ] = 20 ;          // so on...         arr[ 2 ] = 30 ;         arr[ 3 ] = 40 ;         arr[ 4 ] = 50 ;          // accessing the elements of the specified array         for ( int i = 0 ; i < arr.length; i++)             System.out.println( "Element at index " + i                                + " : " + arr[i]);     } } |
Output
Element at index 0 : 10 Element at index 1 : 20 Element at index 2 : 30 Element at index 3 : 40 Element at index 4 : 50
Arrays of Objects
In the same way as an array of primitive type data items is formed, an array of objects is created in the following manner.
new student[] arr Student[7]; /student is a custom class.
The studentArray includes seven memory regions, one for each student class size, in which the addresses of seven Student objects can be placed. The Student objects must be constructed using the Student class’s function Object() { [native code] }, and their references must be allocated to the array elements in the following manner.
Example
- Java
// Java program to illustrate creating // an array of objects  class Student {     public int roll_no;     public String name;     Student( int roll_no, String name)     {         this .roll_no = roll_no;         this .name = name;     } }  // Elements of the array are objects of a class Student. public class GFG {     public static void main(String[] args)     {         // declares an Array of integers.         Student[] arr;          // allocating memory for 5 objects of type Student.         arr = new Student[ 5 ];          // initialize the first elements of the array         arr[ 0 ] = new Student( 1 , "aman" );          // initialize the second elements of the array         arr[ 1 ] = new Student( 2 , "vaibhav" );          // so on...         arr[ 2 ] = new Student( 3 , "shikar" );         arr[ 3 ] = new Student( 4 , "dharmesh" );         arr[ 4 ] = new Student( 5 , "mohit" );          // accessing the elements of the specified array         for ( int i = 0 ; i < arr.length; i++)             System.out.println( "Element at " + i + " : "                                + arr[i].roll_no + " "                                + arr[i].name);     } } |
Output
Element at 0 : 1 aman Element at 1 : 2 vaibhav Element at 2 : 3 shikar Element at 3 : 4 dharmesh Element at 4 : 5 mohit
Time Complexity: O(n)
Auxiliary Space : O(1)
Power up your career with Entri Elevate – Full Stack Development Course!
Example
An array of objects is also created like an array of primitive type data items.
Student[] studentArray; // No array created
Student[] studentArray = new Student[5]; // Array of 5 students created but No studen
The studentArray has five memory slots, one for each student class, in which the addresses of seven Student objects can be kept. The Student objects must be constructed using the Student class’s function Object() { [native code] }, and their references must be allocated to the array elements in the following manner.
// Java program to illustrate creating // an array of objects    class Student {         public String name;     Student(String name)     {         this .name = name;     }       @Override     public String toString(){         return name;     } }    // Elements of the array are objects of a class Student. public class GFG {     public static void main (String[] args)     {            // declares an Array and initializing the elements of the array         Student[] myStudents = new Student[]{ new Student( "Dharma" ), new Student( "sanvi" ), new Student( "Rupa" ), new Student( "Ajay" )}; // Array of 5 students created but No students are there in the array            // accessing the elements of the specified array         for (Student m:myStudents){                System.out.println(m);         }     } } |
Output
Dharma sanvi Rupa Ajay
Multidimensional Arrays:
Multidimensional array in java are arrays of arrays, with each array member containing the reference to another array. These are also referred to as Jagged Arrays. Appending one set of square brackets ([]) for each dimension results in a multidimensional array in java.
int[][] intArray = new int[10][20]; //a 2D array or matrix int[][][] intArray = new int[10][20][10]; //a 3D array
Example
- Java
public class multiDimensional {     public static void main(String args[])     {         // declaring and initializing 2D array         int arr[][]             = { { 2 , 7 , 9 }, { 3 , 6 , 1 }, { 7 , 4 , 2 } };          // printing 2D array         for ( int i = 0 ; i < 3 ; i++) {             for ( int j = 0 ; j < 3 ; j++)                 System.out.print(arr[i][j] + " " );              System.out.println();         }     } } |
Output
2 7 9 3 6 1 7 4 2
If you are interested to learn new coding skills, the Entri app will help you to acquire them very easily. Entri app is following a structural study plan so that the students can learn very easily. If you don’t have a coding background, it won’t be a problem. You can download the Entri app from the google play store and enroll in your favorite course.
Power up your career with Entri Elevate – Full Stack Development Course!