Creating, Initializing, and Accessing an Array
One-Dimensional Arrays
Syntax to Declare an Array in Java
datatype var-name[];
OR
datatype[] var-name;
Instantiation of an Array in Java
Only a reference to an array is created when it is declared. To generate or allocate memory to the array, construct an array in the following manner: In the case of one-dimensional arrays, the general form of new is as follows:
var-name = new datatype [size];
Example:
int intArr[]; //declaration
intArr = new int[20]; // memory allocation
OR
int[] intArr = new int[20]; // combining both statements in one
Creating an array is a two-step procedure. 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.
Array Literal
Array literals can be used in situations where the array's size and variables are already known.
int[] arr = new int[]{ 10,20,30,40,50,60,70,80,90,100 };
// Declaring the array literal
Accessing Java Array Elements using for Loop
The index of each element in the array is used to access it. The index ranges from 0 to (total array size)-1. Using Java for Loop, you may access all of the array's items.
// 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 program to illustrate creating an array of integers, initializing it, and printing each value to standard output.
public class Test
{
public static void main (String[] args)
{
// declaration
int[] a;
//Memory allocation
a = new int[3];
// initializing the first element of the array
a[0] = 10;
// initializing the second element of the array
a[1] = 20;
//so on...
a[2] = 30;
// accessing the elements of the array
for(int i = 0; i<a.length; i++)
System.out.println("Array Element at index " + i +" : "+ a[i]);
}
}
You can also try this code with Online Java Compiler
Run Code
Output
Array Element at index 0: 10
Array Element at index 1: 20
Array Element at index 2: 30
You can also read about the topic of Java Destructor and Hashcode Method in Java.
Arrays of Objects
An array of objects is created in the same way as a primitive type data item array is created.
Employee[] arr = new Employee[7]; //Employee is a user-defined class
The employee Array has seven memory slots, one for each Employee class, in which the addresses of seven Employee objects can be placed. The Employee objects must be constructed using the Employee class's function constructor, and their references must be allocated to the array elements in the following manner.
Employee[] arr = new Employee[5];
Example
class Employee
{
public int emp_id;
public String emp_name;
Employee(int emp_id, String emp_name)
{
this.emp_id = emp_id;
this.emp_name = emp_name;
}
} //Array elements are objects of class Employee
public class Test
{
public static void main (String[] args)
{
Employee[] arr;//creation
arr = new Employee[5];//memory allocation
arr[0] = new Employee(1,"emp1");//declaration
arr[1] = new Employee(2,"emp2");
arr[2] = new Employee(3,"emp3");
arr[3] = new Employee(4,"emp4");
arr[4] = new Employee(5,"emp5");
for (int i = 0; i < arr.length; i++)
System.out.println("Element at " + i + " : " + arr[i].emp_id +" "+ arr[i].emp_name);
}
}
You can also try this code with Online Java Compiler
Run Code
Output
Element at 0: 1 emp1
Element at 1: 2 emp2
Element at 2: 3 emp3
Element at 3: 4 emp4
Element at 4: 5 emp5
ArrayIndexOutOfBoundsException
When traversing an array, the Java Virtual Machine (JVM) raises an ArrayIndexOutOfBoundsException if the length of the array is negative, equal to, or larger than the array size.
Example
public class Test{
public static void main(String args[]){
int arr[]={60,70,80,90};
for(int i=0;i<=arr.length;i++){
System.out.println(arr[i]);
}
}
}
You can also try this code with Online Java Compiler
Run Code
Output
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at Test.main(Test.java:5)
60
70
80
90
Multidimensional Arrays
Multidimensional arrays 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 ([]) each dimension results in a multidimensional array.
Syntax
int[][] intArr = new int[10][20]; //a 2D array or matrix
int[][][] intArr = new int[10][20][10]; //a 3D array
Example
public class multiDimensional
{
public static void main(String args[])
{
// declaring and initializing 2D array
int arr[][] = { {1,2,3},{4,5,6},{7,8,9} };
// 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();
}
}
}
You can also try this code with Online Java Compiler
Run Code
Output
1 2 3
4 5 6
7 8 9
Passing Arrays to Methods
Arrays, just like variables, can also be passed to methods. The following program, for example, passes the array to the method max, which prints the maximum element in the array.
Example
public class Test{
//creating a method that receives an array as a parameter
static void max(int arr[]){
int max=arr[0];
for(int i=1;i<arr.length;i++)
if(max<arr[i])
max=arr[i];
System.out.println(max);
}
public static void main(String args[]){
int a[]={30,3,4,5};//declaring and initializing an array
max(a);//passing array to method
}
}
You can also try this code with Online Java Compiler
Run Code
Output:
30
Returning Arrays from Methods
In Java, we may also return an array from the method.
Example
public class Test{
//creating method that returns an array
static int[] get(){
return new int[]{20,40,60,100,70};
}
public static void main(String args[]){
//calling the method that returns an array
int arr[]=get();
//printing the values of the array
for(int i=0;i<arr.length;i++)
System.out.println(arr[i]);
}
}
You can also try this code with Online Java Compiler
Run Code
Output:
20
40
60
100
70
Class Objects for Arrays
Every array has a Class object that is shared with all other arrays of the same component type.
Example
class Test
{
public static void main(String args[])
{
int intArr[] = new int[3];
byte byteArr[] = new byte[3];
short shortsArr[] = new short[3];
// array of Strings
String[] strArr = new String[3];
System.out.println(intArr.getClass());
System.out.println(intArr.getClass().getSuperclass());
System.out.println(byteArr.getClass());
System.out.println(shortsArr.getClass());
System.out.println(strArr.getClass());
}
}
You can also try this code with Online Java Compiler
Run Code
Output
class [I
class java.lang.Object
class [B
class [S
class [Ljava.lang.String;
- For the class object "array with component type int," the string "[I" is the run-time type signature.
- Java.lang.Object is an array's only direct superclass.
- For the class object "array with component type byte," the string "[B" is the run-time type signature.
- For the class object "array with component type short," the string "[S" is the run-time type signature.
- The string “[L” is the run-time type signature for the class object “array with component type of a Class.” Following that comes the Class name.
Cloning an Array in Java
We can construct a clone of the Java array since it implements the Cloneable interface. When we make a deep duplicate of a single-dimensional array, we're actually making a deep copy of the Java array. It signifies that the real value will be copied. However, cloning a multidimensional array makes a shallow duplicate of the Java array, which implies the references are copied.
Example
public class Test{
public static void main(String args[]){
int arr[]={33,3,4,5};
System.out.println("Printing original array:");
for(int i:arr)
System.out.println(i);
System.out.println("Printing clone of the array:");
int carr[]=arr.clone();
for(int i:carr)
System.out.println(i);
System.out.println("Are both equal?");
System.out.println(arr==carr);
}
}
You can also try this code with Online Java Compiler
Run Code
Output:
Printing original array:
33
3
4
5
Printing clone of the array:
33
3
4
5
Are both equal?
false
Practice it on online java compiler.
Must Read Array of Objects in Java
Frequently Asked Questions
-
Is an array a data type?
The array data type is a compound data type in the database dictionary that is represented by the number 8. Arrays are data structures that hold a list of items of the same data type that may be retrieved using an index (element) number.
-
What is an array in Java and types?
A collection of similar-type items stored at a single memory address is referred to as an array. In Java, an array is a collection of objects with the same data type. Furthermore, an array's elements are stored at a single memory address.
-
Is an array a primitive type?
In Java, arrays aren't primitive datatypes. They are dynamically generated container objects. An array may be used to call all of the methods in the Object class.
Key Takeaways
In this article, we have extensively discussed Arrays and their implementation in java .With the help of examples of each, we learned to create, declare, instantiate arrays, further, we learned types and passing and return arrays from methods. In the end, we saw the cloning of arrays.
We hope that this blog has helped you enhance your knowledge regarding Arrays and if you would like to learn more, check out our articles on Array Problems. Do upvote our blog to help other ninjas grow. Happy Coding!
Solve the following problems related to array -