Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Arrays in Java
3.
Creating, Initializing, and Accessing an Array
3.1.
One-Dimensional Arrays
3.2.
Instantiation of an Array in Java
3.3.
Array Literal
3.4.
Accessing Java Array Elements using for Loop
3.5.
Implementation
4.
Arrays of Objects
4.1.
Example
5.
ArrayIndexOutOfBoundsException
5.1.
Example
6.
Multidimensional Arrays
7.
Passing Arrays to Methods
7.1.
Example
8.
Returning Arrays from Methods
8.1.
Example
9.
Class Objects for Arrays
9.1.
Example
10.
Cloning an Array in Java
10.1.
Example
11.
Frequently Asked Questions
12.
Key Takeaways
Last Updated: Mar 27, 2024

What is Array

Author Sanjana Yadav
1 upvote
Crack Google SDE interview : Essential projects
Speaker
Saurav Prateek
SDE-2 @
20 Jun, 2024 @ 01:30 PM

Introduction

An array is a group of items that are stored in adjacent memory locations. The objective is to group together items of the same category. This makes calculating the position of each element easy by simply adding an offset to a base value, i.e., the memory address of the array's first element (denoted by the array name). The base value is index 0, and the offset is the difference between the two indices.

Also see-  Iteration Statements in Java, and Duck Number in Java.

Arrays in Java

In Java, an Array is a collection of variables with similar types that are referred to by a common 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. 
  • 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 can also be declared in the same way that other variables are by appending [] after the data type.
  • The array's variables are sorted, and each has an index starting at 0.
  • Java arrays can also be utilized as static fields, local variables, and method parameters.
  • An array's size must be supplied as an int or short number, not as a long value.
  • Object is the array type's direct superclass.
  • Every array type implements the Cloneable and java.io.Serializable interfaces.

Also see, Swap Function in Java

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

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]);      
    }
}

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);
    }
}

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]);  
        }  
    }
}  

 

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();
		}
	}
}

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  
    } 
}  

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]);  
    }
    
}

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());
	}
}

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);  
          
    }     
}

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

  1. 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.
     
  2. 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.
     
  3. 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 - 

Next article
Arrays In Java
Live masterclass