Learn Array and ArrayList in Java in one article

Why do we need an array?

Let's say you are asked to store the name and roll_number of a student, you will probably declare a string variable to store name and integer variable to store roll number,

Like,

String name = “myname”;
int roll_number = 20;

What if you are asked to store the name and roll number of 5 or 10 students, if you are not familiar with array then you would declare 5 variables for name and roll number, it is possible upto some extent, but what if you are asked to store hundreds or thousands of students data, would you declare hundreds variable’s, of course not, to overcome this problem we have array,

What is an array?

Array is a collection of data of similar data types, like, if you are storing integer values then all the array data should be integer, you can’t store String, boolean or double.

Declaration of Array,

String[] names = {“name1”, ”name2”, ”name3”, ”name4”, ”name5”};

int[] roll_num  = {1,2,3,4,5,6,7,8};

array memory.png Here,

The above array declaration we saw is called array literals, in java we can declare array using objects, lets see how,

String[] names = new String[5]; //Here we are giving size of the array
// new keyword is used to create an object;

Note: Size of the array is compulsory to give otherwise it will give error.

Memory allocation in java,

In c++ we have continuous memory allocation but in Java , the case is different, as java does not have a pointer concept to get the memory address, so it is dependent on JVM whether the memory allocation will be continuous or not, it may or may not be as its depends on JVM (Java Virtual Machine).

Accessing array elements,

Java array elements can be accessed using index number, index number start from 0, so the first element is said to be at 0th index,

Example:

System.out.print(names[0]); //it will give the result name1

So, the nth element can be accessed by n-1th index number.

Changing array element,

Changing is also be done using indexing,

Example:

names[1] = “name2changed”;
//If you again accessed it , it will print name2changed.
System.out.print(names[1]); // it will print "name2changed"

Note: Here I am only taking string array as an example, but you can use any data types but the array elements should be of similar data types.

In java an array is an object, so we are provided with some built in methods and properties,

roll_num.length; //returns  length of the array,
names.contains(‘name3’) // to check whether a particular element is present or not and return boolean values

Note: If you want to get the length of a String array, you need to use parentheses like .length(), because String is not a primitive data type.

names.length();

Note: In java if you access an empty array then, the default integer array returns 0 and String array returns null.

Looping through an array,

1. For loop,

Getting elements in array using for loop,

import java.util.Scanner;  //Importing scanner class
Scanner input = new Scanner(System.in); //creating object of Scanner class
int[] roll_num = new roll_num(30);
int numberofStudent = 30;
for(int roll =1; roll<numberofStudent; roll++){
     input.roll_num(roll);
}//loop will run 30 times and store 30 values;

Getting elements from an array using for loop,


for(int i=0;i<arr.length;i++){
      System.out.print(roll[i]);
}
  1. For Each loop,
for(int elements : arr){

print(elements); //it will return array elements

//when we don't need an index number then we use a foreach loop
}

Note: foreach loop can only be used to access element not to store elements as we need the index number we use for loop.

Passing array in function,

public class Arrays {
    public static void main(String[] args) {
        int[] arr = {3,6,2,8,9,11};
      //calling arrayFunction and passing and array  of int
        arrayFunction(arr);
    }

    //taking array as parameter
    static void arrayFunction(int[] arr){
        //print array elements
        for(int elem:arr){
            System.out.println(elem);
        }
    }
}

2D Array,

2D arrays is like matrix we studied in class 12th, it has rows and columns,

Declaration of 2D array using literals,

int[][] array2d = {
                {1,2,3},
                {4,5,6},
                {7,8,9}
        };

Declaration of 2D array using object,

int[][] array2dobject = new int[4][];

Note: In 2D array we don't need to declare size of column, you can but its not mandatory, size of the column may vary ,

Like,

int[][] array2dobject = new int[4][];
        array2dobject = new int[4][]{
                {1,2,3},
                {4,5,6,34,25,56},
                {7,8,9,43},
                {12,13}
        };

Accessing 2D array elements using for loop,

//run the loop from 0 to number of rows
        for(int row = 0; row < array2dobject.length; row++){
            //run the inner loop from 0 to length of that row
            for(int col = 0; col < array2dobject[row].length; col++){
                System.out.println(array2dobject[row][col]);
            }
           System.out.println(); //printing new line to look pretty 
        }

Accessing 2D array elements using foreach loop,

for(int[] array: array2dobject) {
            System.out.println(Arrays.toString(array));
        }

ArrayList in Java,

In java ArrayList is a class of resizable array, It comes inside java util package,

Why we should use ArrayList?

Java ArrayList is resizable, you can add data as many as you want, but in built_in array we have to create new array after array is completely filled.

Example:

ArrayList<Integer> list = new ArrayList<>();
        list.add(11);
        list.add(12);
        list.add(13)
//you can add as many as you want

Some built_in Arraylist methods that we used frequently,

        //As you saw above .add method is adding elements 
        //remove elements from at particular index
        list.remove(2);
        //delete all the elements at once
        list.clear();
        //checking whether given element is present or not and returns boolean value
        list.contains(13);
        //accessing element from at particular index
        list.get(3);
        //changing element at particular index 
        list.set(3,31); //first parameter is index and second is changed value

Internal working of ArrayList, Size of the arrayList is fixed internally, but what it does, is when some amount of arrayList is filled it creates a new array of double the size and copy the previous array element in new one and pevious one is gone to garbage collector.

I hope this article would have helped you to grasp a good undestanding of Arrays and ArrayList in Java.

I will be posting new article as soon as I learned a new concept of DSA, so stay connected.

Did you find this article valuable?

Support Ghulam Rabbani Ansari by becoming a sponsor. Any amount is appreciated!