Arrays Data Structure in Java.

An Array is a reference data type that can hold a fixed number of the same type of data. Array elements are store contiguously and the length of the array is decided when the array is created. We cannot change the array length after creation. 

Array in Java is very different than the array present in other programming languages like C/C++. Some key points to note about Array in Java. 

  • In Java, arrays are dynamically allocated. What does it mean? It means that we can allocate memory to an array at run time using the heap. 
  • Arrays are objects in Java and we can use several array properties on them like we can use object property length to know the size of the array. 
  • We can specify the size of the array using int and short data type only. 
An array in Java can hold primitive data like int, char, long, etc, and non-primitive data types like object references. 
Array Indexing

int mark[] = {10, 20, 30, 40 ,50}; //primitive datatype

Employee empList[] = new Employee[3]; //non-primitive datatype

empList[0] = new Employee();
empList[1] = new Employee();
empList[2] = new Employee();

The values that we store in an array are called elements and each element can be accessed by using their index. 

Declaring an Array in Java. 

The two common ways of declaring an array in Java is:

datatype[] arrayName;
        or
datatype arrayName[];

//You can declare array of several different datatype:
int[] arrayInt;
long[] arrayLong;
short[] arrayShort;
float[] arrayFloat;
double[] arrayDouble;
boolean[] arrayBoolean;
char[] arrayChar;
String[] arrayString;

Creating an Array in Java.

An array is created when we allocate memory to an array. 

arrayInt = new int[10]; //creating an array

Initializing an Array in Java.

It is a process of assigning values to each element of the array. 

arrayInt[0] = 10;   //initializing first element
arrayInt[1] = 15;   //initializing second element
arrayInt[2] = 20;   //initializing third element
arrayInt[3] = 25;   //so on..
arrayInt[4] = 30;

Accessing Array Elements in Java. 

We can access any array elements using their index value.

System.out.println(arrayInt[0]); //15
System.out.println(arrayInt[1]); //20
System.out.println(arrayInt[4]); //30

System.out.println(arrayInt[8]); //0
because our array length is 10 but the index 8 is not initialize with any value so by default it assign with 0. 
System.out.println(arrayInt[11]); //Error
We will get "ArrayIndexOutOfBoundsException" because our array length is 10 and we are trying to access index value 11 which is out of its range.


Java program to create integer array and access each element using their index value.  


public class ArrayExample
{
	public static void main(String[] args) {
		//declare an integer 
		int[] array;
		
		//allocating memory to the array 
		array = new int[8];
		
		array[0] = 10;  //initializing first element
		array[1] = 20;  //initializing second element
		array[2] = 30;
		array[3] = 40;
		System.out.println("Element at index 0: "+array[0]); //accessing first element
		System.out.println("Element at index 1: "+array[1]); //accessing second element
		System.out.println("Element at index 2: "+array[2]);
		System.out.println("Element at index 3: "+array[3]);
		System.out.println("Element at index 6: "+array[6]);
	}
}
Output:
Element at index 0: 10
Element at index 1: 20
Element at index 2: 30
Element at index 3: 40
Element at index 6: 0

You can also access array elements using a loop.

public class Main
{
	public static void main(String[] args) {
		//declare an integer 
		int[] array;
		
		//allocating memory to the array 
		array = new int[5];
		
		array[0] = 10;  //initializing first element
		array[1] = 20;  //initializing second element
		array[2] = 30;
		array[3] = 40;
		array[4] = 50;
		
        System.out.println("Length of Array: "+array.length);  
        
		for(int i = 0; i < array.length; i++) {
		    System.out.println("Element at index "+i+":"+array[i]);
		}
	}
}
Output:
Length of Array: 5
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

An array of Objects. 

An array can also store objects similarly like it stores primitive data types. 

Example:
Student studentList[] = new Student[3];

The array variable studentList[] does not hold an array of Student objects, instead, it holds an array of Student reference variables. To make these variables hold the object, we have to create the object as:

studentList[0] = new Student();
studentList[1] = new Student();
studentList[2] = new Student();


Example of Array of Object in Java.

import java.util.*;

class Student {
    public int stud_roll_no;
    public String studen_Name;
    Student(int rollno, String name) {
        this.stud_roll_no = rollno;
        this.studen_Name = name;
    }
}

public class Main
{
	public static void main(String[] args) {
	    Scanner sc = new Scanner(System.in);
	    
	    //allocating memory to object of type student
		Student studentList[] = new Student[3];
		
		//initializing elements of the array
		for(int i = 0; i < studentList.length; i++) {
		    System.out.println("Enter the rollNo: ");
		    int rollno = sc.nextInt();
		    
		    System.out.println("Enter the name: ");
		    String name = sc.next();
		    
		    studentList[i] = new Student(rollno, name);
		}
		
		//accessing elements of the array 
		for(int i = 0; i < studentList.length; i++) {
		    System.out.println(studentList[i].studen_Name+" Roll no is: "+studentList[i].stud_roll_no);
		}
	}
}
Output:
Enter the rollNo: 
101
Enter the name: 
Rahul
Enter the rollNo: 
102
Enter the name: 
Mohit
Enter the rollNo: 
103
Enter the name: 
Kajal
Rahul Roll no is: 101
Mohit Roll no is: 102
Kajal Roll no is: 103

Multidimensional Arrays in Java.

A multidimensional array is also called an Array of Arrays in which an array holds another array. Each row of the array can contain different lengths. The dimension of the array is decided by the number of square brackets ([ ]) you are adding. These are also known as Jagged Array

  • int[] arr; // 1D array
  • int[][] arr; // 2D array
  • int[][][] arr; //3D array  
Example to 2D Array in Java.
public class Main
{
	public static void main(String[] args) {
		
		int[][] arr = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
		
		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 8

Array as a Function Argument.

Java passes "objects by reference" and not by values. The array is passed as a reference and not as a copy of individual elements so any change done using array reference will be reflected in the original array. 

Example of an array as a function argument in Java(Sort an Array). 

class SortArray {
    public void sort(int[] newArr) {
        
        int n = newArr.length;
        
        for(int i = 0; i < n; i++) {
            for(int j = 0; j < n-1; j++) {
                if(newArr[j] > newArr[j+1]) {
                    int temp = newArr[j];
                    newArr[j] = newArr[j+1];
                    newArr[j+1] = temp;
                }
            }
        }
    }
}
public class Main
{
	public static void main(String[] args) {
		
		SortArray obj = new SortArray();
		
		int arr[] = {20, 12, 50, 65, 15, 10};
		obj.sort(arr);
		
		for(int i : arr) {
		    System.out.print(i+" ");
		}
	}
}
Output:
10 12 15 20 50 65

The above example program is to sort all the array elements in ascending order. Similarly, we can perform several different operations on an array, like searching an element in an array using different searching methods or sorting the array elements in ascending or descending order. 

⚡ Please share your valuable feedback and suggestion in the comment section below or you can send us an email on our offical email id ✉ algolesson@gmail.com. You can also support our work by buying a cup of coffee ☕ for us.

Similar Posts

No comments:

Post a Comment


CLOSE ADS
CLOSE ADS