Category: 8. Java Array

https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSnsycMpSp4Bbb4uVtMNY-8Hf6P3HFSXRy2sg&s

  • Reverse an Array in Java

    In this tutorial, we will discuss how one can reverse an array in Java. In the input, an integer array is given, and the task is to reverse the input array. Reversing an array means the last element of the input array should be the first element of the reversed array, the second last element of the input array should be the second element of the reversed array, and so on. Observe the following examples.

    Example 1:

    Input:

    arr[] = {1, 2, 3, 4, 5, 6, 7, 8}

    Output

    arr[] = {8, 7, 6, 5, 4, 3, 2, 1}

    Example 2:

    Input:

    arr[] = {4, 8, 3, 9, 0, 1}

    Output:

    arr[] = {1, 0, 9, 3, 8, 4}

    Approach 1: Using an auxiliary array

    We can traverse the array from end to beginning, i.e., in reverse order, and store the element pointed by the loop index in the auxiliary array. The auxiliary array now contains the elements of the input array in reversed order. After that, we can display the auxiliary array on the console. See the following program.

    FileName: ReverseArr.java

    1. public class ReverseArr  
    2. {  
    3. // method for reversing an array  
    4. public int[]  reverseArray(int arr[])  
    5. {  
    6.     // computing the size of the array arr  
    7.     int size = arr.length;  
    8.       
    9.     // auxiliary array for reversing the   
    10.     // elements of the array arr  
    11.     int temp[] = new int[size];  
    12.       
    13.     int index = 0;  
    14.     for(int i = size – 1; i >= 0; i–)  
    15.     {  
    16.         temp[i] = arr[index];  
    17.         index = index + 1;  
    18.     }  
    19.       
    20.     return temp;  
    21.       
    22. }  
    23.   
    24. // main method  
    25. public static void main(String argvs[])   
    26. {  
    27.   // creating an object of the class ReverseArr  
    28.   ReverseArr obj = new ReverseArr();  
    29.     
    30.   // input array – 1  
    31.   int arr[] = {1, 2, 3, 4, 5, 6, 7, 8};  
    32.     
    33.   // computing the length  
    34.   int len = arr.length;  
    35.   int ans[] = obj.reverseArray(arr);  
    36.     
    37.   System.out.println(“For the input array: “);  
    38.   for(int  i = 0; i < len; i++)  
    39.   {  
    40.      System.out.print(arr[i] + ” “);  
    41.   }  
    42.     
    43.   System.out.println();  
    44.   System.out.println(“The reversed array is: “);  
    45.   for(int  i = 0; i < len; i++)  
    46.   {  
    47.      System.out.print(ans[i] + ” “);  
    48.   }  
    49.     
    50.   System.out.println(“\n “);  
    51.     
    52.   // input array – 2  
    53.   int arr1[] = {4, 8, 3, 9, 0, 1};  
    54.     
    55.   // computing the length  
    56.   len = arr1.length;  
    57.   int ans1[] = obj.reverseArray(arr1);  
    58.     
    59.   System.out.println(“For the input array: “);  
    60.   for(int  i = 0; i < len; i++)  
    61.   {  
    62.      System.out.print(arr1[i] + ” “);  
    63.   }  
    64.     
    65.   System.out.println();  
    66.   System.out.println(“The reversed array is: “);  
    67.   for(int  i = 0; i < len; i++)  
    68.   {  
    69.      System.out.print(ans1[i] + ” “);  
    70.   }  
    71.         
    72.    
    73. }  
    74. }  

    Output:

    For the input array:
    1 2 3 4 5 6 7 8
    The reversed array is:
    8 7 6 5 4 3 2 1
    
    For the input array:
    4 8 3 9 0 1
    The reversed array is:
    1 0 9 3 8 4
    

    Complexity Analysis: A for loop is required to reverse the array, which makes the time complexity of the program O(n). Also, an auxiliary array is required to reverse the array making the space complexity of the program O(n), where n is the total number of elements present in the array.

    Approach 2: Using Two Pointers

    We can also use two pointers to reverse the input array. The first pointer will go to the first element of the array. The second pointer will point to the last element of the input array. Now we will start swapping elements pointed by these two pointers. After swapping, the second pointer will move in the leftward direction, and the first pointer will move in the rightward direction. When these two pointers meet or cross each other, we stop the swapping, and the array we get is the reversed array of the input array.

    FileName: ReverseArr1.java

    1. public class ReverseArr1  
    2. {  
    3. // method for reversing an array  
    4. public int[]  reverseArray(int arr[])  
    5. {  
    6.     // computing the size of the array arr  
    7.     int size = arr.length;  
    8.       
    9.     // two pointers for reversing   
    10.     // the input array  
    11.     int ptr1 = 0;  
    12.     int ptr2 = size – 1;  
    13.       
    14.     // reversing the input array  
    15.     // using a while loop  
    16.     while(ptr1 < ptr2)  
    17.     {  
    18.         int temp = arr[ptr1];  
    19.         arr[ptr1] = arr[ptr2];  
    20.         arr[ptr2] = temp;  
    21.           
    22.         ptr1 = ptr1 + 1;  
    23.         ptr2 = ptr2 – 1;  
    24.     }  
    25.       
    26.     return arr;  
    27.       
    28. }  
    29.   
    30. // main method  
    31. public static void main(String argvs[])   
    32. {  
    33.   // creating an object of the class ReverseArr1  
    34.   ReverseArr1 obj = new ReverseArr1();  
    35.     
    36.   // input array – 1  
    37.   int arr[] = {1, 2, 3, 4, 5, 6, 7, 8};  
    38.     
    39.   // computing the length  
    40.   int len = arr.length;  
    41.     
    42.     
    43.   System.out.println(“For the input array: “);  
    44.   for(int  i = 0; i < len; i++)  
    45.   {  
    46.      System.out.print(arr[i] + ” “);  
    47.   }  
    48.     
    49.   int ans[] = obj.reverseArray(arr);  
    50.     
    51.   System.out.println();  
    52.   System.out.println(“The reversed array is: “);  
    53.   for(int  i = 0; i < len; i++)  
    54.   {  
    55.      System.out.print(ans[i] + ” “);  
    56.   }  
    57.     
    58.   System.out.println(“\n “);  
    59.     
    60.   // input array – 2  
    61.   int arr1[] = {4, 8, 3, 9, 0, 1};  
    62.     
    63.   // computing the length  
    64.   len = arr1.length;  
    65.     
    66.     
    67.   System.out.println(“For the input array: “);  
    68.   for(int  i = 0; i < len; i++)  
    69.   {  
    70.      System.out.print(arr1[i] + ” “);  
    71.   }  
    72.     
    73.   int ans1[] = obj.reverseArray(arr1);  
    74.     
    75.   System.out.println();  
    76.   System.out.println(“The reversed array is: “);  
    77.   for(int  i = 0; i < len; i++)  
    78.   {  
    79.      System.out.print(ans1[i] + ” “);  
    80.   }  
    81.         
    82.    
    83. }  
    84. }  

    Output:

    For the input array:
    1 2 3 4 5 6 7 8
    The reversed array is:
    8 7 6 5 4 3 2 1
    
    For the input array:
    4 8 3 9 0 1
    The reversed array is:
    1 0 9 3 8 4
    

    Complexity Analysis: The time complexity of the program is the same as the previous program. There is no extra space used in the program, making the space complexity of the program O(1).

    Approach 3: Using Stack

    Since a Stack works on the LIFO (Last In First Out) principle, it can be used to reverse the input array. All we have to do is to put all the elements of the input array in the stack, starting from left to right. We will do it using a loop.

    FileName: ReverseArr2.java

    1. // importing Stack  
    2. import java.util.Stack;  
    3.   
    4.   
    5. public class ReverseArr2  
    6. {  
    7. // method for reversing an array  
    8. public int[]  reverseArray(int arr[])  
    9. {  
    10.     // computing the size of the array arr  
    11.     int size = arr.length;  
    12.       
    13.     Stack<Integer> stk = new Stack<Integer>();  
    14.       
    15.     // pusing all the elements into stack  
    16.     // starting from left  
    17.     for(int i = 0; i < size; i++)  
    18.     {  
    19.         stk.push(arr[i]);  
    20.     }  
    21.       
    22.     int i = 0;  
    23.     while(!stk.isEmpty())  
    24.     {  
    25.         int ele = stk.pop();  
    26.         arr[i] = ele;  
    27.         i = i + 1;  
    28.     }  
    29.       
    30.     return arr;  
    31.       
    32. }  
    33.   
    34. // main method  
    35. public static void main(String argvs[])   
    36. {  
    37.   // creating an object of the class ReverseArr2  
    38.   ReverseArr2 obj = new ReverseArr2();  
    39.     
    40.   // input array – 1  
    41.   int arr[] = {1, 2, 3, 4, 5, 6, 7, 8};  
    42.     
    43.   // computing the length  
    44.   int len = arr.length;  
    45.     
    46.     
    47.   System.out.println(“For the input array: “);  
    48.   for(int  i = 0; i < len; i++)  
    49.   {  
    50.      System.out.print(arr[i] + ” “);  
    51.   }  
    52.     
    53.   int ans[] = obj.reverseArray(arr);  
    54.     
    55.   System.out.println();  
    56.   System.out.println(“The reversed array is: “);  
    57.   for(int  i = 0; i < len; i++)  
    58.   {  
    59.      System.out.print(ans[i] + ” “);  
    60.   }  
    61.     
    62.   System.out.println(“\n “);  
    63.     
    64.   // input array – 2  
    65.   int arr1[] = {4, 8, 3, 9, 0, 1};  
    66.     
    67.   // computing the length  
    68.   len = arr1.length;  
    69.     
    70.     
    71.   System.out.println(“For the input array: “);  
    72.   for(int  i = 0; i < len; i++)  
    73.   {  
    74.      System.out.print(arr1[i] + ” “);  
    75.   }  
    76.     
    77.   int ans1[] = obj.reverseArray(arr1);  
    78.     
    79.   System.out.println();  
    80.   System.out.println(“The reversed array is: “);  
    81.   for(int  i = 0; i < len; i++)  
    82.   {  
    83.      System.out.print(ans1[i] + ” “);  
    84.   }  
    85.         
    86.    
    87. }  
    88. }  

    Output:

    For the input array:
    1 2 3 4 5 6 7 8
    The reversed array is:
    8 7 6 5 4 3 2 1
    
    For the input array:
    4 8 3 9 0 1
    The reversed array is:
    1 0 9 3 8 4
    

    Complexity Analysis: The time complexity of the program is the same as the previous program. There is stack used in the program, making the space complexity of the program O(n).

    Using Recursion

    Using recursion also, we can achieve the same result. Observe the following.

    FileName: ReverseArr3.java

    1. // importing ArrayList  
    2. import java.util.ArrayList;  
    3.   
    4.   
    5. public class ReverseArr3  
    6. {  
    7. ArrayList<Integer> reverseArr;  
    8.   
    9. // constructor of the class  
    10. ReverseArr3()  
    11. {  
    12. reverseArr = new  ArrayList<Integer>();  
    13. }  
    14.   
    15. // method for reversing an array  
    16. public void  reverseArray(int arr[], int i, int size)  
    17. {  
    18. // dealing with the base case  
    19. if(i >= size)  
    20. {  
    21.     return;  
    22. }  
    23.   
    24. // recursively calling the method  
    25. reverseArray(arr, i + 1, size);  
    26. reverseArr.add(arr[i]);  
    27.       
    28. }  
    29.   
    30. // main method  
    31. public static void main(String argvs[])   
    32. {  
    33.   // creating an object of the class ReverseArr3  
    34.   ReverseArr3 obj = new ReverseArr3();  
    35.     
    36.   // input array – 1  
    37.   int arr[] = {1, 2, 3, 4, 5, 6, 7, 8};  
    38.     
    39.   // computing the length  
    40.   int len = arr.length;  
    41.     
    42.     
    43.   System.out.println(“For the input array: “);  
    44.   for(int  i = 0; i < len; i++)  
    45.   {  
    46.      System.out.print(arr[i] + ” “);  
    47.   }  
    48.     
    49.   obj.reverseArray(arr, 0 , len);  
    50.     
    51.   System.out.println();  
    52.   System.out.println(“The reversed array is: “);  
    53.   for(int  i = 0; i < len; i++)  
    54.   {  
    55.      System.out.print(obj.reverseArr.get(i) + ” “);  
    56.   }  
    57.     
    58.   System.out.println(“\n “);  
    59.     
    60.   obj = new ReverseArr3();  
    61.     
    62.   // input array – 2  
    63.   int arr1[] = {4, 8, 3, 9, 0, 1};  
    64.     
    65.   // computing the length  
    66.   len = arr1.length;  
    67.     
    68.     
    69.   System.out.println(“For the input array: “);  
    70.   for(int  i = 0; i < len; i++)  
    71.   {  
    72.      System.out.print(arr1[i] + ” “);  
    73.   }  
    74.     
    75.   obj.reverseArray(arr1, 0, len);  
    76.     
    77.   System.out.println();  
    78.   System.out.println(“The reversed array is: “);  
    79.   for(int  i = 0; i < len; i++)  
    80.   {  
    81.       System.out.print(obj.reverseArr.get(i) + ” “);  
    82.   }  
    83.         
    84.    
    85. }  
    86. }  

    Output:

    For the input array:
    1 2 3 4 5 6 7 8
    The reversed array is:
    8 7 6 5 4 3 2 1
    
    For the input array:
    4 8 3 9 0 1
    The reversed array is:
    1 0 9 3 8 4
    

    Explanation: The statement reverseArr.add(arr[i]); is written after the recursive call goes in the stack (note that the stack is implicit in this case). So, when the base case is hit in the recursive call, stack unwinding happens, and whatever is there in the stack pops out. The last element goes into the stack during the last recursive call. Therefore, the last element is popped out first. Then the penultimate element is popped out, and so on. The statement reverseArr.add(arr[i]); stores that popped element. In the end, we are displaying the elements that are stored in the list reverseArr.

    Complexity Analysis: Same as the first program of approach-3.

    Approach 4: Using Collections.reverse() method

    The build method Collections.reverse() can be used to reverse the list. The use of it is shown in the following program.

    FileName: ReverseArr4.java

    1. // importing Collections, Arrays, ArrayList & List  
    2. import java.util.Collections;  
    3. import java.util.Arrays;  
    4. import java.util.List;  
    5. import java.util.ArrayList;  
    6.   
    7. public class ReverseArr4  
    8. {  
    9.   
    10. // method for reversing an array  
    11. public List<Integer>  reverseArray(Integer arr[])  
    12. {  
    13. List<Integer> l = (Arrays.asList(arr));  
    14. Collections.reverse(l);  
    15. return l;  
    16. }  
    17.   
    18. // main method  
    19. public static void main(String argvs[])   
    20. {  
    21.   // creating an object of the class ReverseArr4  
    22.   ReverseArr4 obj = new ReverseArr4();  
    23.     
    24.   // input array – 1  
    25.   Integer arr[] = {1, 2, 3, 4, 5, 6, 7, 8};  
    26.     
    27.   // computing the length  
    28.   int len = arr.length;  
    29.     
    30.     
    31.   System.out.println(“For the input array: “);  
    32.   for(int  i = 0; i < len; i++)  
    33.   {  
    34.      System.out.print(arr[i] + ” “);  
    35.   }  
    36.     
    37.   List<Integer> ans = obj.reverseArray(arr);  
    38.     
    39.   System.out.println();  
    40.   System.out.println(“The reversed array is: “);  
    41.   for(int  i = 0; i < len; i++)  
    42.   {  
    43.      System.out.print(ans.get(i) + ” “);  
    44.   }  
    45.     
    46.   System.out.println(“\n “);  
    47.   
    48.   // input array – 2  
    49.   Integer arr1[] = {4, 8, 3, 9, 0, 1};  
    50.     
    51.   // computing the length  
    52.   len = arr1.length;  
    53.     
    54.     
    55.   System.out.println(“For the input array: “);  
    56.   for(int  i = 0; i < len; i++)  
    57.   {  
    58.      System.out.print(arr1[i] + ” “);  
    59.   }  
    60.     
    61.   ans = obj.reverseArray(arr1);  
    62.     
    63.   System.out.println();  
    64.   System.out.println(“The reversed array is: “);  
    65.   for(int  i = 0; i < len; i++)  
    66.   {  
    67.       System.out.print(ans.get(i) + ” “);  
    68.   }  
    69.         
    70.    
    71. }  
    72. }  

    Output:

    For the input array:
    1 2 3 4 5 6 7 8
    The reversed array is:
    8 7 6 5 4 3 2 1
    
    For the input array:
    4 8 3 9 0 1
    The reversed array is:
    1 0 9 3 8 4
    

    Complexity Analysis: The program uses Collections.reverse() method that reverses the list in linear time, making the time complexity of the program O(n). The program uses using list, making the space complexity of the program O(n), where n is the total number of elements present in the array.

    Note 1: Collections.reverse() method is also used to reverse the linked list.

    Note 2: All the approaches discussed above are applicable to different data types too.

    Approach 5: Using StringBuilder.append() method

    It is evident from the heading that this approach is applicable to string arrays. Using the StringBuilder.append() method, we can reverse the string array. All we have to do is to start appending the string elements of the array from the last to the beginning.

    FileName: ReverseArr5.java

    1. import java.util.*;  
    2.   
    3. public class ReverseArr5  
    4. {  
    5.   
    6. // method for reversing an array  
    7. public String[]  reverseArray(String arr[])  
    8. {  
    9. StringBuilder reversedSB = new StringBuilder();  
    10.   
    11. for (int j = arr.length; j > 0; j–)   
    12. {  
    13.   reversedSB.append(arr[j – 1]).append(” “);  
    14. };  
    15.   
    16. String[] reversedArr = reversedSB.toString().split(” “);  
    17. return reversedArr;  
    18. }  
    19.   
    20. // main method  
    21. public static void main(String argvs[])   
    22. {  
    23.   // creating an object of the class ReverseArr5  
    24.   ReverseArr5 obj = new ReverseArr5();  
    25.     
    26.   // input array – 1  
    27.   String arr[] = {“javaTpoint”, “is”, “the”, “best”, “website”};  
    28.     
    29.   // computing the length  
    30.   int len = arr.length;  
    31.     
    32.     
    33.   System.out.println(“For the input array: “);  
    34.   for(int  i = 0; i < len; i++)  
    35.   {  
    36.      System.out.print(arr[i] + ” “);  
    37.   }  
    38.     
    39.   String[] ans = obj.reverseArray(arr);  
    40.     
    41.   System.out.println();  
    42.   System.out.println(“The reversed array is: “);  
    43.   for(int  i = 0; i < len; i++)  
    44.   {  
    45.      System.out.print(ans[i] + ” “);  
    46.   }  
    47.     
    48.   System.out.println(“\n “);  
    49.   
    50.   // input array – 2  
    51.   String arr1[] = {“India”, “is”, “my”, “country”};  
    52.     
    53.   // computing the length  
    54.   len = arr1.length;  
    55.     
    56.     
    57.   System.out.println(“For the input array: “);  
    58.   for(int  i = 0; i < len; i++)  
    59.   {  
    60.      System.out.print(arr1[i] + ” “);  
    61.   }  
    62.     
    63.   String[] ans1 = obj.reverseArray(arr1);  
    64.     
    65.   System.out.println();  
    66.   System.out.println(“The reversed array is: “);  
    67.   for(int  i = 0; i < len; i++)  
    68.   {  
    69.       System.out.print(ans1[i] + ” “);  
    70.   }  
    71.         
    72.    
    73. }  
    74. }  

    Output:

    For the input array:
    javaTpoint is the best website
    The reversed array is:
    website best the is javaTpoint
    
    For the input array:
    India is my country
    The reversed array is:
    country my is India
    
  • String Arrays in Java

    An Array is an essential and most used data structure in Java. It is one of the most used data structure by programmers due to its efficient and productive nature; The Array is a collection of similar data type elements. It uses a contiguous memory location to store the elements.

    What is a String Array?

    A String Array is an Array of a fixed number of String values. A String is a sequence of characters. Generally, a string is an immutable object, which means the value of the string can not be changed. The String Array works similarly to other data types of Array.

    Similar to arrays, in string array only a fixed set of elements can be stored. It is an index-based data structure, which starts from the 0th position. The first element will take place in Index 0, and the 2nd element will take place in Index 1, and so on.

    The main method {Public static void main[ String [] args]; } in Java is also an String Array.

    Consider the below points about the String Array:

    • It is an object of the Array.
    • It can be declared by the two methods; by specifying the size or without specifying the size.
    • It can be initialized either at the time of declaration or by populating the values after the declaration.
    • The elements can be added to a String Array after declaring it.
    • The String Array can be iterated using the for loop.
    • The searching and sorting operation can be performed on the String Array.

    Declaration:

    The Array declaration is of two types, either we can specify the size of the Array or without specifying the size of the Array. A String Array can be declared as follows:

    1. String[] stringArray1   //Declaration of the String Array without specifying the size  
    2. String[] stringArray2 = new String[2];   //Declarartion by specifying the size  

    Another way of declaring the Array is String strArray[], but the above-specified methods are more efficient and recommended.

    Initialization:

    The String Array can be initialized easily. Below is the initialization of the String Array:

    1. 1. String[] strAr1=new String[] {“Ani”, “Sam”, “Joe”}; //inline initialization  
    2. 2. String[] strAr2 = {“Ani”, “Sam”, ” Joe”};  
    3. 3. String[] strAr3= new String[3]; //Initialization after declaration with specific size  
    4.    strAr3[0]= “Ani”;  
    5.    strAr3[1]= “Sam”;  
    6.    strAr3[2]= “Joe”;  

    All of the above three ways are used to initialize the String Array and have the same value.

    The 3rd method is a specific size method. In this, the value of the index can be found using the ( arraylength – 1) formula if we want to access the elements more than the index 2 in the above Array. It will throw the Java.lang.ArrayIndexOutOfBoundsException exception.

    Let’s see an example of String Array to demonstrate it’s behavior:

    Iteration of String Array

    The String Array can be iterated using the for and foreach loop. Consider the below code:

    1. String[] strAr = {“Ani”, “Sam”, “Joe”};  
    2. for (int i=0; i<StrAr.length; i++)  
    3. {  
    4. System.out.println(strAr[i]);  
    5. }  
    6. for ( String str: strAr)  
    7. {  
    8. Sytem.out.println(str);  
    9. }  

    Adding Elements to a String Array

    We can easily add the elements to the String Array just like other data types. It can be done using the following three methods:

    • Using Pre-Allocation of the Array
    • Using the Array List
    • By creating a new Array

    let’s understand the above methods:

    Using Pre-Allocation of the Array:

    In this method, we already have an Array of larger size. For example, if we require to store the 10 elements, then we will create an Array of size 20. It is the easiest way to expand the Array elements.

    Consider the below example to add elements in a pre-allocated array.

    1. // Java Program to add elements in a pre-allocated Array  
    2. import java.util.Arrays;  
    3. public class StringArrayDemo {  
    4.         public static void main(String[] args) {  
    5.             String[] sa = new String[7]; // Creating a new Array of Size 7  
    6.             sa[0] = “A”; // Adding Array elements  
    7.             sa[1] = “B”;  
    8.             sa[2] = “C”;  
    9.             sa[3] = “D”;  
    10.             sa[4] = “E”;  
    11.             System.out.println(“Original Array Elements:” + Arrays.toString(sa));  
    12.             int numberOfItems = 5;  
    13.             String newItem = “F”; // Expanding Array Elements Later  
    14.             String newItem2 =”G”;  
    15.             sa[numberOfItems++] = newItem;  
    16.             sa[numberOfItems++] = newItem2;  
    17.             System.out.println(“Array after adding two elements:” +    
    18.                       Arrays.toString(sa));  
    19.         }  
    20.     }  

    Output:

    Original Array Elements:[A, B, C, D, E, null, null]
    Array after adding two elements:[A, B, C, D, E, F, G]
    

    From the above example, we have added two elements in a pre-allocated Array.

    Using ArrayList:

    The ArrayList is a fascinating data structure of the Java collection framework. We can easily add elements to a String Array using an ArrayList as an intermediate data structure.

    Consider the below example to understand how to add elements to a String Array using ArrayList:

    File Name: StringArrayDemo1.java

    1. import java.util.ArrayList;  
    2. import java.util.Arrays;  
    3. import java.util.List;  
    4.   
    5. public class StringArrayDemo1 {   
    6.         public static void main(String[] args)   
    7.         {   
    8.               // Defining a String Array   
    9.               String sa[] = { “A”, “B”, “C”, “D”, “E”, “F” };  
    10.           //   
    11.             System.out.println(“Initial Array:\n”  
    12.                                + Arrays.toString(sa));   
    13.             String ne = “G”; // Define new element to add  
    14.             List<String>l = new ArrayList<String>(  
    15.                       Arrays.asList(sa)); // Convert Array to ArrayList  
    16.             l.add(ne); // Add new element in ArrayList l  
    17.             sa = l.toArray(sa); // Revert Conversion from ArrayList to Array  
    18.             // printing the new Array  
    19.             System.out.println(“Array with added Value: \n”  
    20.                                + Arrays.toString(sa)) ;   
    21.         }   
    22.     }  

    Output:

    Initial Array:
    [A, B, C, D, E, F]
    Array with added value:
    [A, B, C, D, E, F, G]
    

    By Creating a New Array:

    In this method, we will create a new Array with a larger size than the initial Array and accommodate the elements in it. We will copy all the elements to the newly added Array. Consider the following example:

    File Name: StringArrayDemo2.java

    1. // Java Program to add elements in a String Array by creating a new Array  
    2. import java.util.Arrays;  
    3. public class StringArrayDemo2 {  
    4.         public static void main(String[] args) {  
    5.             //Declaring Initial Array  
    6.             String[] sa = {“A”, “B”, “C” };    
    7.             // Printing the Original Array  
    8.             System.out.println(“Initial Array: ” + Arrays.toString(sa));  
    9.                 int length_Var = sa.length; //Defining the array length variable  
    10.             String newElement = “D”; // Defining new element to add  
    11.             //define new array with extended length           
    12.             String[] newArray = new String[ length_Var + 1 ];  
    13.             //Adding all the elements to initial Array  
    14.             for (int i=0; i <sa.length; i++)  
    15.             {  
    16.                 newArray[i] = sa [i];  
    17.              }  
    18.             //Specifying the position of the added elements ( Last)  
    19.             newArray[newArray.length- 1] = newElement;  
    20.             //make it original and print  
    21.             sa = newArray;     
    22.             System.out.println(“updated Array: ” + Arrays.toString(sa));  
    23.         }  
    24.     }  

    Output:

    Initial Array: [A, B, C]
    updated Array: [A, B, C, D]
    

    This is how we can add elements to a String Array. Let’s understand how to search and sort elements in String Array.

    Searching in String Array

    For searching a String from the String Array, for loop is used. Consider the below example:

    StringArrayExample.java

    1. public class StringArrayExample {  
    2.         public static void main(String[] args) {  
    3.             String[] strArray = { “Ani”, “Sam”, “Joe” };  
    4.             boolean x = false//initializing x to false  
    5.             int in = 0; //declaration of index variable  
    6.             String s = “Sam”;  // String to be searched  
    7.             // Iteration of the String Array  
    8.             for (int i = 0; i < strArray.length; i++) {  
    9.                 if(s.equals(strArray[i])) {  
    10.                     in = i; x = truebreak;  
    11.                 }  
    12.             }  
    13.             if(x)  
    14.                 System.out.println(s +” String is found at index “+in);  
    15.             else  
    16.                 System.out.println(s +” String is not found in the array”);  
    17.         }  
    18. }  

    Output:

    Sam String is found at index 1
    

    In the above example, we have initialized a boolean variable x to false and an index variable to iterate through the string. Also, we have declared a local variable String variable s to be searched. Here, the break keyword will exit the loop as soon as the string is found.

    Sorting in String Array

    The sorting in the String array is quite easy. It is performed like in a traditional array. We use a sort() method to sort the Array elements. Sorting is easier than searching.

    Consider the below example to sort a String Array:

    File Name: StringArraySorting.java

    1. //Java Program to sort elements in a String Array  
    2. import java.util.Arrays;  
    3. public class StringArraySorting {  
    4.        public static void main(String[] args)   
    5.         {   
    6.            // Adding String values  
    7.            String[] colors = {“Cricket”,”Basketball”,”Football”,”Badminton”,”Tennis”};  
    8.            // Print Original values   
    9.            System.out.println(“Entered Sports: “+Arrays.toString(colors));  
    10.             Arrays.sort(colors); // Sorting Elements  
    11.            // Print Sorted Values  
    12.             System.out.println(“Sorted Sports: “+Arrays.toString(colors));  
    13.         }  
    14.     }  

    Output:

    Entered Sports: [Cricket, Basketball, Football, Badminton, Tennis]
    Sorted Sports: [Badminton, Basketball, Cricket, Football, Tennis]
    

    From the above example, we can see the elements from a String Array is sorted using the sort() method.

    We can also convert String Array to other data structures such as List, int Array, ArrayList, and more and vice-versa.

    Manipulating String Arrays

    String arrays support various operations for manipulation, including adding, removing, and modifying elements. However, it’s essential to remember that arrays in Java have a fixed size once initialized. Therefore, to perform dynamic operations, such as adding or removing elements, you may need to resort to other data structures like ArrayList.

  • Array of Objects in Java

    In Java, an array is a collection of the same data type that dynamically creates objects and can have elements of primitive types. Java allows us to store objects in an array.

    An array of objects is a collection of multiple objects stored in a single variable. It stores the references to the objects. It is useful when managing multiple instances of a class efficiently.

    How to Create Array of Objects in Java

    Creating an Array of Objects

    Before creating an array of objects, we must create an instance of the class by using the new keyword. We can use any of the following statements to create an array of objects.

    Syntax:

    1. ClassName obj[]=new ClassName[array_length]; //declare and instantiate an array of objects  

    Or

    1. ClassName[] objArray;  

    Or

    1. ClassName objeArray[];  

    Suppose, we have created a class named Employee. We want to keep records of 20 employees of a company having three departments. In this case, we will not create 20 separate variables. Instead of this, we will create an array of objects, as follows.

    1. Employee department1[20];  
    2. Employee department2[20];  
    3. Employee department3[20];  

    The above statements create an array of objects with 20 elements.

    Example: Creating an Array of Objects

    In the following program, we have created a class named Product and initialized an array of objects using the constructor. We have created a constructor of the class Product that contains the product ID and product name. In the main() function, we have created individual objects of the class Product. After that, we passed initial values to each of the objects using the constructor.

    Example

    1. public class Main  {    
    2.     public static void main(String args[])   {    
    3.         //create an array of product objects     
    4.         Product[] obj = new Product[5] ;    
    5.         //create & initialize actual product objects using constructor    
    6.         obj[0] = new Product(23907,”Dell Laptop”);    
    7.         obj[1] = new Product(91240,”HP 630″);    
    8.         obj[2] = new Product(29823,”LG OLED TV”);    
    9.         obj[3] = new Product(11908,”MI Note Pro Max 9″);    
    10.         obj[4] = new Product(43590,”Kingston USB”);    
    11.         //display the product object data    
    12.         System. out.println(“Product Object 1:”);    
    13.         obj[0].display();    
    14.         System.out.println(“Product Object 2:”);    
    15.         obj[1].display();    
    16.         System.out.println(“Product Object 3:”);    
    17.         obj[2].display();    
    18.         System.out.println(“Product Object 4:”);    
    19.         obj[3].display();    
    20.         System.out.println(“Product Object 5:”);    
    21.         obj[4].display();    
    22.     }    
    23. }    
    24.  //Product class with product ID and product name as attributes    
    25. class Product  {    
    26.     int pro_Id;    
    27.     String pro_name;    
    28.     //Product class constructor    
    29.     Product(int pid, String n)  {    
    30.         pro_Id = pid;    
    31.         pro_name = n;    
    32.     }     
    33.     public void display()  {    
    34.         System.out.print(“Product ID = “+pro_ID + ”  ” + ” Product Name = “+pro_name);    
    35.         System.out.println();    
    36.     }    
    37. }    

    Compile and Run

    Output:

    Product Object 1:
    Product ID = 23907 Product Name = Dell Laptop
    Product Object 2:
    Product ID = 91240 Product Name = HP 630
    Product Object 3:
    Product ID = 29823 Product Name = LG OLED TV
    Product Object 4:
    Product ID = 11908 Product Name = MI Note Pro Max 9
    Product Object 5:
    Product ID = 43590 Product Name = Kingston USB
    

    Initializing an Array of Objects

    After the objects are instantiated, the array has to be initialized with values. In contrast to a variety of primitive types, an array of objects cannot be initialized in the same way. It is necessary to initialize each element or object in an array of objects. An array contains pointers to the real class through its objects.

    Consequently, it is highly recommended to generate actual objects of the class after declaring and instantiating an array of objects. The constructors can set up the array. Actual objects can have their initial values assigned by the application by supplying values to the constructor. A class’s independent member method can also be used to assign data to an object.

    The elements of an array of objects must be initialized after they have been created. Two common approaches are available to perform this:

    1. Using the Constructor
    2. Using Setter Methods

    1. Using the Constructor

    By providing variables to the constructor individually, we can define starting values for each object as the actual objects are being created. Every single real object is made with its unique values.

    Example

    1. // Java program to demonstrate initializing an array of objects using a constructor  
    2. public class Main {  
    3.     public static void main(String args[]) {  
    4.         // Declaring an array of Book  
    5.         Book[] books;  
    6.         // Allocating memory for 3 Book objects  
    7.         books = new Book[3];  
    8.         // Initializing the elements of the array using the constructor  
    9.         books[0] = new Book(101, “Java Basics”);  
    10.         books[1] = new Book(102, “Data Structures”);  
    11.         books[2] = new Book(103, “Operating Systems”);  
    12.         System.out.println(“Book details:”);  
    13.         for (int i = 0; i < books.length; i++) {  
    14.             books[i].display();  
    15.         }  
    16.     }  
    17. }  
    18. // Creating a Book class with id and title as attributes  
    19. class Book {  
    20.     public int bookId;  
    21.     public String title;  
    22.     // Book class constructor  
    23.     Book(int bookId, String title) {  
    24.         this.bookId = bookId;  
    25.         this.title = title;  
    26.     }  
    27.     // display() method to display the book data  
    28.     public void display() {  
    29.         System.out.println(“Book ID: ” + bookId + “, Title: ” + title);  
    30.     }  
    31. }  

    Compile and Run

    Output:

    Book details:
    Book ID: 101, Title: Java Basics
    Book ID: 102, Title: Data Structures
    Book ID: 103, Title: Operating Systems
    

    3. Using Setter Methods

    Using setter methods, we may assign values after creating objects. The initial values of the objects are assigned using a member function of the corresponding class that is formed.

    Example

    1. // Java program to demonstrate initializing an array of objects using setter methods  
    2. public class Main {  
    3.     public static void main(String args[]) {  
    4.         // Declaring an array of Book  
    5.         Book[] books;  
    6.         // Allocating memory for 3 objects of type Book  
    7.         books = new Book[3];  
    8.         // Creating actual Book objects  
    9.         books[0] = new Book();  
    10.         books[1] = new Book();  
    11.         books[2] = new Book();  
    12.         // Assigning data to Book objects using the setter method  
    13.         books[0].setData(201, “Java Programming”);  
    14.         books[1].setData(202, “Algorithms”);  
    15.         books[2].setData(203, “Database Systems”);  
    16.         // Displaying the book data  
    17.         System.out.println(“Book details:”);  
    18.         for (int i = 0; i < books.length; i++) {  
    19.             books[i].display();  
    20.         }  
    21.     }  
    22. }  
    23. // Creating a Book class with id and title as attributes  
    24. class Book {  
    25.     public int bookId;  
    26.     public String title;  
    27.     // Setter method to set the data  
    28.     public void setData(int bookId, String title) {  
    29.         this.bookId = bookId;  
    30.         this.title = title;  
    31.     }  
    32.     // display() method to show book details  
    33.     public void display() {  
    34.         System.out.println(“Book ID: ” + bookId + “, Title: ” + title);  
    35.     }  
    36. }  

    Compile and Run

    Output:

    Book details:
    Book ID: 201, Title: Java Programming
    Book ID: 202, Title: Algorithms
    Book ID: 203, Title: Database Systems
    
  • Arrays Class in Java

    In Java, the Arrays class is a utility class that is a member of the Java collection framework. It belongs to java.util package. The class provides various static methods for manipulating arrays efficiently. It simplifies common operations (like searching, sorting, copying and comparison) on the arrays.

    To read more Java Arrays

    Why Use the Java Arrays Class?

    The main reason for using the Java Arrays class is that it provides ready-made methods for complex logic. Here are some reasons why developers use it often.

    1. Convenience: The Arrays class is convenience for array manipulation because it provides various ready-made static methods to perform complex logic. It eliminates the need to write complex code for array operations.
    2. Efficiency: Methods in this class provide highly optimized algorithms (Dual-Pivot Quicksort for primitives and TimSort for objects). It offers better performance that increases efficiency.
    3. Readability: The methods of the Arrays class follow intuitive names (names that are easy to pronounce, spell, and understand, often having a straightforward and familiar sound) and behaviors that make code easier to read, understand, and maintain.
    4. Streamlining Code: By using the Arrays class, the code becomes cleaner and more concise. We can use the Arrays.toString() method to convert arrays into a String instead of writing a loop.
    5. Enhanced Functionality: The class provides advance capabilities like deep comparison by using the Arrays.deepEquals() method, filling arrays efficiently by using the Arrays,fill() method, and working with streams by using the Arrays.stream() method.
    6. Collection Compatibility: The class allows seamless conversion of arrays to lists, which makes it easier to work with the collection framework.

    Java Arrays Class Methods

    ManipulationMethod SignatureDescription
    Sortingsort(byte[] a)  Sorts the specified array into ascending numerical order.
    sort(byte[] a, int fromIndex, int toIndex)Sorts the specified range of the array into ascending order.
    sort(char[] a)  Sorts the specified array into ascending numerical order.
    sort(char[] a, int fromIndex, int toIndex)Sorts the specified range of the array into ascending order.
    sort(double[] a)Sorts the specified array into ascending numerical order.
    sort(double[] a, int fromIndex, int toIndex)
    Sorts the specified range of the array into ascending order.
    sort(float[] a)Sorts the specified array into ascending numerical order.
    sort(float[] a, int fromIndex, int toIndex)Sorts the specified range of the array into ascending order.
    sort(int[] a)Sorts the specified array into ascending numerical order.
    sort(int[] a, int fromIndex, int toIndex)Sorts the specified range of the array into ascending order.
    sort(long[] a)Sorts the specified array into ascending numerical order.
    sort(long[] a, int fromIndex, int toIndex)Sorts the specified range of the array into ascending order.
    sort(short[] a)Sorts the specified array into ascending numerical order.
    sort(short[] a, int fromIndex, int toIndex)Sorts the specified range of the array into ascending order.
    sort(Object[] a)  Sorts the specified array of objects into ascending order, according to the natural ordering of its elements.
    sort(Object[] a, int fromIndex, int toIndex)  Sorts the specified range of the specified array of objects into ascending order, according to the natural ordering of its elements.
    sort(T[] a, int fromIndex, int toIndex, Comparator<? super T> c)Sorts the specified range of the specified array of objects according to the order induced by the specified comparator.
    sort(T[] a, Comparator<? super T> c)  Sorts the specified array of objects according to the order induced by the specified comparator.
    SearchingbinarySearch(byte[] a, byte key)Searches the specified array of bytes for the specified value using the binary search algorithm.
    binarySearch(byte[] a, int fromIndex, int toIndex, byte key)Searches a range of the specified array of bytes for the specified value using the binary search algorithm.
    binarySearch(char[] a, char key)Searches the specified array of chars for the specified value using the binary search algorithm.
    binarySearch(char[] a, int fromIndex, int toIndex, char key)Searches a range of the specified array of chars for the specified value using the binary search algorithm.
    binarySearch(double[] a, double key)Searches the specified array of doubles for the specified value using the binary search algorithm.
    binarySearch(double[] a, int fromIndex, int toIndex, double key)Searches a range of the specified array of doubles for the specified value using the binary search algorithm.
    binarySearch(float[] a, float key)  Searches the specified array of floats for the specified value using the binary search algorithm.
    binarySearch(float[] a, int fromIndex, int toIndex, float key)Searches a range of the specified array of floats for the specified value using the binary search algorithm.
    binarySearch(int[] a, int key)Searches the specified array of ints for the specified value using the binary search algorithm.
    binarySearch(int[] a, int fromIndex, int toIndex, int key)Searches a range of the specified array of ints for the specified value using the binary search algorithm.
    binarySearch(long[] a, int fromIndex, int toIndex, long key)Searches a range of the specified array of longs for the specified value using the binary search algorithm.
    binarySearch(long[] a, long key)  Searches the specified array of longs for the specified value using the binary search algorithm.
    binarySearch(short[] a, int fromIndex, int toIndex, short key)  Searches a range of the specified array of shorts for the specified value using the binary search algorithm.
    binarySearch(short[] a, short key)  Searches the specified array of shorts for the specified value using the binary search algorithm.
    binarySearch(Object[] a, int fromIndex, int toIndex, Object key)  Searches a range of the specified array for the specified object using the binary search algorithm.
    binarySearch(Object[] a, Object key)  Searches the specified array for the specified object using the binary search algorithm.
    binarySearch(T[] a, int fromIndex, int toIndex, T key, Comparator<? super T> c)Searches a range of the specified array for the specified object using the binary search algorithm.
    binarySearch(T[] a, T key, Comparator<? super T> c)Searches the specified array for the specified object using the binary search algorithm.
    ComparisondeepEquals(Object[] a1, Object[] a2)Returns true if the two specified arrays are deeply equal to one another.
    deepHashCode(Object[] a)  Returns a hash code based on the “deep contents” of the specified array.
    deepToString(Object[] a)Returns a string representation of the “deep contents” of the specified array.
    equals(boolean[] a, boolean[] a2)  
    Returns true if the two specified arrays of booleans are equal to one another.
    equals(boolean[] a, int aFromIndex, int aToIndex, boolean[] b, int bFromIndex, int bToIndex)Returns true if the two specified arrays of booleans, over the specified ranges, are equal to one another.
    equals(byte[] a, byte[] a2)Returns true if the two specified arrays of bytes are equal to one another.
    equals(byte[] a, int aFromIndex, int aToIndex, byte[] b, int bFromIndex, int bToIndex)Returns true if the two specified arrays of bytes, over the specified ranges, are equal to one another.
    equals(char[] a, char[] a2)Returns true if the two specified arrays of chars are equal to one another.
    equals(char[] a, int aFromIndex, int aToIndex, char[] b, int bFromIndex, int bToIndex)Returns true if the two specified arrays of chars, over the specified ranges, are equal to one another.
    equals(double[] a, double[] a2)Returns true if the two specified arrays of doubles are equal to one another.
    equals(double[] a, int aFromIndex, int aToIndex, double[] b, int bFromIndex, int bToIndex)Returns true if the two specified arrays of doubles, over the specified ranges, are equal to one another.
    equals(float[] a, float[] a2)Returns true if the two specified arrays of floats are equal to one another.
    equals(float[] a, int aFromIndex, int aToIndex, float[] b, int bFromIndex, int bToIndex)Returns true if the two specified arrays of floats, over the specified ranges, are equal to one another.
    equals(int[] a, int[] a2)Returns true if the two specified arrays of ints are equal to one another.
    equals(int[] a, int aFromIndex, int aToIndex, int[] b, int bFromIndex, int bToIndex)Returns true if the two specified arrays of ints, over the specified ranges, are equal to one another.
    equals(long[] a, int aFromIndex, int aToIndex, long[] b, int bFromIndex, int bToIndex)Returns true if the two specified arrays of longs, over the specified ranges, are equal to one another.
    equals(long[] a, long[] a2)Returns true if the two specified arrays of longs are equal to one another.
    equals(short[] a, int aFromIndex, int aToIndex, short[] b, int bFromIndex, int bToIndex)Returns true if the two specified arrays of shorts, over the specified ranges, are equal to one another.

    equals(short[] a, short[] a2)  
    Returns true if the two specified arrays of shorts are equal to one another.
    equals(Object[] a, int aFromIndex, int aToIndex, Object[] b, int bFromIndex, int bToIndex)Returns true if the two specified arrays of Objects, over the specified ranges, are equal to one another.

    equals(Object[] a, Object[] a2)  
    Returns true if the two specified arrays of Objects are equal to one another.
    equals(T[] a, int aFromIndex, int aToIndex, T[] b, int bFromIndex, int bToIndex, Comparator<? super T> cmp)Returns true if the two specified arrays of Objects, over the specified ranges, are equal to one another.
    equals(T[] a, T[] a2, Comparator<? super T> cmp)Returns true if the two specified arrays of Objects are equal to one another.
    compare(boolean[] a, boolean[] b)Compares two boolean arrays lexicographically.
    compare(boolean[] a, int aFromIndex, int aToIndex, boolean[] b, int bFromIndex, int bToIndex)Compares two boolean arrays lexicographically over the specified ranges.
    compare(byte[] a, byte[] b)Compares two byte arrays lexicographically.
    compare(byte[] a, int aFromIndex, int aToIndex, byte[] b, int bFromIndex, int bToIndex)Compares two byte arrays lexicographically over the specified ranges.
    compare(char[] a, char[] b)Compares two char arrays lexicographically.
    compare(char[] a, int aFromIndex, int aToIndex, char[] b, int bFromIndex, int bToIndex)Compares two char arrays lexicographically over the specified ranges.
    compare(double[] a, double[] b)Compares two double arrays lexicographically.
    compare(double[] a, int aFromIndex, int aToIndex, double[] b, int bFromIndex, int bToIndex)Compares two double arrays lexicographically over the specified ranges.
    compare(float[] a, float[] b)Compares two float arrays lexicographically.
    compare(float[] a, int aFromIndex, int aToIndex, float[] b, int bFromIndex, int bToIndex)Compares two float arrays lexicographically over the specified ranges.
    compare(int[] a, int[] b)Compares two int arrays lexicographically.
    compare(int[] a, int aFromIndex, int aToIndex, int[] b, int bFromIndex, int bToIndex)Compares two int arrays lexicographically over the specified ranges.
    compare(long[] a, int aFromIndex, int aToIndex, long[] b, int bFromIndex, int bToIndex)Compares two long arrays lexicographically over the specified ranges.
    compare(long[] a, long[] b)Compares two long arrays lexicographically.
    compare(short[] a, int aFromIndex, int aToIndex, short[] b, int bFromIndex, int bToIndex)Compares two short arrays lexicographically over the specified ranges.
    compare(short[] a, short[] b)Compares two short arrays lexicographically.
    compare(T[] a, int aFromIndex, int aToIndex, T[] b, int bFromIndex, int bToIndex)Compares two Object arrays lexicographically over the specified ranges.
    compare(T[] a, int aFromIndex, int aToIndex, T[] b, int bFromIndex, int bToIndex, Comparator<? super T> cmp)Compares two Object arrays lexicographically over the specified ranges.
    compare(T[] a, T[] b)Compares two Object arrays, within comparable elements, lexicographically.
    compare(T[] a, T[] b, Comparator<? super T> cmp)Compares two Object arrays lexicographically using a specified comparator.
    compareUnsigned(byte[] a, byte[] b)Compares two byte arrays lexicographically, numerically treating elements as unsigned.
    compareUnsigned(byte[] a, int aFromIndex, int aToIndex, byte[] b, int bFromIndex, int bToIndex)Compares two byte arrays lexicographically over the specified ranges, numerically treating elements as unsigned.
    compareUnsigned(int[] a, int[] b)Compares two int arrays lexicographically, numerically treating elements as unsigned.
    compareUnsigned(int[] a, int aFromIndex, int aToIndex, int[] b, int bFromIndex, int bToIndex)Compares two int arrays lexicographically over the specified ranges, numerically treating elements as unsigned.
    compareUnsigned(long[] a, int aFromIndex, int aToIndex, long[] b, int bFromIndex, int bToIndex)Compares two long arrays lexicographically over the specified ranges, numerically treating elements as unsigned.
    compareUnsigned(long[] a, long[] b)Compares two long arrays lexicographically, numerically treating elements as unsigned.
    compareUnsigned(short[] a, int aFromIndex, int aToIndex, short[] b, int bFromIndex, int bToIndex)Compares two short arrays lexicographically over the specified ranges, numerically treating elements as unsigned.
    compareUnsigned(short[] a, short[] b)Compares two short arrays lexicographically, numerically treating elements as unsigned.
    CopyingcopyOf(boolean[] original, int newLength)Copies the specified array, truncating or padding with false (if necessary) so the copy has the specified length.
    copyOf(byte[] original, int newLength)Copies the specified array, truncating or padding with zeros (if necessary) so the copy has the specified length.
    copyOf(char[] original, int newLength)Copies the specified array, truncating or padding with null characters (if necessary) so the copy has the specified length.
    copyOf(double[] original, int newLength)Copies the specified array, truncating or padding with zeros (if necessary) so the copy has the specified length.
    copyOf(float[] original, int newLength)Copies the specified array, truncating or padding with zeros (if necessary) so the copy has the specified length.
    copyOf(int[] original, int newLength)Copies the specified array, truncating or padding with zeros (if necessary) so the copy has the specified length.
    copyOf(long[] original, int newLength)Copies the specified array, truncating or padding with zeros (if necessary) so the copy has the specified length.
    copyOf(short[] original, int newLength)Copies the specified array, truncating or padding with zeros (if necessary) so the copy has the specified length.
    copyOf(T[] original, int newLength)Copies the specified array, truncating or padding with nulls (if necessary) so the copy has the specified length.
    copyOf(U[] original, int newLength, Class<? extends T[]> newType)Copies the specified array, truncating or padding with nulls (if necessary) so the copy has the specified length.
    copyOfRange(boolean[] original, int from, int to)Copies the specified range of the specified array into a new array.
    copyOfRange(byte[] original, int from, int to)Copies the specified range of the specified array into a new array.
    copyOfRange(char[] original, int from, int to)Copies the specified range of the specified array into a new array.
    copyOfRange(double[] original, int from, int to)Copies the specified range of the specified array into a new array.
    copyOfRange(float[] original, int from, int to)Copies the specified range of the specified array into a new array.
    copyOfRange(int[] original, int from, int to)Copies the specified range of the specified array into a new array.
    copyOfRange(long[] original, int from, int to)Copies the specified range of the specified array into a new array.
    copyOfRange(short[] original, int from, int to)Copies the specified range of the specified array into a new array.
    copyOfRange(T[] original, int from, int to)Copies the specified range of the specified array into a new array.
    copyOfRange(U[] original, int from, int to, Class<? extends T[]> newType)Copies the specified range of the specified array into a new array.
    Fillfill(boolean[] a, boolean val)Assigns the specified boolean value to each element of the specified array of booleans.
    fill(boolean[] a, int fromIndex, int toIndex, boolean val)Assigns the specified boolean value to each element of the specified range of the specified array of booleans.
    fill(byte[] a, byte val)Assigns the specified byte value to each element of the specified array of bytes.
    fill(byte[] a, int fromIndex, int toIndex, byte val)Assigns the specified byte value to each element of the specified range of the specified array of bytes.
    fill(char[] a, char val)Assigns the specified char value to each element of the specified array of chars.
    fill(char[] a, int fromIndex, int toIndex, char val)Assigns the specified char value to each element of the specified range of the specified array of chars.
    fill(double[] a, double val)Assigns the specified double value to each element of the specified array of doubles.
    fill(double[] a, int fromIndex, int toIndex, double val)Assigns the specified double value to each element of the specified range of the specified array of doubles.
    fill(float[] a, float val)Assigns the specified float value to each element of the specified array of floats.
    fill(float[] a, int fromIndex, int toIndex, float val)Assigns the specified float value to each element of the specified range of the specified array of floats.
    fill(int[] a, int val)Assigns the specified int value to each element of the specified array of ints.
    fill(int[] a, int fromIndex, int toIndex, int val)Assigns the specified int value to each element of the specified range of the specified array of ints.
    fill(long[] a, int fromIndex, int toIndex, long val)Assigns the specified long value to each element of the specified range of the specified array of longs.
    fill(long[] a, long val)Assigns the specified long value to each element of the specified array of longs.
    fill(short[] a, int fromIndex, int toIndex, short val)Assigns the specified short value to each element of the specified range of the specified array of shorts.
    fill(short[] a, short val)Assigns the specified short value to each element of the specified array of shorts.
    fill(Object[] a, int fromIndex, int toIndex, Object val)Assigns the specified Object reference to each element of the specified range of the specified array of Objects.
    fill(Object[] a, Object val)Assigns the specified Object reference to each element of the specified array of Objects.
    Streamstream(double[] array)Returns a sequential DoubleStream with the specified array as its source.
    stream(double[] array, int startInclusive, int endExclusive)Returns a sequential DoubleStream with the specified range of the specified array as its source.
    stream(int[] array)Returns a sequential IntStream with the specified array as its source.
    stream(int[] array, int startInclusive, int endExclusive)Returns a sequential IntStream with the specified range of the specified array as its source.
    stream(long[] array)Returns a sequential LongStream with the specified array as its source.
    stream(long[] array, int startInclusive, int endExclusive)Returns a sequential LongStream with the specified range of the specified array as its source.
    stream(T[] array)  Returns a sequential Stream with the specified array as its source.
    stream(T[] array, int startInclusive, int endExclusive)Returns a sequential Stream with the specified range of the specified array as its source.
    ConversiontoString(boolean[] a)Returns a string representation of the contents of the specified array.
    toString(byte[] a)Returns a string representation of the contents of the specified array.
    toString(char[] a)Returns a string representation of the contents of the specified array.
    toString(double[] a)Returns a string representation of the contents of the specified array.
    toString(float[] a)Returns a string representation of the contents of the specified array.
    toString(int[] a)Returns a string representation of the contents of the specified array.
    toString(long[] a)  Returns a string representation of the contents of the specified array.
    toString(short[] a)  Returns a string representation of the contents of the specified array.
    toString(Object[] a)Returns a string representation of the contents of the specified array.
     asList(T… a)Returns a fixed-size list backed by the specified array.
    UtilityhashCode(boolean[] a)Returns a hash code based on the contents of the specified array.
    hashCode(byte[] a)Returns a hash code based on the contents of the specified array.
    hashCode(char[] a)Returns a hash code based on the contents of the specified array.
    hashCode(double[] a)Returns a hash code based on the contents of the specified array.
    hashCode(float[] a)Returns a hash code based on the contents of the specified array.
    hashCode(int[] a)Returns a hash code based on the contents of the specified array.
    hashCode(long[] a)Returns a hash code based on the contents of the specified array.
    hashCode(short[] a)Returns a hash code based on the contents of the specified array.
    hashCode(Object[] a)Returns a hash code based on the contents of the specified array.
    mismatch(boolean[] a, boolean[] b)Finds and returns the index of the first mismatch between two boolean arrays; otherwise, returns -1 if no mismatch is found.
    mismatch(boolean[] a, int aFromIndex, int aToIndex, boolean[] b, int bFromIndex, int bToIndex)Finds and returns the relative index of the first mismatch between two boolean arrays over the specified ranges, otherwise returns -1 if no mismatch is found.
    mismatch(byte[] a, byte[] b)Finds and returns the index of the first mismatch between two-byte arrays; otherwise, returns -1 if no mismatch is found.
    mismatch(byte[] a, int aFromIndex, int aToIndex, byte[] b, int bFromIndex, int bToIndex)Finds and returns the relative index of the first mismatch between two-byte arrays over the specified ranges, otherwise returns -1 if no mismatch is found.
    mismatch(char[] a, char[] b)Finds and returns the index of the first mismatch between two char arrays; otherwise, returns -1 if no mismatch is found.
    mismatch(char[] a, int aFromIndex, int aToIndex, char[] b, int bFromIndex, int bToIndex)Finds and returns the relative index of the first mismatch between two char arrays over the specified ranges, otherwise returns -1 if no mismatch is found.
    mismatch(double[] a, double[] b)Finds and returns the index of the first mismatch between two double arrays; otherwise, returns -1 if no mismatch is found.
    mismatch(double[] a, int aFromIndex, int aToIndex, double[] b, int bFromIndex, int bToIndex)Finds and returns the relative index of the first mismatch between two double arrays over the specified ranges; otherwise, returns -1 if no mismatch is found.
    mismatch(float[] a, float[] b)Finds and returns the index of the first mismatch between two float arrays; otherwise, returns -1 if no mismatch is found.
    mismatch(float[] a, int aFromIndex, int aToIndex, float[] b, int bFromIndex, int bToIndex)Finds and returns the relative index of the first mismatch between two float arrays over the specified ranges; otherwise, returns -1 if no mismatch is found.
    mismatch(int[] a, int[] b)Finds and returns the index of the first mismatch between two int arrays; otherwise, returns -1 if no mismatch is found.
    mismatch(int[] a, int aFromIndex, int aToIndex, int[] b, int bFromIndex, int bToIndex)Finds and returns the relative index of the first mismatch between two int arrays over the specified ranges, otherwise returns -1 if no mismatch is found.
    mismatch(long[] a, int aFromIndex, int aToIndex, long[] b, int bFromIndex, int bToIndex)Finds and returns the relative index of the first mismatch between two long arrays over the specified ranges; otherwise, returns -1 if no mismatch is found.
    mismatch(long[] a, long[] b)Finds and returns the index of the first mismatch between two long arrays; otherwise, returns -1 if no mismatch is found.
    mismatch(short[] a, int aFromIndex, int aToIndex, short[] b, int bFromIndex, int bToIndex)Finds and returns the relative index of the first mismatch between two short arrays over the specified ranges; otherwise, returns -1 if no mismatch is found.
    mismatch(short[] a, short[] b)Finds and returns the index of the first mismatch between two short arrays; otherwise, returns -1 if no mismatch is found.
    mismatch(Object[] a, int aFromIndex, int aToIndex, Object[] b, int bFromIndex, int bToIndex)Finds and returns the relative index of the first mismatch between two Object arrays over the specified ranges, otherwise returns -1 if no mismatch is found.
    mismatch(Object[] a, Object[] b)Finds and returns the index of the first mismatch between two Object arrays; otherwise, returns -1 if no mismatch is found.
    mismatch(T[] a, int aFromIndex, int aToIndex, T[] b, int bFromIndex, int bToIndex, Comparator<? super T> cmp)Finds and returns the relative index of the first mismatch between two Object arrays over the specified ranges, otherwise returns -1 if no mismatch is found.
    mismatch(T[] a, T[] b, Comparator<? super T> cmp)Finds and returns the index of the first mismatch between two Object arrays; otherwise, returns -1 if no mismatch is found.
    Parallel ArrayparallelPrefix(double[] array, int fromIndex, int toIndex, DoubleBinaryOperator op)Performs parallelPrefix(double[], DoubleBinaryOperator) for the given subrange of the array.
    parallelPrefix(double[] array, DoubleBinaryOperator op)Cumulates, in parallel, each element of the given array in place, using the supplied function.
    parallelPrefix(int[] array, int fromIndex, int toIndex, IntBinaryOperator op)Performs parallelPrefix(int[], IntBinaryOperator) for the given subrange of the array.
    parallelPrefix(int[] array, IntBinaryOperator op)Cumulates, in parallel, each element of the given array in place, using the supplied function.
    parallelPrefix(long[] array, int fromIndex, int toIndex, LongBinaryOperator op)Performs parallelPrefix(long[], LongBinaryOperator) for the given subrange of the array.
    parallelPrefix(long[] array, LongBinaryOperator op)Cumulates, in parallel, each element of the given array in place, using the supplied function.
    parallelPrefix(T[] array, int fromIndex, int toIndex, BinaryOperator<T> op)Performs parallelPrefix(Object[], BinaryOperator) for the given subrange of the array.
    parallelPrefix(T[] array, BinaryOperator<T> op)Cumulates, in parallel, each element of the given array in place, using the supplied function.
    parallelSetAll(double[] array, IntToDoubleFunction generator)Set all elements of the specified array, in parallel, using the provided generator function to compute each element.
    parallelSetAll(int[] array, IntUnaryOperator generator)Set all elements of the specified array, in parallel, using the provided generator function to compute each element.
    parallelSetAll(long[] array, IntToLongFunction generator)Set all elements of the specified array, in parallel, using the provided generator function to compute each element.
    parallelSetAll(T[] array, IntFunction<? extends T> generator)Set all elements of the specified array, in parallel, using the provided generator function to compute each element.
    parallelSort(byte[] a)Sorts the specified array into ascending numerical order.
    parallelSort(byte[] a, int fromIndex, int toIndex)Sorts the specified range of the array into ascending numerical order.
    parallelSort(char[] a)Sorts the specified array into ascending numerical order.
    parallelSort(char[] a, int fromIndex, int toIndex)Sorts the specified range of the array into ascending numerical order.
    parallelSort(double[] a)Sorts the specified array into ascending numerical order.
    parallelSort(double[] a, int fromIndex, int toIndex)Sorts the specified range of the array into ascending numerical order.
    parallelSort(float[] a)Sorts the specified array into ascending numerical order.
    parallelSort(float[] a, int fromIndex, int toIndex)Sorts the specified range of the array into ascending numerical order.
    parallelSort(int[] a)Sorts the specified array into ascending numerical order.
    parallelSort(int[] a, int fromIndex, int toIndex)Sorts the specified range of the array into ascending numerical order.
    parallelSort(long[] a)Sorts the specified array into ascending numerical order.
    parallelSort(long[] a, int fromIndex, int toIndex)Sorts the specified range of the array into ascending numerical order.
    parallelSort(short[] a)Sorts the specified array into ascending numerical order.
    parallelSort(short[] a, int fromIndex, int toIndex)Sorts the specified range of the array into ascending numerical order.
    parallelSort(T[] a)Sorts the specified array of objects into ascending order, according to the natural ordering of its elements.
    parallelSort(T[] a, int fromIndex, int toIndex)Sorts the specified range of the specified array of objects into ascending order, according to the natural ordering of its elements.
    parallelSort(T[] a, int fromIndex, int toIndex, Comparator<? super T> cmp)Sorts the specified range of the specified array of objects according to the order induced by the specified comparator.
    parallelSort(T[] a, Comparator<? super T> cmp)Sorts the specified array of objects according to the order induced by the specified comparator.
    SetsetAll(double[] array, IntToDoubleFunction generator)Set all elements of the specified array, using the provided generator function to compute each element.
    setAll(int[] array, IntUnaryOperator generator)Set all elements of the specified array, using the provided generator function to compute each element.
    setAll(long[] array, IntToLongFunction generator)Set all elements of the specified array, using the provided generator function to compute each element.
    setAll(T[] array, IntFunction<? extends T> generator)Set all elements of the specified array, using the provided generator function to compute each element.

    Arrays Class Method Example

    Let’s see some commonly used methods of the Java Arrays class.

    1. Sorting an Array by Using the sort() Method

    Example

    1. import java.util.Arrays;  
    2. public class Main {  
    3.     public static void main(String[] args) {  
    4.         int[] numbers = {5, 2, 8, 1, 3};         
    5.         Arrays.sort(numbers);         
    6.         System.out.println(“Sorted Array: ” + Arrays.toString(numbers));  
    7.     }  
    8. }  

    Compile and Run

    Output:

    Sorted Array: [1, 2, 3, 5, 8]

    When sorting in descending order, apply Arrays.sort() along with Collections.reverseOrder() treatment to Integer[] arrays.

    2. Comparing Two Arrays by Using the equals() Method

    Example

    1. import java.util.Arrays;  
    2. public class Main {  
    3.    public static void main(String[] args) {  
    4.        int[] num1 = {6, 7, 8};  
    5.        int[] num2 = {6, 7, 8};  
    6.        System.out.println(Arrays.equals(num1, num2));  
    7.    }  
    8. }  

    Compile and Run

    Output:

    true

    3. Searching an Array by Using the binarySearch() Method

    Example

    1. import java.util.Arrays;  
    2. public class Main {  
    3.     public static void main(String[] args) {  
    4.         int[] numbers = {1, 3, 5, 7, 9};  
    5.         int index = Arrays.binarySearch(numbers, 5);  
    6.         System.out.println(“Index of 5 is: ” + index);  
    7.     }  
    8. }  

    Compile and Run

    Output:

    Index of 5 is: 2

    Note: The array must be sorted before using the binarySearch() method; otherwise, the results will be unpredictable.

    4. Filling an Array by Using the fill() Method

    Example

    1. import java.util.Arrays;  
    2. public class Main {  
    3.     public static void main(String[] args) {  
    4.         int[] arr = new int[5];  
    5.         Arrays.fill(arr, 10)  
    6.         System.out.println(“Filled Array: ” + Arrays.toString(arr));  
    7.     }  
    8. }  

    Output:

    Filled Array: [10, 10, 10, 10, 10]

    5. Copying an Array by Using the copyOf() Method

    Example

    1. import java.util.Arrays;  
    2. public class Main{  
    3.     public static void main(String[] args) {  
    4.         int[] original = {1, 2, 3, 4, 5};  
    5.         int[] copied = Arrays.copyOf(original, 3);  
    6.         System.out.println(“Copied Array: ” + Arrays.toString(copied));  
    7.     }  
    8. }  

    Compile and Run

    Output:

    Copied Array: [1, 2, 3]

    6. Converting an Array by Using the toString() Method

    Example

    1. import java.util.Arrays;  
    2. public class Main {  
    3.     public static void main(String[] args) {  
    4.         String[] names = {“Alice”, “Bob”, “Charlie”}  
    5.         System.out.println(“Array as String: ” + Arrays.toString(names));  
    6.     }  
    7. }  

    Output:

    Array as String: [Alice, Bob, Charlie]

    7. Comparing Two-Dimensional Arrays by Using the deepEquals() Method

    Example

    1. import java.util.Arrays;  
    2. public class Main {  
    3.    public static void main(String[] args) {  
    4.        int[][] numbers = {{4, 8, 0}, {9, 5, 1}, {7, 2, 6}};  
    5.        int[][] numbersCopy = Arrays.copyOf(numbers, numbers.length);  
    6.        System.out.println(“Are the given arrays equal to each other?”);  
    7.        System.out.println(Arrays.deepEquals(numbers, numbersCopy));  
    8.        System.out.println(Arrays.deepToString(numbersCopy));  
    9.    }  
    10. }  

    Compile and Run

    Output:

    Are the given arrays equal to each other?
    true
    [[4, 8, 0], [9, 5, 1], [7, 2, 6]]
    
  • Array Programs in Java

    In Java, an array is a linear data structure that has a collection of the same data type. These elements are stored in a contiguous memory location. In this section, we will discuss a variety of array programs, including array operations, manipulation, sorting, searching, etc.

    1. Java program to find the sum of the array elements.

    To find the sum of the array’s elements, first we have defined and declared an array. After that, we have defined a sum() method that adds array elements. Inside this method, the loop iterates over each element of the array and adds an element to the sum variable, repeatedly. In the main() method, we have called the sum() method that returns the sum of the array elements.

    Example

    1. class Main {  
    2.     static int arr[] = { 7, 4, 10, 9, 13, 26 };  
    3.     // method for the sum of elements   
    4.     static int sum()  
    5.     {  
    6.         int i, sum = 0;   
    7.         // Iterate through all elements and add them to the sum  
    8.         for (i = 0; i < arr.length; i++)  
    9.             sum += arr[i];  
    10.         return sum;  
    11.     }  
    12.     public static void main(String[] args)  
    13.     {  
    14.         System.out.println(“The sum of the given array is: “+ sum());  
    15.     }  
    16. }  

    Compile and Run

    Output:

    The sum of the given array is: 69

    2. Java program to find the reverse of an array.

    Reversing an array means writing an array from the last element to the first element. First, we have initializead an array. The loop iterates over the array until the array is reversed. We swap the first element with the last, the second with the second last, and so on. At last, we convert the array into a string and print the reversed array.

    Example

    1. import java.util.Arrays;  
    2. public class Main {  
    3.     public static void main(String[] args) {       
    4.         int[] arr = {1, 2, 3, 4, 5};  
    5.         // Swap elements from start to end  
    6.         for (int i = 0; i < arr.length / 2; i++) {  
    7.             int t = arr[i];  
    8.             arr[i] = arr[arr.length – 1 – i];  
    9.             arr[arr.length – 1 – i] = t;  
    10.         }  
    11.         System.out.println(“” + Arrays.toString(arr));  
    12.     }  
    13. }  

    Compile and Run

    Output:

    [5, 4, 3, 2, 1]

    3. Java program to merge two arrays.

    There are various ways to merge two arrays. But in this program, we have used user-defined logic to merge two arrays. This method is useful when we need full control over the merging process without relying on built-in functions. It directly merges the arrays.

    Example

    1. import java.util.Arrays;  
    2. public class Main {  
    3.     public static void main(String[] args) {  
    4.         int arr1[] = { 23, 45, 56, 78, 90};  
    5.         int arr2[] = { 3, 4, 6, 8, 9, 0, 7};  
    6.         // determining the length of both arrays  
    7.         int sizearr1 = arr1.length;  
    8.         int sizearr2 = arr2.length;  
    9.         // resultant array size  
    10.         int sizearr3 = sizearr1 + sizearr2;  
    11.         // Creating a new array   
    12.         int[] arr3 = new int[sizearr3];  
    13.         // Loop to store the elements of the first array into the resultant array  
    14.         for (int i = 0; i < sizearr1; i = i + 1) {    
    15.             // Storing the elements in the resultant array  
    16.             arr3[i] = arr1[i];  
    17.         }  
    18.         // Loop to concatenate the elements of the second array into the resultant array  
    19.         for (int i = 0; i < sizearr2; i = i + 1) {  
    20.             // Storing the elements in the resultant array  
    21.             arr3[sizearr1 + i] = arr2[i];  
    22.         }  
    23.         System.out.println(“” + Arrays.toString(arr3));  
    24.     }  
    25. }  

    Compile and Run

    Output:

    [23, 45, 56, 78, 90, 3, 4, 6, 8, 9, 0, 7]

    4. Java program to find the second most significant element in a sorted matrix.

    In a sorted matrix, the rows and columns of the elements are placed in ascending order. We can navigate the matrix and note the largest and second-largest elements to determine the second-largest element. The second-largest element will have been stored when the traverse is complete.

    The program uses a simple approach to find the second-largest element in a sorted matrix. It applies a nested loop to traverse the matrix in reverse order and compares each element with the largest and second-largest elements found so far. The program updates the largest and second-largest variables accordingly. Finally, it prints the value of the second-largest element.

    Example

    1. public class Main  
    2. {    
    3.     public static void main(String[] args)     
    4.     {    
    5.         int[][] matrix =     
    6.         {    
    7.             {1,2,3},    
    8.             {4,5,6},    
    9.             {7,8,9}    
    10.         };    
    11.         int rows=matrix.length;    
    12.         int cols=matrix[0].length;    
    13.         int largest=matrix[rows-1][cols-1]; // Initialize largest with the bottom-right element    
    14.         int secondLargest=matrix[rows-1][cols-2]; // Initialize secondLargest with the element before largest    
    15.             
    16.         // Traverse the matrix in reverse order    
    17.         for (int i=rows-1;i>=0;i–)     
    18.         {    
    19.             for (int j=cols-1;j>=0;j–)     
    20.             {    
    21.                 if (matrix[i][j]>largest)     
    22.                 {    
    23.                     secondLargest=largest; // Update secondLargest to the previous largest    
    24.                     largest=matrix[i][j]; // Update largest to the new largest element    
    25.                 }     
    26.               else if(matrix[i][j]>secondLargest&&matrix[i][j]<largest)     
    27.                 {    
    28.                     secondLargest=matrix[i][j];     
    29.                 }    
    30.             }    
    31.         }    
    32.         System.out.println(“Second largest element in the sorted matrix is: “+secondLargest);    
    33.     }    
    34. }    

    Compile and Run

    Output:

    Second largest element in the sorted matrix is: 8

    Complexity Analysis

    Time Complexity: O(rows * cols), where rows and cols are the dimensions of the matrix.

    Space Complexity: O(1), as we use constant additional space.

    5. Java program to find the k-th smallest element in a sorted matrix.

    In a sorted matrix, elements are arranged in ascending order, both row-wise and column-wise. The task is to find the kth smallest element in the matrix.

    The program uses a min-heap implemented with a PriorityQueue to find the kth smallest element in a sorted matrix. The findKthSmallest() method initializes the minHeap and adds the elements from the first column. It then performs k-1 iterations, extracting the minimum element, finding its indices, and adding the next element from the same row to the minHeap. Finally, the method returns the kth smallest element. The main function showcases the method by providing a sample matrix and k value.

    Example

    1. import java.util.*;    
    2. public class Main    
    3. {    
    4.     public static int findKthSmallest(int[][] matrix,int k)     
    5.     {    
    6.         int rows=matrix.length;    
    7.         int cols=matrix[0].length;    
    8.         PriorityQueue<Integer> minHeap=new PriorityQueue<>();    
    9.         for (int i=0;i<rows;i++) {    
    10.             minHeap.add(matrix[i][0]);    
    11.         }    
    12.         // Perform k-1 iterations    
    13.         for (int i=0;i<k-1;i++)     
    14.         {    
    15.             int minElement=minHeap.poll(); // Extract the minimum element    
    16.             // Get the row and column index of the extracted element    
    17.             int rowIndex=-1;    
    18.             int colIndex=-1;    
    19.             for (int j=0;j<rows;j++)     
    20.             {    
    21.                 for (int p=0;p<cols;p++)     
    22.                 {    
    23.                     if (matrix[j][p]==minElement)     
    24.                     {    
    25.                         rowIndex=j;    
    26.                         colIndex=p+1;    
    27.                         break;    
    28.                     }    
    29.                 }    
    30.             }    
    31.             // Add the next element from the same row to the min-heap    
    32.             if (colIndex<cols) {    
    33.                 minHeap.add(matrix[rowIndex][colIndex]);    
    34.             }    
    35.         }    
    36.         return minHeap.peek(); // Return the kth smallest element    
    37.     }    
    38.     public static void main(String[] args)     
    39.     {    
    40.         int[][] matrix={    
    41.             {1,3,5},    
    42.             {6,7,12},    
    43.             {11,14,14}    
    44.         };    
    45.         int k=4;    
    46.         int kthSmallest=findKthSmallest(matrix,k);    
    47.         System.out.println(“The “+ k+”-th smallest element in the sorted matrix is: “+kthSmallest);    
    48.     }    
    49. }    

    Compile and Run

    Output:

    The 4-th smallest element in the sorted matrix is: 6

    Complexity Analysis

    Time Complexity: The time complexity is O(k * log(rows)).

    Space Complexity: The space complexity is O(rows) for storing the elements in the min-heap.

    6. Java program to remove duplicate elements from a sorted array.

    In a sorted array, duplicate elements may occur consecutively. To put off duplicates from a looked-after array, we need to adjust the array in-place, making sure that each detail appears as effective as soon as. The Java program removes duplicates from a sorted array using the “RemoveDuplicates” class. The method “removeDuplicates” returns the new length of the modified array without duplicates. It checks if the array is empty, initializes “nextUnique” to 1, and traverses the array starting from the second element. It assigns unique elements to the position of “nextUnique” and increments it. After the loop, “nextUnique” represents the new length. The “main” function showcases the method by printing the modified array.

    Example

    1. import java.util.*;    
    2. public class Main    
    3. {    
    4.     public static int removeDuplicates(int[] nums)     
    5.     {    
    6.         int n=nums.length;    
    7.         if (n==0)     
    8.         {    
    9.             return 0;     
    10.         }    
    11.         int nextUnique=1;     
    12.         // Pointer to track the position of the next unique element    
    13.         // Traverse the array starting from the second element    
    14.         for (int current=1;current<n;current++)     
    15.         {    
    16.             // Compare the current element with the element at the next unique – 1    
    17.             if (nums[current]!=nums[nextUnique-1])     
    18.             {    
    19.    nums[nextUnique]=nums[current]; // Assign current element to nextUnique position    
    20.                 nextUnique++; // Increment nextUnique    
    21.             }    
    22.         }    
    23.         return nextUnique;     
    24.     }    
    25.     public static void main(String[] args)     
    26.     {    
    27.         int[] nums={1,1,2,2,3,4,4,5};    
    28.         int length=removeDuplicates(nums);    
    29.         System.out.print(“Modified Array: “);    
    30.         for (int i=0;i<length;i++)     
    31.         {    
    32.             System.out.print(nums[i]+” “);    
    33.         }    
    34.     }    
    35. }    

    Compile and Run

    Output:

    Modified Array: 1 2 3 4 5

    Complexity Analysis

    Time Complexity is O(n), where n is the array’s element count.

    Space complexity is O(1) since the array is modified directly without additional data structures.

    7. Java program to find the frequency of each word in a string array.

    We shall calculate the frequency of each word in a string array using a Java program. In a list of strings, we want to know how frequently each word appears. To calculate the frequency of each word in a string array, the program employs a hash map.

    A simple approach separates each string into words, and the number of each word is then saved in the hash map. After initializing a blank HashMap, the program loops through each string in the array. It determines if a word is present in the HashMap for each one it encounters.

    If it does, the frequency increases; if not, it is set to 1, and the word is added to the hash map. Finally, the program prints the word-frequency pairs stored in the HashMap. The approach efficiently tracks and counts the occurrences of each word, allowing for accurate frequency analysis of the words in the string array.

    Example

    1. import java.util.*;    
    2. public class Main   
    3. {    
    4.     public static void main(String[] args)     
    5.     {    
    6.         String[] strings={“Hello world”,”Hello Java”,”Java is great”,”Java is powerful”};         // Create a HashMap to store word-frequency pairs    
    7.         Map<String,Integer> frequencyMap=new HashMap<>();    
    8.         for (String str:strings)     
    9.         {    
    10.             // Split the string into words using whitespace as the delimiter    
    11.             String[] words=str.split(“\\s+”);    
    12.             // Count the occurrences of each word    
    13.             for (String word:words)     
    14.             {    
    15.                 // Check if the word already exists in the HashMap    
    16.                 if (frequencyMap.containsKey(word))     
    17.                 {    
    18.                     // If it exists, increment its frequency by 1    
    19.                     frequencyMap.put(word,frequencyMap.get(word)+1);    
    20.                 } else {    
    21.                     // If it does not exist, add it to the HashMap with a frequency of 1    
    22.                     frequencyMap.put(word,1);    
    23.                 }    
    24.             }    
    25.         }    
    26.         // Print the word-frequency pairs    
    27.         for (Map.Entry<String, Integer> entry : frequencyMap.entrySet()) {    
    28.             System.out.println(“Word: ” + entry.getKey() + “, Frequency: ” + entry.getValue());    
    29.         }    
    30.     }    
    31. }    

    Compile and Run

    Output:

    Word: Java, Frequency: 3
    Word: world, Frequency: 1
    Word: Hello, Frequency: 2
    Word: powerful, Frequency: 1
    Word: is, Frequency: 2
    Word: great, Frequency: 1
    

    Complexity Analysis

    The time complexity is O(n*m), where n represents the number of strings within the array and m is the maximum common sort of phrase in every string.

    The space complexity of the program is O(n), where n is the total wide variety of words inside the array.

    8. Java program to find the missing number in a sorted array of consecutive integers.

    Using the binary search method, we locate the missing integer in a sorted array of succeeding integers. The first detail’s index is low, and the remaining is high. We determine whether or not the missing integer is on the left or proper side of the array by computing the expected value for the middle element, which ought to be the same as the first element plus the centre index. The operation is repeated until there is only one element left in the search space, at which point we update low or high as necessary. The missing number will be the expected value at the index low.

    Example

    1. public class Main   
    2. {    
    3.     public static int findMissingNumber(int[] nums)     
    4.     {    
    5.         int low=0;    
    6.         int high=nums.length-1;    
    7.         // Perform binary search    
    8.         while (low<=high)     
    9.         {    
    10.             int mid=low+(high-low)/2;    
    11.             int expectedValue=nums[0]+mid;    
    12.             if (nums[mid]==expectedValue)     
    13.             {    
    14.                 // Missing number lies in the right half    
    15.                 low=mid+1;    
    16.             } else     
    17.             {    
    18.                 // Missing number lies in the left half    
    19.                 high=mid-1;    
    20.             }    
    21.         }    
    22.         // Return the missing number    
    23.         return nums[0]+low;    
    24.     }    
    25.     public static void main(String[] args)     
    26.     {    
    27.         int[] nums={1,2,3,4,6,7,8,9};    
    28.         int missingNumber=findMissingNumber(nums);    
    29.         System.out.println(“Missing number: “+missingNumber);    
    30.     }    
    31. }    

    Compile and Run

    Output:

    Missing number: 5

    Complexity Analysis

    Time Complexity: The binary search approach has a time complexity of O(log n), where n is the size of the array

    Space Complexity: The program has a space complexity of O(1), only using a few variables to track the low, high, and mid indices and the expected value.

    9. Java program to find the element that appears only once in an array.

    The technique used to find the element that appears most effectively at least once in an array is primarily based on the XOR operation. By XORing all the factors within the array, the factors that seem a fair number of instances will cancel out, leaving only the detail that appears best once. To enforce this approach, we initialize a variable ‘unique’ to zero. Then, we iterate through each detail inside the array and XOR it with the ‘particular’ variable. The result is stored back in ‘unique.’ At the end of the iteration, ‘unique’ will hold the element’s value that appears only once.

    Example

    1. public class Main     
    2. {    
    3.     public static int findUnique(int[] nums)     
    4.     {    
    5.         int unique=0;    
    6.         for (int num:nums)     
    7.         {    
    8.             unique^=num; // XOR the current element with ‘unique’    
    9.         }    
    10.         return unique;    
    11.     }    
    12.     
    13.     public static void main(String[] args)     
    14.     {    
    15.         int[] nums = {1,2,3,4,3,2,1};    
    16.         int uniqueElement=findUnique(nums);    
    17.         System.out.println(“The element that appears only once: ” + uniqueElement);    
    18.     }    
    19. }    

    Compile and Run

    Output:

    The element that appears only once: 4

    Complexity Analysis

    Time Complexity: The time complexity of this technique is O(n), where n is the length of the array.

    Space Complexity: The Space complexity is O(1) because we simplest use a single variable to keep the result.

    10. Java program to check if an array is a palindrome.

    To check if an array is a palindrome, we will use a pointer method where one pointer starts evolving at the start of the array and the alternative at the end. The elements are as compared to those suggestions, and we move them closer and nearer collectively until they meet at the centre. We conclude that the array is not a palindrome if the elements at any point at the pointers are not equal. Otherwise, if the loop completes without finding any unequal elements, then the array is a palindrome. The two-pointer approach allows us to efficiently check for palindromicity by eliminating the need for additional space.

    Example

    1. public class Main  
    2. {    
    3.     public static boolean isPalindrome(int[] nums)     
    4.     {    
    5.         int left=0;                     // Initialize the left pointer at the beginning of the array    
    6.         int right=nums.length-1;      // Initialize the right pointer at the end of the array    
    7. while (left<=right) {      // Continue the loop until the pointers meet or cross each other    
    8.  if (nums[left]!=nums[right])     
    9. {    
    10.    return false;             // If the elements at the pointers are not equal, the array is not a palindrome    
    11.             }    
    12.             left++;                           
    13.             right–;                          
    14.         }    
    15.  return true;    // If the loop completes without finding unequal elements, the array is a palindrome    
    16.     }    
    17.     public static void main(String[] args) {    
    18.         int[] nums={1,2,3,2,1};       
    19.         boolean isPalindrome=isPalindrome(nums);      
    20.         if (isPalindrome)     
    21.        {    
    22.             System.out.println(“The array is a palindrome.”);    
    23.         }     
    24.        else     
    25.        {    
    26.             System.out.println(“The array is not a palindrome.”);    
    27.         }    
    28.     }    
    29. }  

    Compile and Run

    Output:

    The array is a palindrome.

    Complexity Analysis

    The time complexity of the above approach is O(n), where n is the length of the array.

    The space complexity is O(1) as we are not using any extra space.

    11. Java program to shuffle elements of an array.

    To shuffle the elements of an array, we use the Fisher-Yates shuffle algorithm is commonly used. The procedure ensures that each array’s item is randomly permuted. Starting with the final entry in the array, the process iterates through the array in reverse order to get started. Each time, the current element is added to the range of the remaining unshrunk elements to create a random index. The element at the current index is then swapped with the element at the randomly generated index. The swapping continues until the first element is reached, resulting in a shuffled array with elements in random order.

    Example

    1. import java.util.Random;    
    2. public class Main     
    3. {    
    4.     public static void shuffle(int[] nums)     
    5.     {    
    6.         Random rand=new Random();    
    7.         for (int i=nums.length-1;i>=1;i–)     
    8.         {    
    9.             int j=rand.nextInt(i+1);    
    10.             // Swap the current element with the randomly selected element    
    11.             int temp=nums[i];    
    12.             nums[i]=nums[j];    
    13.             nums[j]=temp;    
    14.         }    
    15.     }    
    16.     public static void main(String[] args)     
    17.     {    
    18.         int[] nums = {1,2,3,4,5};    
    19.         System.out.println(“Original array: “);    
    20.         for (int num:nums)     
    21.       {    
    22.             System.out.print(num + ” “);    
    23.         }    
    24.         shuffle(nums);    
    25.         System.out.println(“\nShuffled array: “);    
    26.         for (int num:nums)     
    27.       {    
    28.             System.out.print(num + ” “);    
    29.         }    
    30.     }    
    31. }    

    Compile and Run

    Output:

    Original array:
    1 2 3 4 5
    Shuffled array:
    5 2 1 3 4
    

    Complexity Analysis

    The time complexity of this technique is O(N), where N is the size of the array.

    The space complexity is O(1) since we use a consistent quantity of extra space for the random variety.

    12. Java program to check if two matrices are orthogonal.

    To examine if two matrices are orthogonal, we evaluate the dot manufactured of corresponding rows or columns of the matrices. The matrices are said to be orthogonal if the dot product is 0 for all pairs. The algorithm iterates through the rows or columns, then calculates the dot product and returns false if any dot product is non-zero. It then checks for appropriate dimensions. If all dot products are zero, it returns true to indicate that the matrices are orthogonal.

    Example

    1. public class Main    
    2. {    
    3.     public static boolean areMatricesOrthogonal(int[][] matrix1,int[][] matrix2)     
    4. {    
    5.         int rows1=matrix1.length;    
    6.         int cols1=matrix1[0].length;    
    7.         int rows2=matrix2.length;    
    8.         int cols2=matrix2[0].length;    
    9.         // Check if matrices have compatible dimensions    
    10.         if (rows1 != rows2 || cols1 != cols2) {    
    11.             return false;    
    12.         }    
    13.         // Check the dot product for each row/column pair    
    14.         for (int i=0;i<rows1;i++) {    
    15.             int dotProduct = 0;    
    16.             for (int j=0;j<cols1;j++) {    
    17.                 dotProduct += matrix1[i][j] * matrix2[i][j];    
    18.             }    
    19.             if (dotProduct!=0)     
    20.             {    
    21.                 return false;    
    22.             }    
    23.         }    
    24.         return true;    
    25.     }    
    26.     public static void main(String[] args) {    
    27.         int[][] matrix1={{1,2},{3,4}};    
    28.         int[][] matrix2={{0,1},{-1,0}};    
    29.             
    30.         boolean areOrthogonal = areMatricesOrthogonal(matrix1, matrix2);    
    31.         if (areOrthogonal) {    
    32.             System.out.println(“The matrices are orthogonal.”);    
    33.         } else {    
    34.             System.out.println(“The matrices are not orthogonal.”);    
    35.         }    
    36.     }    
    37. }    

    Compile and Run

    Output:

    The matrices are not orthogonal.

    Complexity Analysis:

    The time complexity of this technique is O(n), where n is the range of rows or columns in the matrices.

    The space complexity is O(1), as no additional data structures are used.

    13. Java program to find the maximum element in a two-dimensional array.

    We initialize the variable ‘ max’ with the smallest value conceivable given the data type of the array elements to determine the greatest element in a two-dimensional array. The next step is to loop separately via the array’s rows and factors. Every element is compared to the modern fee of “max,” and if the detail is more, “max” is up to date. The maximum element in the two-dimensional array will be contained in ‘max’ once all items have been iterated through. By comparing each element to the current maximum value, the method enables us to determine the maximum element quickly.

    Example

    1. public class Main  
    2. {    
    3.     public static int findMaximumElement(int[][] array) {    
    4.         int max=Integer.MIN_VALUE; // Initialize max with the minimum value    
    5.         for (int i=0;i<array.length;i++)     
    6.         {    
    7.             // Iterate through each element of the row    
    8.             for (int j=0;j<array[i].length;j++)     
    9.             {    
    10.                 // Compare the current element with the current max value    
    11.                 if (array[i][j] > max) {    
    12.                     max=array[i][j];     
    13.                 }    
    14.             }    
    15.         }    
    16.         return max; // Return the maximum element    
    17.     }    
    18.     public static void main(String[] args) {    
    19.         int[][] array={    
    20.             {1, 2, 3},    
    21.             {4, 5, 6},    
    22.             {7, 8, 9}    
    23.         };    
    24.         int maximum=findMaximumElement(array);    
    25.         System.out.println(“The maximum element in the array is: “+maximum);    
    26.     }    
    27. }    

    Compile and Run

    Output:

    The maximum element in the array is: 9

    Complexity Analysis

    The time complexity of this approach is O(n * m), where n is the number of rows and m is the number of columns in the two-dimensional array.

    The space complexity is O(1) when you consider that we are not the usage of any extra area that grows with the entered size.

    14. Java program to find the sum of each diagonal in a matrix.

    To find the sum of each diagonal in a matrix, we iterate through the elements and calculate the diagonal index of every component by summing its row and column indices. We then add the element’s value to the corresponding diagonal sum in an array. After processing all elements, the array will contain the sum of each diagonal.

    Example

    1. public class Main {    
    2.     public static int[] getDiagonalSums(int[][] matrix) {    
    3.         int rows=matrix.length;    
    4.         int cols=matrix[0].length;    
    5.         int numDiagonals=rows+cols-1;    
    6.         int[] sums=new int[numDiagonals];    
    7.         for (int i=0;i<rows;i++)   {    
    8.             for (int j=0;j<cols;j++)    {    
    9.                 int diagonalIndex=i+j;    
    10.                 sums[diagonalIndex]+=matrix[i][j];    
    11.             }    
    12.         }    
    13.         return sums;    
    14.     }    
    15.     public static void main(String[] args) {    
    16.         int[][] matrix={    
    17.             {1, 2, 3},    
    18.             {4, 5, 6},    
    19.             {7, 8, 9}    
    20.         };    
    21.         int[] diagonalSums=getDiagonalSums(matrix);    
    22.         System.out.println(“Sum of each diagonal:”);    
    23.         for (int sum:diagonalSums)  {    
    24.             System.out.println(sum);    
    25.         }    
    26.     }    
    27. }    

    Compile and Run

    Output:

    Sum of each diagonal:
    1
    6
    15
    14
    9
    

    Complexity Analysis

    The approach has a time complexity of O(m*n), where m is the number of rows and n is the number of columns in the matrix.

    The space complexity is O(m + n), as we must store the diagonal sums in an array.

    15. Java program to find the element with the maximum frequency in an array.

    We use a HashMap to record the frequency of each element in the array to locate the element with the highest frequency. The element with the highest frequency can be recognized via looping through the array and updating the frequency within the hash map. Then, by comparing the frequency counts in the HashMap, we identify the element with the maximum frequency. The approach allows us to efficiently find the element with the highest frequency in the array.

    Example

    1. import java.util.*;  
    2. public class Main {  
    3.     public static int findMaxFrequencyElement(int[] nums) {  
    4.         Map<Integer, Integer> frequencyMap = new HashMap<>();  
    5.         for (int num : nums) {  
    6.             frequencyMap.put(num, frequencyMap.getOrDefault(num, 0) + 1);  
    7.         }  
    8.         return Collections.max(frequencyMap.entrySet(), Map.Entry.comparingByValue()).getKey();  
    9.     }  
    10.     public static void main(String[] args) {  
    11.         int[] nums = {1, 2, 3, 2, 1, 2, 3, 3, 3};  
    12.         System.out.println(“Element with maximum frequency is: ” + findMaxFrequencyElement(nums));  
    13.     }  
    14. }  

    Compile and Run

    Output:

    Element with maximum frequency is: 3

    Complexity Analysis

    The time complexity of this technique is O(n), where n is the size of the array.

    The area complexity is O(n) because a HashMap can save up to n unique elements in the worst case.

    16. Java program to rotate a two-dimensional array clockwise.

    To rotate a two-dimensional array clockwise, we can follow a two-step approach: transposing the array and reversing each row. First, we iterate via the array and switch each detail at function (i, j) with the detail at the role (j, i), then successfully transpose the array. After, we iterate through each row of the transposed array and reverse it by swapping the elements from the start and end of the row until they meet in the middle. The process rotates the array clockwise.

    Example

    1. public class Main  {    
    2.     public static void rotateClockwise(int[][] matrix)  {    
    3.         int rows=matrix.length;    
    4.         int cols=matrix[0].length;    
    5.         // Transpose the array    
    6.         for (int i=0;i<rows;i++)    {    
    7.             for (int j=i;j<cols;j++)   {    
    8.                 int temp=matrix[i][j];    
    9.                 matrix[i][j]=matrix[j][i];    
    10.                 matrix[j][i]=temp;    
    11.             }    
    12.         }    
    13.         // Reverse each row    
    14.         for (int i=0;i<rows;i++)   {    
    15.             int left=0;    
    16.             int right=cols-1;    
    17.             while (left<right)    {    
    18.                 int temp=matrix[i][left];    
    19.                 matrix[i][left]=matrix[i][right];    
    20.                 matrix[i][right]=temp;    
    21.                 left++;    
    22.                 right–;    
    23.             }    
    24.         }    
    25.     }    
    26.     public static void main(String[] args) {    
    27.         int[][] matrix = {    
    28.             {1, 2, 3},    
    29.             {4, 5, 6},    
    30.             {7, 8, 9}    
    31.         };    
    32.         System.out.println(“Original Matrix:”);    
    33.         printMatrix(matrix);    
    34.         rotateClockwise(matrix);    
    35.         System.out.println(“Rotated Matrix:”);    
    36.         printMatrix(matrix);    
    37.     }    
    38.     public static void printMatrix(int[][] matrix) {    
    39.         int rows=matrix.length;    
    40.         int cols=matrix[0].length;    
    41.         for (int i=0;i<rows;i++)   {    
    42.             for (int j=0;j<cols;j++)       {    
    43.                 System.out.print(matrix[i][j]+” “);    
    44.             }    
    45.             System.out.println();    
    46.         }    
    47.         System.out.println();    
    48.     }    
    49. }   

    Compile and Run

    Output:

    Original Matrix:
    1 2 3
    4 5 6
    7 8 9
    
    Rotated Matrix:
    7 4 1
    8 5 2
    9 6 3
    

    Complexity Analysis

    The time complexity of this approach is O(n2), where n is the size of the array.

    The space complexity is O(1) as we carry out the rotation in-place without using any additional storage systems.

    17. Java program to sort a two-dimensional array across columns.

    We construct a custom comparator that compares rows based on the required column to sort a two-dimensional array across columns. The Arrays.sort() method is called with the custom comparator as an argument. The sorting algorithm employs a comparator to compare rows according to the selected column and arrange them correctly. We can quickly sort the two-dimensional array across columns using this method.

    Example

    1. import java.util.Arrays;    
    2. import java.util.Comparator;    
    3. public class Main {    
    4.     public static void sortByColumn(int[][] matrix, int column) {    
    5.         // Use Arrays.sort() with a custom comparator to sort the matrix by the specified column    
    6.         Arrays.sort(matrix,Comparator.comparingInt(row -> row[column]));    
    7.     }    
    8.     public static void main(String[] args) {    
    9.         int[][] matrix = {    
    10.             {13, 12, 11},    
    11.             {6, 5, 4},    
    12.             {19, 18, 17}    
    13.         };    
    14.         int columnToSortBy=1;    
    15.         System.out.println(“Original Matrix:”);    
    16.         printMatrix(matrix);    
    17.         sortByColumn(matrix,columnToSortBy);    
    18.         System.out.println(“Sorted Matrix by Column ” + columnToSortBy + “:”);    
    19.         printMatrix(matrix);    
    20.     }    
    21.     public static void printMatrix(int[][] matrix) {    
    22.         int rows=matrix.length;    
    23.         int cols=matrix[0].length;    
    24.         for (int i=0;i<rows;i++)   {    
    25.             for (int j=0;j<cols;j++)   {    
    26.                 System.out.print(matrix[i][j]+” “);    
    27.             }    
    28.             System.out.println();    
    29.         }    
    30.         System.out.println();    
    31.     }    
    32. }    

    Compile and Run

    Output:

    Original Matrix:
    13 12 11
    6 5 4
    19 18 17
    
    Sorted Matrix by Column 1:
    6 5 4
    13 12 11
    19 18 17
    

    Complexity Analysis

    The time complexity of this approach is O(n log n), where n is the number of rows in the matrix.

    The space complexity is O(1) since the sorting is done in place.

    18. Java program to perform matrix exponentiation to compute Fibonacci numbers efficiently.

    We might also describe the Fibonacci sequence as a matrix and calculate matrix multiplication to compute the Fibonacci numbers using matrix exponentiation speedily. The manner includes creating a transformation matrix that represents the Fibonacci series, utilizing matrix multiplication and exponentiation strategies, and then elevating the matrix to the necessary power using the powerMatrix approach. By deleting the Fibonacci number from the following matrix, we can also quickly calculate Fibonacci numbers.

    Example

    1. public class Main {    
    2.     public static long computeFibonacci(int n)   {    
    3.         if (n<=0)   {    
    4.             return 0;    
    5.         }    
    6.         // Fibonacci transformation matrix    
    7.         long[][] fibMatrix = {{1, 1}, {1, 0}};    
    8.         // Raise fibMatrix to the power of (n-1)    
    9.         fibMatrix = powerMatrix(fibMatrix, n – 1);    
    10.         // Extract the Fibonacci number from the matrix    
    11.         return fibMatrix[0][0];    
    12.     }    
    13.     private static long[][] powerMatrix(long[][] matrix, int power) {    
    14.         if (power == 0) {    
    15.             // Identity matrix    
    16.             return new long[][]{{1, 0}, {0, 1}};    
    17.         }    
    18.         if (power == 1) {    
    19.             return matrix;    
    20.         }    
    21.         long[][] result = powerMatrix(matrix, power / 2);    
    22.         result = multiplyMatrices(result, result);    
    23.         if (power % 2 != 0) {    
    24.             result = multiplyMatrices(result, matrix);    
    25.         }    
    26.         return result;    
    27.     }    
    28.     private static long[][] multiplyMatrices(long[][] matrix1,long[][] matrix2)    {    
    29.         long[][] result=new long[2][2];    
    30.         result[0][0]=matrix1[0][0]*matrix2[0][0]+matrix1[0][1]*matrix2[1][0];    
    31.         result[0][1]=matrix1[0][0]*matrix2[0][1]+matrix1[0][1]*matrix2[1][1];    
    32.         result[1][0]=matrix1[1][0]*matrix2[0][0]+matrix1[1][1]*matrix2[1][0];    
    33.         result[1][1]=matrix1[1][0]*matrix2[0][1]+matrix1[1][1]*matrix2[1][1];    
    34.         return result;    
    35.     }    
    36.     public static void main(String[] args)    {    
    37.         int n=10;    
    38.         long fibonacci=computeFibonacci(n);    
    39.         System.out.println(“Fibonacci number at position “+n+” is: “+fibonacci);    
    40.     }    
    41. }    

    Compile and Run

    Output:

    Fibonacci number at position 10 is: 55

    Complexity Analysis

    The time complexity of this approach is O(log n) since we perform matrix multiplication using the exponentiation by squaring technique.

    The space complexity is O(1) since we only need a fixed-size matrix and a few additional variables.

    19. Given an array of integers, rearrange the array such that all even numbers appear before all odd numbers.

    Note: Maintaining the relative order is not relevant for this problem.

    We can use a two-pointer technique to reorder an array so that all even numbers appear before all odd numbers. While the right pointer begins at the end and advances backwards, the left pointer moves ahead from the beginning. The elements pointed by the left and right pointers are examined at each step, and swaps are made as needed. All even numbers will be arranged before odd numbers by the time the loop is complete.

    Example

    1. public class Main     
    2. {    
    3.     public static void rearrangeArray(int[] arr)     
    4.     {    
    5.         int left=0;    
    6.         int right=arr.length-1;    
    7.         while (left<=right)   {    
    8.             if (arr[left]%2==0)    {    
    9.                 left++; // Move the left pointer forward if the element is even    
    10.             } else if (arr[right]%2==1)   {    
    11.                 right–; // Move the right pointer backwards if the element is odd    
    12.             } else {    
    13.     swap(arr,left,right); // Swap the elements if the left element is odd and the right element is even    
    14.                 left++; // Move the left pointer forward    
    15.                 right–; // Move the right pointer backwards    
    16.             }    
    17.         }    
    18.     }    
    19.     public static void swap(int[] arr,int i,int j)   {    
    20.         int temp=arr[i];    
    21.         arr[i]=arr[j];    
    22.         arr[j]=temp;    
    23.     }    
    24.     public static void main(String[] args)    {    
    25.         int[] arr = {1,2,3,4,5,6,7,8,9};    
    26.         System.out.println(“Original Array: “);    
    27.         printArray(arr);    
    28.         rearrangeArray(arr);    
    29.         System.out.println(“Rearranged Array: “);    
    30.         printArray(arr);    
    31.     }    
    32.     public static void printArray(int[] arr)   {    
    33.         for (int num:arr)   {    
    34.             System.out.print(num+” “);    
    35.         }    
    36.         System.out.println();    
    37.     }    
    38. }    

    Compile and Run

    Output:

    Original Array:
    1 2 3 4 5 6 7 8 9
    Rearranged Array:
    8 2 6 4 5 3 7 1 9
    

    Complexity Analysis

    The time complexity of this approach is O(n), where n is the number of elements in the array.

    The space complexity is O(1) as we perform the rearrangement in place without using any additional data structures.

    20. Java program to find the smallest missing positive number in an unsorted array.

    We can rearrange the array by assigning each positive integer to its appropriate index to discover the smallest missing positive number in an unsorted array. You can accomplish this by looping through the array and switching each element with a positive integer with the one at the desired index. The array is iterated once more to locate the first index where an element no longer corresponds to the required value after the rearrangement. The index corresponds to the smallest missing positive number. If all elements match their desired values, the smallest missing positive number is the next positive integer after the array size.

    Example

    1. public class Main    
    2. {    
    3.     public static int findSmallestMissingPositive(int[] nums)    
    4.     {    
    5.         int n=nums.length;    
    6.         // Rearrange the array    
    7.         for (int i=0;i<n;i++)     
    8.         {    
    9.             while (nums[i]>0&&nums[i]<=n&&nums[nums[i]-1]!=nums[i])     
    10.             {    
    11.                 swap(nums,i,nums[i]-1);    
    12.             }    
    13.         }    
    14.         //Find the smallest missing positive number    
    15.         for (int i=0;i<n;i++)     
    16.         {    
    17.             if (nums[i]!=i+1)     
    18.             {    
    19.                 return i+1;    
    20.             }    
    21.         }    
    22.         // If all elements match their desired values, return the next positive integer    
    23.         return n+1;    
    24.     }    
    25.     public static void swap(int[] nums,int i,int j)     
    26.     {    
    27.         int temp=nums[i];    
    28.         nums[i]=nums[j];    
    29.         nums[j]=temp;    
    30.     }    
    31.     public static void main(String[] args)     
    32.     {    
    33.         int[] nums={3,4,-1,1};    
    34.         int smallestMissingPositive = findSmallestMissingPositive(nums);    
    35.         System.out.println(“Smallest Missing Positive Number: “+smallestMissingPositive);    
    36.     }    
    37. }   

    Compile and Run

    Output:

    Smallest Missing Positive Number: 2

    Complexity Analysis

    The approach ensures a time complexity of O(n) and a space complexity of O(1) as we perform the rearrangement and search in place without additional data structures.

    21. Java program to find the intersection of two arrays.

    The best approach to finding the intersection of two arrays is to use a HashSet data structure. We create a HashSet and add all elements from one array to it. Then, we iterate through the second array and check if each element exists in the HashSet. If it does, we add it to the result ArrayList and remove it from the HashSet to avoid duplicates.

    Example

    1. import java.util.ArrayList;    
    2. import java.util.HashSet;    
    3. import java.util.List;    
    4. public class Main{    
    5.     public static List<Integer> intersection(int[] nums1, int[] nums2) {    
    6.         HashSet<Integer> set=new HashSet<>();    
    7.         List<Integer> result=new ArrayList<>();    
    8.         // Add elements of nums1 to the set    
    9.         for (int num:nums1)  {    
    10.             set.add(num);    
    11.         }    
    12.         // Check for intersection in nums2    
    13.         for (int num:nums2)   {    
    14.             if (set.contains(num))   {    
    15.                 result.add(num);    
    16.                 set.remove(num);    
    17.             }    
    18.         }    
    19.         return result;    
    20.     }    
    21.     public static void main(String[] args) {    
    22.         int[] nums1 = {1, 2, 2, 1};    
    23.         int[] nums2 = {2, 2};    
    24.         List<Integer> intersection=intersection(nums1, nums2);    
    25.         System.out.println(“Intersection: “+intersection);    
    26.     }    
    27. }    

    Compile and Run

    Output:

    Intersection: [2]

    Complexity Analysis

    The time complexity of this approach is O(n), where n is the size of the larger array.

    The space complexity is O(m), where m is the size of the HashSet.

    22. Java program to find the longest subarray with an equal number of 0s and 1s.

    Utilizing the prefix sum method, we can determine the longest subarray that contains an equal number of 0s and 1s. We can calculate the running sum while traversing the array by assigning a value of 1 for every 1 and -1 for every 0. When the running sum reaches zero, the number of 0s and 1s we have seen thus far is equal. To find the longest subarray, we store the running sum in a HashMap and its corresponding index. If the same running sum appears again, we update the maximum length by subtracting the stored index from the current index. By keeping track of the maximum length throughout the iteration, we can find the longest subarray with equal 0s and 1s.

    Example

    1. import java.util.HashMap;    
    2. public class Main {    
    3.     public static int findMaxLength(int[] nums)   {    
    4.         int maxLength=0;    
    5.         int runningSum=0;    
    6.         HashMap<Integer,Integer> sumMap=new HashMap<>();    
    7.         sumMap.put(0,-1); // Handle the case when the subarray starts from the beginning    
    8.         for (int i=0;i<nums.length;i++)   {    
    9.             runningSum+=nums[i]==0?-1:1;    
    10.             if (sumMap.containsKey(runningSum))    {    
    11.                 int startIndex=sumMap.get(runningSum);    
    12.                 maxLength=Math.max(maxLength,i-startIndex);    
    13.             } else {    
    14.                 sumMap.put(runningSum,i);    
    15.             }    
    16.         }    
    17.         return maxLength;    
    18.     }    
    19.     public static void main(String[] args)    {    
    20.         int[] nums = {0, 1, 0, 0, 1, 1, 0};    
    21.         int maxLength=findMaxLength(nums);    
    22.   System.out.println(“Length of the longest subarray with equal 0s and 1s is: “+maxLength);    
    23.     }    
    24. }    

    Compile and Run

    Output:

    Length of the longest subarray with equal 0s and 1s: 6

    Complexity Analysis

    The time complexity of this approach is O(n) since we iterate through the array once.

    The space complexity is O(n) as we store the running sum and its corresponding index in the HashMap.

    23. Java program to find the maximum product of two integers in an array.

    To find the maximum product of two integers in an array, we iterate through the array and keep track of the maximum and second maximum elements. We initialize max1 and max2 to the smallest possible integer values. Then, for each element, we compare it with max1 and update max2 and max1 accordingly. After iterating through the array, the maximum product is the product of max1 and max2, as max1 will hold the largest element and max2 will hold the second largest element.

    Example

    1. public class Main {    
    2.     public static int findMaximumProduct(int[] arr)  {    
    3.       int max1=Integer.MIN_VALUE; // Initialize the maximum element to the smallest possible value    
    4.         int max2=Integer.MIN_VALUE; // Initialize the second maximum element to the smallest possible value    
    5.         for (int num:arr)    {    
    6.             if (num>max1)    {    
    7.                 max2=max1; // Update the second maximum element    
    8.                 max1=num; // Update the maximum element    
    9.             }     
    10.             else if (num>max2)    {    
    11.                 max2=num; // Update the second maximum element    
    12.             }    
    13.         }    
    14.         return max1*max2; // Return the maximum product    
    15.     }    
    16.     public static void main(String[] args)    {    
    17.         int[] arr={1,2,3,4,5};    
    18.         int maximumProduct=findMaximumProduct(arr);    
    19.         System.out.println(“Maximum Product: “+maximumProduct);    
    20.     }    
    21. }    

    Compile and Run

    Output:

    Maximum Product: 20

    Complexity Analysis

    The time complexity of this approach is O(n), where n is the size of the array.

    The space complexity is O(1) since we only use constant extra space to store the maximum and second maximum elements.

    24. Java program to find the smallest subarray length with a sum greater than a given value.

    To find the smallest subarray length with a sum greater than a given value, we can utilize the sliding window technique. The approach involves maintaining a window that expands and contracts while calculating the current sum. We start with an empty window and gradually expand it by adding elements from the right end. If the current sum exceeds the given value, we update the minimum length of the subarray. Then, until the current total is less than or equal to the specified value, we contract the window from the left end by eliminating items. Until we reach the end of the array, we keep doing this.

    Example

    1. public class Main{    
    2.     public static int findSmallestSubarray(int[] arr,int target)   {    
    3.         int minLength=Integer.MAX_VALUE; // Variable to store the minimum length of the subarray    
    4.         int currentSum=0; // Variable to track the current sum of the subarray    
    5.         int left=0; // Left pointer to mark the start of the subarray    
    6.         int right=0; // Right pointer to mark the end of the subarray    
    7.         while (right<arr.length) {    
    8.         currentSum+=arr[right]; // Add the element at the right pointer to the current sum            while (currentSum>target)   {    
    9.   minLength=Math.min(minLength,rightleft+1); // Update the minimum length if necessary    
    10.     currentSum=arr[left]; // Subtract the element at the left pointer from the current sum  
    11.                 left++; // Move the left pointer to the right to contract the window    
    12.             }    
    13.             right++; // Move the right pointer to the right to expand the window    
    14.         }    
    15.         return (minLength==Integer.MAX_VALUE)?-1:minLength;     
    16.     }    
    17.     public static void main(String[] args)   {    
    18.         int[] arr={1, 4, 45, 6, 0, 19};    
    19.         int target=51;    
    20.         int smallestSubarrayLength=findSmallestSubarray(arr,target);    
    21.         System.out.println(“Smallest Subarray Length: “+smallestSubarrayLength);    
    22.     }    
    23. }    

    Compile and Run

    Output:

    Smallest Subarray Length: 3

    Complexity Analysis

    The time complexity of this approach is O(n), where n is the size of the array.

    The space complexity is O(1) since we only use constant extra space to store variables.

    25. Java program to find the triplet with the smallest sum in an array.

    We can take the help of three variables (an integer array of size three will also do the work), and using a loop, we can find the minimum elements present in the given array. We will be looking for the minimum elements as we have to find the smallest sum.

    Example

    1. public class Main   {    
    2. public static void findSmallestTripletSum(int[] arr)  {    
    3. int n = arr.length; // finding the size    
    4. // for storing the first three minimum values present in the given array.    
    5. int fMin = Integer.MAX_VALUE;    
    6. int sMin = Integer.MAX_VALUE;    
    7. int tMin = Integer.MAX_VALUE;     
    8. for (int i = 0; i < n; i++)   {     
    9. // getting the first, second and third minimum elements     
    10. if (arr[i] < fMin)   {     
    11.     tMin = sMin;     
    12.     sMin = fMin;     
    13.     fMin = arr[i];     
    14. }     
    15. // updating the second and third minimum elements     
    16. else if (arr[i] < sMin)   {     
    17.     tMin = sMin;     
    18.     sMin = arr[i];     
    19. }     
    20. else if (arr[i] < tMin)   {     
    21.     tMin = arr[i];     
    22. }     
    23. }    
    24. // print statement    
    25. System.out.println(“The Triplet with the smallest sum is: {“+ fMin + “, ” + sMin + “, ” + tMin + “}”);    
    26. }    
    27. // main method    
    28. public static void main(String[] args)   {    
    29. int[] arr = {5, 1, -3, -4, -2, 6};    
    30. findSmallestTripletSum(arr);    
    31. }    
    32. }    

    Compile and Run

    Output:

    The Triplet with the smallest sum is: {-4, -3, -2}

    Complexity Analysis

    The time complexity of this approach is O(n) since we are only using one loop in the program.

    The space complexity is O(1), as we are not using any extra space that grows with the input size.

    26. Java program to increment all elements of an array by one.

    The input array is defined as {1, 2, 3, 4, 5}. The method incrementArrayElements(int[] array) accepts an array as an argument. It then uses a for loop to iterate over each element in the array. Increment Operation: Inside the loop, the code array[i]++ increments each element by one. The final output is printed in the main() method, where the incremented array elements are displayed.

    Example

    1. public class Main {    
    2.     public static void main(String[] args) {    
    3.         int[] array = {1, 2, 3, 4, 5};    
    4.         incrementArrayElements(array);    
    5.         // Print the incremented array    
    6.         for (int i = 0; i < array.length; i++) {    
    7.             System.out.print(array[i] + ” “);    
    8.         }    
    9.     }    
    10.     public static void incrementArrayElements(int[] array) {    
    11.         for (int i = 0; i < array.length; i++) {    
    12.             array[i]++;    
    13.         }    
    14.     }    
    15. }   

    Compile and Run

    Output:

    2 3 4 5 6

    27. Java program to move all zeroes to the end of the array.

    For this approach, we traverse the array twice. In the first traversal, we do the following:

    • Iterate through the array while counting non-zero elements. Initialize the count at 0, which also indicates the position for the next non-zero element in the array.
    • For each non-zero element, position it at arr[count] and then increase the count by 1.
    • Once all elements have been processed, all non-zero entries will be moved to the front, keeping their original sequence.

    In the second traversal, we do the following:

    • Following the initial traversal, all non-zero elements will occupy the beginning of the array, while the variable ‘count’ will indicate the position for the first zero.
    • Proceed from ‘count’ to the end of the array, filling all subsequent indices with 0.

    Example

    1. public class Main {  
    2.     public static void main(String[] args) {  
    3.         int[] arr = {1, 0, 2, 0, 3, 0, 4, 0};  
    4.         int n = arr.length;  //finding array length  
    5.         int count = 0;  
    6.         for (int i = 0; i < n; i++) { //loop iterate over the array  
    7.             if (arr[i] != 0) {  //compare if the array element is equals to zero or not  
    8.                 arr[count++] = arr[i];  //  
    9.             }  
    10.         }  
    11.         while (count < n) {  
    12.             arr[count++] = 0;  
    13.         }  
    14.         System.out.println(“Array after moving zeroes: ” + java.util.Arrays.toString(arr));  
    15.     }  
    16. }  

    Compile and Run

    Output:

    Array after moving zeroes: [1, 2, 3, 4, 0, 0, 0, 0]

    28. Reverse an array without changing the position of zeroes.

    To solve the problem, the method involves moving through the array from both ends and swapping non-zero elements until reaching the centre. Throughout this procedure, the positions of zeroes are left intact. The code employs a while loop to bypass zeroes while decrementing the index from the end. When a non-zero element is detected, it gets swapped with the corresponding non-zero element from the opposite end. This swapping continues until the centre of the array is reached.

    Example

    1. import java.util.Arrays;  
    2. public class Main {  
    3. // Print function  
    4. public static void printReverse(int[] arr) {  
    5.     // Print the original array  
    6.     System.out.print(“Original array: “);  
    7.     System.out.println(Arrays.toString(arr));  
    8.     // Reverse the array without changing the position of zeroes  
    9.     // Initialize the index to the last element  
    10.     int j = arr.length – 1;  
    11.     for (int i = 0; i < j; i++) {  
    12.     // If the current element is zero, skip to the next element  
    13.     if (arr[i] == 0) {  
    14.         continue;  
    15.     }  
    16.     // If the current element is zero from the end  
    17.     while (j > i && arr[j] == 0) {  
    18.         // Decrement the index to the previous element  
    19.         j–;  
    20.     }  
    21.     // Swap the elements  
    22.     int temp = arr[i];  
    23.     arr[i] = arr[j];  
    24.     arr[j] = temp;  
    25.     // Decrement the index to the previous element  
    26.     j–;  
    27.     }  
    28.     // Prints the reversed array  
    29.     System.out.print(“Reversed array: “);  
    30.     System.out.println(Arrays.toString(arr));  
    31. }  
    32. public static void main(String[] args) {  
    33.     int[] arr = { 6, 0, 8, 0, 2, 0, 1 };  
    34.     printReverse(arr);  
    35. }  
    36. }  

    Compile and Run

    Output:

    Original array: [6, 0, 8, 0, 2, 0, 1]
    Reversed array: [1, 0, 2, 0, 8, 0, 6]
    

    29. Java program to find the leader element in an array.

    Given an array arr[] of size n, the task is to find all the Leaders in the array. An element is a Leader if it is greater than or equal to all the elements to its right side.

    Note: The rightmost element is always a leader.

    Example

    1. public class Main {  
    2.     public static void main(String[] args) {  
    3.         int[] arr = {12, 11, 4, 7, 9, 6, 8, 15};  
    4.         int n = arr.length;  
    5.         int maxFromRight = arr[n – 1];  
    6.         System.out.print(“Leader is: ” + maxFromRight + ” “);  
    7.         for (int i = n – 2; i >= 0; i–) {  
    8.             if (arr[i] > maxFromRight) {  
    9.                 maxFromRight = arr[i];  
    10.                 System.out.print(maxFromRight + ” “);  
    11.             }  
    12.         }  
    13.     }  
    14. }  

    Compile and Run

    Output:

    Leader is: 15

    30. Java program to find all the non-empty subarrays.

    To create a subarray, we first need a starting index from the original array. We can choose this starting index by looping through the range [0 to n-1] and treating each index i as a potential starting point. For each selected starting index i, we then determine an ending index from the range [i to n-1]. A nested loop, running from [i to n-1], will assist in selecting the ending index. Once both the starting and ending indices are established, an innermost loop will be required to print the elements of the subarray.

    Example

    1. import java.util.ArrayList;  
    2. public class Main {  
    3.     //Prints all subarrays in arr[0..n-1]  
    4.     static void findSubArray(ArrayList<Integer> arr) {  
    5.         int n = arr.size();  
    6.         // Pick starting point  
    7.         for (int i = 0; i < n; i++) {           
    8.             // Pick ending point  
    9.             for (int j = i; j < n; j++) {               
    10.                 // Print subarray between current starting and ending points  
    11.                 for (int k = i; k <= j; k++) {  
    12.                     System.out.print(arr.get(k) + ” “);  
    13.                 }  
    14.                 System.out.println();  
    15.             }  
    16.         }  
    17.     }  
    18.     public static void main(String[] args) {  
    19.         ArrayList<Integer> arr = new ArrayList<>();  
    20.         arr.add(1);  
    21.         arr.add(2);  
    22.         arr.add(3);  
    23.         System.out.println(“Subarrays are:”);  
    24.         findSubArray(arr);  
    25.     }  
    26. }  

    Compile and Run

    Output:

    Subarrays are:
    1
    1 2
    1 2 3
    2
    2 3
    3
    
  • Jagged Array in Java

    A jagged array in Java is a collection of arrays where each array may contain a varied number of elements. A two-dimensional array, in contrast, requires all rows and columns to have the same length.

    Jagged arrays are also known as “ragged arrays” or “irregular arrays”. They can be created by specifying the size of each array in the declaration. For example, a jagged array with three rows can have the first row with three elements, the second with two elements, and the third with four elements.

    Example of Jagged Array

    A jagged array with three rows can have the first row with three elements, the second with two elements, and the third with four elements.

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

    Declaration and Initialization of Jagged Array

    In Java, a jagged array can be declared and initialized using the following syntax:

    Syntax:

    1. datatype[][] arrayName = new datatype[numRows][];  
    2. arrayName[0] = new datatype[numColumns1];  
    3. arrayName[1] = new datatype[numColumns2];  
    4. …  
    5. arrayName[numRows-1] = new datatype[numColumnsN];  

    Here, the datatype is the data type of the elements in the array, numRows is the number of rows in the jagged array, and numColumns1, numColumns2, …, numColumnsN are the number of columns in each row. Users should be aware that the number of columns in each row is flexible.

    The first line creates an array of arrays with numRows rows. Each row is initialized to null by default.

    The subsequent lines initialize each row of the jagged array. You create a new one-dimensional array of numColumns elements for each row and assign it to the corresponding row in the jagged array.

    Ways to Initialize a Jagged Array

    In addition to the standard approach of declaring and initializing a jagged array, as shown in the previous answer, several alternative ways exist to initialize a jagged array in Java.

    1. Using Array Literals

    We can use array literals to initialize the jagged array elements like this directly:

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

    Here, we create a jagged array with three rows, where the first row has two elements, the second row has three elements, and the third row has four elements.

    Example

    1. public class Main {    
    2.     public static void main(String[] args) {    
    3.         // create a jagged array with three rows    
    4.         int[][] jaggedArray = {    
    5.             {1, 2, 3},   // first row has three columns    
    6.             {4, 5},      // second row has two columns    
    7.             {6, 7, 8, 9}   };  // third row has four columns    
    8.         // loop through each row of the jagged array    
    9.         for (int i = 0; i < jaggedArray.length; i++) {    
    10.             // loop through each column of the current row    
    11.             for (int j = 0; j < jaggedArray[i].length; j++) {    
    12.                 // print the value at the current position in the array    
    13.                 System.out.print(jaggedArray[i][j] + ” “);    
    14.             }    
    15.             // move to the next line for the next row    
    16.             System.out.println();    
    17.         }    
    18.     }    
    19. }    

    Compile and Run

    Output:

    1 2 3
    4 5
    6 7 8 9
    

    2. Using Nested Loops

    We can also use nested loops to initialize the jagged array elements when the elements are to be programmatically generated. Utilizing such an approach can be beneficial.

    1. int[][] jaggedArray = new int[3][];  
    2. for (int i = 0; i < jaggedArray.length; i++) {  
    3.     jaggedArray[i] = new int[i + 1];  
    4.     for (int j = 0; j < jaggedArray[i].length; j++) {  
    5.         jaggedArray[i][j] = i + j;  
    6.     }  
    7. }  

    Here, we design a jagged array with three rows, the first of which contains one element, the second two, and the third three. Using a simple formula, the nested loops generate the elements in the jagged array.

    Example

    1. public class Main {    
    2.     public static void main(String[] args) {    
    3.         // Create a 2-D jagged array with 4 rows    
    4.         int[][] jaggedArray = new int[4][];    
    5.         // Set the number of columns for each row    
    6.         jaggedArray[0] = new int[1];    
    7.         jaggedArray[1] = new int[2];    
    8.         jaggedArray[2] = new int[3];    
    9.         jaggedArray[3] = new int[4];    
    10.         // Fill the array with values starting from 1    
    11.         int value = 1;    
    12.         for (int i = 0; i < jaggedArray.length; i++) {    
    13.             for (int j = 0; j < jaggedArray[i].length; j++) {    
    14.                 jaggedArray[i][j] = value;    
    15.                 value++;    
    16.             }    
    17.         }    
    18.         // Print the values in the array    
    19.         for (int i = 0; i < jaggedArray.length; i++) {    
    20.             for (int j = 0; j < jaggedArray[i].length; j++) {    
    21.                 System.out.print(jaggedArray[i][j] + ” “);    
    22.             }    
    23.             System.out.println();    
    24.         }    
    25.     }    
    26. }    

    Compile and Run

    Output:

    1
    2 3
    4 5 6
    7 8 9 10
    

    3. Using Java 8 Streams

    With Java 8 streams, you can create and initialize a jagged array in a single line using the Arrays.stream and toArray methods like this:

    1. int[][] jaggedArray = Stream.of(  
    2.         new int[]{1, 2},  
    3.         new int[]{3, 4, 5},  
    4.         new int[]{6, 7, 8, 9})  
    5.         .toArray(int[][]::new);  

    Here, we make a three-row jagged array with two elements in the first row, three in the second row, and four in the third row. The Arrays.stream method converts each one-dimensional array into a stream of integers, and then the toArray method collects the stream into a jagged array.

    Example

    1. import java.util.*;    
    2. public class Main {    
    3.     public static void main(String[] args) {           
    4.         // create a jagged array with three rows    
    5.         int[][] jaggedArray = {    
    6.             {1, 2, 3},   // first row has three columns    
    7.             {4, 5},      // second row has two columns    
    8.             {6, 7, 8, 9} // third row has four columns    
    9.         };    
    10.         // loop through each row of the jagged array using streams    
    11.         Arrays.stream(jaggedArray)    
    12.             .forEach(row -> {    
    13.                 // loop through each element of the current row using streams    
    14.                 Arrays.stream(row)    
    15.                     .forEach(element -> System.out.print(element + ” “));    
    16.                 // move to the next line for the next row    
    17.                 System.out.println();    
    18.             });    
    19.     }    
    20. }    

    Compile and Run

    Output:

    1 2 3
    4 5
    6 7 8 9
    

    4. Dynamic Jagged Array

    In Java, we can create a dynamic jagged array by creating an array of arrays, where each sub-array represents a row in the two-dimensional array. Then, we can allocate memory to each sub-array to specify its number of columns.

    Example

    1. import java.util.Scanner;    
    2. public class Main {    
    3. public static void main(String[] args) {    
    4. // Create a Scanner object to get user input    
    5. Scanner scanner = new Scanner(System.in);    
    6.     // Prompt the user to enter the number of sub-arrays    
    7.     System.out.print(“Enter the number of sub-arrays: “);    
    8.     int numberOfArrays = scanner.nextInt();    
    9.     // Declare the jagged array with the number of sub-arrays    
    10.     int[][] jaggedArray = new int[numberOfArrays][];    
    11.     //Loop through each sub-array to allocate memory and get user input for each element    
    12.     for (int i = 0; i < numberOfArrays; i++) {    
    13.         // Prompt the user to enter the size of the current sub-array    
    14.         System.out.print(“Enter the size of sub-array ” + (i + 1) + “: “);    
    15.         int sizeOfSubArray = scanner.nextInt();    
    16.         // Allocate memory to the current sub-array    
    17.         jaggedArray[i] = new int[sizeOfSubArray];    
    18.         //Loop through each element of the current sub-array to get user input    
    19.         for (int j = 0; j < sizeOfSubArray; j++) {    
    20.             System.out.print(“Enter the element at index ” + j + ” of sub-array ” + (i + 1) + “: “);    
    21.             jaggedArray[i][j] = scanner.nextInt();    
    22.         }    
    23.     }    
    24.     // Print the jagged array    
    25.     System.out.println(“The jagged array is:”);    
    26.     for (int i = 0; i < numberOfArrays; i++) {    
    27.         for (int j = 0; j < jaggedArray[i].length; j++) {    
    28.             System.out.print(jaggedArray[i][j] + ” “);    
    29.         }    
    30.         System.out.println();    
    31.     }    
    32.     // Close the scanner object    
    33.     scanner.close();    
    34. }    
    35. }    

    Compile and Run

    Output:

    Enter the number of sub-arrays: 3
    Enter the size of sub-array 1: 2
    Enter the element at index 0 of sub-array 1: 1
    Enter the element at index 1 of sub-array 1: 2
    Enter the size of sub-array 2: 3
    Enter the element at index 0 of sub-array 2: 3
    Enter the element at index 1 of sub-array 2: 4
    Enter the element at index 2 of sub-array 2: 5
    Enter the size of sub-array 3: 1
    Enter the element at index 0 of sub-array 3: 6
    The jagged array is:
    1 2
    3 4 5
    6
    

    Advantages of Jagged Array

    Jagged arrays have several advantages over multidimensional arrays with a fixed size:

    1. Memory Efficiency: Jagged arrays are more memory-efficient than multidimensional arrays because they only allocate memory for the elements they need. In a multidimensional array with a fixed size, all the memory is allocated, even if some elements are unused.
    2. Flexibility: Jagged arrays are more flexible than multidimensional arrays because they can have different sizes for each row. Jagged arrays enable the representation of non-rectangular or irregular data structures.
    3. Easy to Initialize: Jagged arrays are easy to initialize because you can specify the size of each row individually. The suitability of jagged arrays lies in their ability to store data that varies in size or is generated dynamically.
    4. Enhanced Performance: Jagged arrays can provide enhanced performance in certain scenarios, such as when you need to perform operations on each row independently or when you need to add or remove rows dynamically.
    5. More natural representation of data: In some cases, jagged arrays may be a more natural representation of data than rectangular arrays. For example, when working with irregularly shaped data such as geographic maps, a jagged array can be a more intuitive way to represent the data.
    6. Easier to manipulate: Jagged arrays can be easier to manipulate than rectangular arrays because they allow for more direct access to individual elements. With rectangular arrays, you may need to use more complex indexing or slicing operations to access subsets of the data.

    How do jagged arrays differ from multi-dimensional arrays?

    A jagged array is not the same as a multi-dimensional array. There are some differences between Jagged array and multi-dimensional array that are described in the following table.

    AspectJagged ArrayMulti-dimensional Array
    StructureEach row (or sub-array) can have a different length.All rows must have the same number of columns.
    Memory AllocationMemory is allocated separately for each sub-array, making it more memory-efficient when varying row sizes are needed.It allocates a continuous block of memory for all elements, potentially wasting memory when row lengths vary.
    Declarationint[][] jaggedArray = {
        {1, 2, 3},
        {4, 5},
        {6, 7, 8, 9}
    };
    int[][] multiArray = new int[3][3]; // Fixed size: 3 rows, 3 columns
    Accessing ElementsJagged Array: jaggedArray[row][column]Multi-dimensional Array: multiArray[row][column]
    Uses CasesIt is useful when dealing with irregular data structures like variable-length rows in tables.It is ideal for grids, matrices, or fixed-size tables.
  • Java Array length Property

    In Java, the array length is the number of elements that an array can hold. There is no predefined method to obtain the length of an array. We can find the array length in Java by using the array attribute length. We use this attribute with the array name.

    Array length Attribute

    Java provides an attribute length that determines the length of an array. Every array has an in-built length property whose value is the size of the array. Size implies the total number of elements that an array can contain. The length property can be invoked by using the dot (.) operator followed by the array name. We can find the length of int[], double[], String[], etc. For example:

    1. int[] arr=new int[5];  
    2. int arrayLength=arr.length  

    In the above code snippet, arr is an array of type int that can hold 5 elements. The arrayLength is a variable that stores the length of an array. To find the length of the array, we have used the array name (arr) followed by the dot operator and length attribute, respectively. It determines the size of the array.

    How to Find Array Length in Java

    Note that length determines the maximum number of elements that the array can contain or the capacity of the array. It does not count the elements that are inserted into the array. That is, length returns the total size of the array. For arrays whose elements are initialized at the time of its creation, length and size are the same.

    If we talk about the logical size, the index of the array, then simply int arrayLength=arr.length-1, because the array index starts from 0. So, the logical or array index will always be less than the actual size by 1.

    How to Find Array Length in Java

    Let’s find the length of the array through an example.

    Example

    1. public class Main  {     
    2. public static void main(String[] args)   {     
    3. //defining an array of type int named num    
    4. //The square bracket contains the length of an array    
    5. int[] num = new int[10];     
    6. //length is an Array attribute that determines the array length     
    7. int arrayLength=num.length;    
    8. //prints array length    
    9. System.out.println(“The length of the array is: “+ arrayLength);     
    10. }     
    11. }    

    Compile and Run

    Output:

    The length of the array is: 10

    Explanation

    This Java code, which is part of the ArrayLengthExample1 class, shows how to find an array’s length. The syntax int[] num = new int[10]; is used in the main method to declare and initialise an array of type int with a length of 10. When an array is declared, its length is specified by the square brackets. The code then determines the length of the num array by using the length attribute, which is built into all Java arrays, and assigning the result to the variable arrayLength. Finally, the program prints out the length of the array using System.out.println, providing information about the number of elements the array can hold.

    Example

    1. public class Main   {     
    2. public static void main(String[] args)   {     
    3. //Initialising an array of type String named country     
    4. String[] country = { “India”, “Australia”, “Japan”, “USA”, “UAE”, “Canada”, “Brazil”};    
    5. //length is an Array attribute that determines the array length     
    6. int arrayLength=country.length;     
    7. //prints array length    
    8. System.out.println(“The size of the array is: ” + arrayLength);     
    9. }     
    10. }    

    Compile and Run

    Output:

    The size of the array is: 7

    Explanation

    With a main method, the class ArrayLengthExample2 is defined in the Java code that is provided. Several country names are initialised into an array of type String called country inside the main procedure. Next, the code calculates the length of the nation array, or the total number of entries it may contain, using Java’s length attribute for arrays. The variable arrayLength is given the length. The array’s size and the number of elements it contains are finally printed by the programme using System.out.println. This code basically shows how to use Java’s length attribute to find the length of an array and how to output the length for reference.

    Example

    1. public class Main   {    
    2. private static void LengthOfArray(String[] array)   {    
    3. //checks array is empty or not        
    4. if (array == null)   {    
    5. //if the array is empty, prints the following statement    
    6. System.out.println(“The array is empty, can’t be determined the length.”);    
    7. }     
    8. else   {    
    9. //The length attribute of the Array class determines the length of an array    
    10. int arrayLength = array.length;    
    11. //prints the array length    
    12. System.out.println(“The length of the array is: “+arrayLength);    
    13. }    
    14. }    
    15. public static void main(String[] args)   {    
    16. String[] fruits = { “Guava”, “Banana”, “Apple”, “Papaya”, “Melon”, “Strawberry”};    
    17. String[] alphabets = { “m”, “p”, “k”, “l”, “t” };    
    18. String[] numbers = { “12”, “25”, “63”, “84”, “90”, “11”, “54”};    
    19. //passing a null value to the function    
    20. LengthOfArray(null);    
    21. //passing the fruits array to the function    
    22. LengthOfArray(fruits);    
    23. //passing the alphabet array to the function    
    24. LengthOfArray(alphabets);    
    25. //passing the numbers array to the function    
    26. LengthOfArray(numbers);    
    27. }    
    28. }    

    Compile and Run

    Output:

    The array is empty, can't be determined the length.
    The length of the array is: 6
    The length of the array is: 5
    The length of the array is: 7
    

    Explanation

    The Java code that is provided defines a class called Main, and in that class, there is a method called LengthOfArray that is used to find and report the length of a specified array of strings. The procedure initially determines if the supplied array is null or empty by looking at its value. It prints a message saying that the length cannot be computed if the array is empty. If not, it uses the Array class’s length attribute to determine the array’s length and displays it. LengthOfArray’s usefulness is demonstrated in the main method by passing several arrays, such as a null value, an array of fruits, alphabets, and numerals. The length of each array is output by the programme when it runs.

    Iterating through the Array

    Another method involves iterating through the array and counting the number of elements encountered. This approach provides more flexibility and control over the counting process.

    Example

    1. public class Main {    
    2.     public static void main(String[] args) {    
    3.         int[] arr = new int[5];    
    4.         int count = 0;    
    5.         for (int element : arr) {    
    6.             count++;    
    7.         }    
    8.         int arrayLength = count;    
    9.         System.out.println(“The length of the array is: ” + arrayLength);    
    10.     }    
    11. }    

    Compile and Run

    Output:

    The length of the array is: 5
  • Multi-Dimensional Arrays in Java

    Multi-dimensional arrays in Java are basically arrays of arrays. It allows us to store data in a tabular or grid-like structure, making them useful for scenarios like matrices, game boards, or any data that requires multiple dimensions. It is useful when we want to store data in tabular form (rows and columns).

    It can be a two-dimensional (2D) or three-dimensional (3D) array.

    Two-Dimensional (2D) Array

    It is the simplest multi-dimensional array having rows and columns.

    Declaration

    1. DataType[][] arrayName;    

    or

    1. DataType arrayName[][];   

    or

    1. arrayName = new DataType[rows][columns];   

    We can declare and initialize a two-dimensional array in a single statement as follows.

    1. datatype[][] arrayName = new datatype[rows][columns];   

    Assigning Values

    1. arrayName[rows][columns] = {values};   

    Examples

    1. // 2D Array with two rows and two columns Intialised and Assigned  
    2. int[][] arr = { { 1, 2 }, { 3, 4 } };  
    3. //array with three rows and three columns  
    4.  int[][] arr = new int[3][3];  

    Representation of 2D Array

    Multi-Dimensional Arrays in Java

    Note that Java uses zero-based indexing. It means the indexing of arrays in Java starts with 0.

    Also, note that in a multi-dimensional array, each row can be of different sizes. It means that each row may not have the same number of elements.

    Two-Dimensional (2D) Array Java Program

    Example

    1. public class Main {      
    2.     public static void main(String args[]) {      
    3.         int arr[][] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; // 3×3 matrix      
    4.         // Printing the 2D array      
    5.         for (int i = 0; i < 3; i++)   //loop for rows  
    6. {      
    7.             for (int j = 0; j < 3; j++)  //loop for columns  
    8.    {      
    9.                 System.out.print(arr[i][j] + ” “);    //prints element with space  
    10.             }      
    11.             System.out.println();    //throws cursor to the next line  
    12.         }      
    13.     }      
    14. }      

    Compile and Run

    Output:

    1 2 3
    4 5 6
    7 8 9
    

    Explanation

    In the above program, we have declared and initialized a 3×3 matrix. The first for loop iterates over the rows, and the second for loop iterates over the columns. The first print statement prints the elements of the array with space, and the second print statement throws the cursor to the next line.

    Two-Dimensional (2D) Array with User Input

    Example

    1. import java.util.Scanner;  
    2. public class Main {  
    3.     public static void main(String[] args) {  
    4.         Scanner scanner = new Scanner(System.in);  
    5.         // Define the dimensions of the array  
    6.         System.out.print(“Enter the number of rows:”);  
    7.         int rows = scanner.nextInt();  //reading number of rows from the user  
    8.         System.out.print(“Enter the number of columns:”);  
    9.         int columns = scanner.nextInt();  //reading number of columns from the user  
    10.         // Initialize the 2D array  
    11.         int[][] array = new int[rows][columns];  
    12.         //reading array elements from the user  
    13.         System.out.println(“Enter the elements of the array:”);  
    14.         for (int i = 0; i < rows; i++)    //loop for rows  
    15.         {  
    16.             for (int j = 0; j < columns; j++)   //loop for columns  
    17.             {  
    18.                 System.out.print(“Enter element for position (” + i + “, ” + j + “): “);  
    19.                 //reading array elements one by one  
    20.                 array[i][j] = scanner.nextInt();  
    21.             }  
    22.         }  
    23.         // Printing the 2D array  
    24.         System.out.println(“The entered 2D array is:”);  
    25.         for (int i = 0; i < rows; i++) {  
    26.             for (int j = 0; j < columns; j++) {  
    27.                 System.out.print(array[i][j] + ” “);  
    28.             }  
    29.             System.out.println();  
    30.         }  
    31.         scanner.close();  
    32.     }  
    33. }  

    Output:

    Enter the number of rows:3
    Enter the number of columns:3
    Enter the elements of the array:
    Enter element for position (0, 0): 1
    Enter element for position (0, 1): 2
    Enter element for position (0, 2): 3
    Enter element for position (1, 0): 4
    Enter element for position (1, 1): 5
    Enter element for position (1, 2): 6
    Enter element for position (2, 0): 7
    Enter element for position (2, 1): 8
    Enter element for position (2, 2): 9
    The entered 2D array is:
    1 2 3
    4 5 6
    7 8 9
    

    Three-Dimensional (3D) Array

    It is a complex form of a 2D array. In other words, it is an array of a two-dimensional array.

    Declaration

    1. DataType[][][] arrayName;        

    or

    1. DataType arrayName[][][];   

    or

    1. arrayName = new DataType[][][];   

    We can declare and initialize a three-dimensional array in a single statement as follows.

    1. datatype[][][] arrayName = new datatype[][][];   

    Assigning Values

    1. arrayName[][][] = {values};  

    Examples

    public class Main {  
    
        public static void main(String[] args)   
    
        {  
    
            //declaring and initializing three-dimensional array  
    
            int[][][] threeDArray = {  
    
                {  
    
                    {1, 2, 3},  
    
                    {4, 5, 6}  
    
                },  
    
                {  
    
                    {7, 8, 9},  
    
                    {10, 11, 12}  
    
                }  
    
            };  
    
            //Print the elements of the 3D array  
    
            System.out.println("Elements of the 3D Array:");  
    
            for (int i = 0; i < threeDArray.length; i++) {  
    
                for (int j = 0; j < threeDArray[i].length; j++) {  
    
                    for (int k = 0; k < threeDArray[i][j].length; k++) {  
    
                        System.out.print(threeDArray[i][j][k] + " ");  
    
                    }  
    
                    System.out.println(); // Move to the next line for better readability  
    
                }  
    
                System.out.println(); // Add a blank line between blocks  
    
            }  
    
        }  
    
    }

    1. // 3D Array with two rows ad two columns Intialised and Assigned  
    2. int[][][] values = {{{1, 2, 3}, {4, 5, 6}}, {{-2, -8, 3, 7}, {5}, {12, 11}}};  
    3. //array contains three array of three rows and three columns   
    4.  int[][][] arr = new int[3][3][3];  

    Representation of 3D Array

    Multi-Dimensional Arrays in Java

    Three-Dimensional (3D) Array Java Program

    Example

    Compile and Run

    Output:

    Elements of the 3D Array:
    1 2 3
    4 5 6
    
    7 8 9
    10 11 12
    

    Size of Multidimensional Arrays

    We can calculate the size of the array by multiplying the size of all the dimensions. It gives the number of elements that can be stored in an array. For example, int[][][] num = new int[5][5][5]; can store total 125 elements.

    Why Use Multidimensional Arrays?

    Multidimensional arrays are useful in many real-world scenarios, such as:

    1. Mathematical computations: Representing matrices for algebraic calculations.
    2. Game development: Storing board layouts, game grids, or levels.
    3. Image processing: Representing pixels in a digital image.
    4. Data analysis: Managing structured data like spreadsheets or databases.

    Conclusion

    Multidimensional arrays in Java serve as an effective solution for managing organized data structures while processing them. Multidimensional arrays surpass the functionality of single-dimensional arrays because they enable table organization, which results in applications ranging from scientific computing to game development.

    Two-dimensional arrays function as the preferred form for applications that need matrix computations together with pathfinding implementations and data presentation. The option to produce jagged arrays makes the process more adaptable for developers since they can handle irregular data formats.

  • Java Arrays

    Normally, an array is a collection of similar type of elements which has contiguous memory location.

    Java array is an object which contains elements of a similar data type. Additionally, The elements of an array are stored in a contiguous memory location. It is a data structure where we store similar elements. We can store only a fixed set of elements in a Java array.

    Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element is stored on 1st index and so on.

    Unlike C/C++, we can get the length of the array using the length member. In C/C++, we need to use the sizeof operator.

    In Java, array is an object of a dynamically generated class. Java array inherits the Object class, and implements the Serializable as well as Cloneable interfaces. We can store primitive values or objects in an array in Java. Like C/C++, we can also create single dimentional or multidimentional arrays in Java.

    Moreover, Java provides the feature of anonymous arrays which is not available in C/C++.

    Java array

    Advantages

    • Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.
    • Random access: We can get any data located at an index position.

    Disadvantages

    • Size Limit: We can store only the fixed size of elements in the array. It doesn’t grow its size at runtime. To solve this problem, collection framework is used in Java which grows automatically.

    Types of Array in java

    There are two types of array.

    • Single Dimensional Array
    • Multidimensional Array

    Single Dimensional Array in Java

    Syntax to Declare an Array in Java

    dataType[] arr; (or)  
    
    dataType []arr; (or)  
    
    dataType arr[];  

      Instantiation of an Array in Java

      arrayRefVar=new datatype[size];  

      Example of Java Array

      Let’s see the simple example of java array, where we are going to declare, instantiate, initialize and traverse an array.

      //Java Program to illustrate how to declare, instantiate, initialize  
      
      //and traverse the Java array.  
      
      class Testarray{  
      
      public static void main(String args[]){  
      
      int a[]=new int[5];//declaration and instantiation  
      
      a[0]=10;//initialization  
      
      a[1]=20;  
      
      a[2]=70;  
      
      a[3]=40;  
      
      a[4]=50;  
      
      //traversing array  
      
      for(int i=0;i<a.length;i++)//length is the property of array  
      
      System.out.println(a[i]);  
      
      }}

      Output:

      10
      20
      70
      40
      50
      

      Declaration, Instantiation and Initialization of Java Array

      We can declare, instantiate and initialize the java array together by:

      int a[]={33,3,4,5};//declaration, instantiation and initialization  

      Let’s see the simple example to print this array.

      //Java Program to illustrate the use of declaration, instantiation   
      
      //and initialization of Java array in a single line  
      
      class Testarray1{  
      
      public static void main(String args[]){  
      
      int a[]={33,3,4,5};//declaration, instantiation and initialization  
      
      //printing array  
      
      for(int i=0;i<a.length;i++)//length is the property of array  
      
      System.out.println(a[i]);  
      
      }}

      Output:

      33
      3
      4
      5
      

      For-each Loop for Java Array

      We can also print the Java array using for-each loop. The Java for-each loop prints the array elements one by one. It holds an array element in a variable, then executes the body of the loop.

      The syntax of the for-each loop is given below:

      for(data_type variable:array){  
      
      //body of the loop  
      
      } 

        Let us see the example of print the elements of Java array using the for-each loop.

        //Java Program to print the array elements using for-each loop  
        
        class Testarray1{  
        
        public static void main(String args[]){  
        
        int arr[]={33,3,4,5};  
        
        //printing array using for-each loop  
        
        for(int i:arr)  
        
        System.out.println(i);  
        
        }}  

          Output:

          33
          3
          4
          5
          

          Passing Array to a Method in Java

          We can pass the java array to method so that we can reuse the same logic on any array.

          Let’s see the simple example to get the minimum number of an array using a method.

          //Java Program to demonstrate the way of passing an array  
          
          //to method.  
          
          class Testarray2{  
          
          //creating a method which receives an array as a parameter  
          
          static void min(int arr[]){  
          
          int min=arr[0];  
          
          for(int i=1;i<arr.length;i++)  
          
           if(min>arr[i])  
          
            min=arr[i];  
          
            
          
          System.out.println(min);  
          
          }  
          
            
          
          public static void main(String args[]){  
          
          int a[]={33,3,4,5};//declaring and initializing an array  
          
          min(a);//passing array to method  
          
          }}

          Output:

          3
          

          Anonymous Array in Java

          Java supports the feature of an anonymous array, so you don’t need to declare the array while passing an array to the method.

          //Java Program to demonstrate the way of passing an anonymous array  
          
          //to method.  
          
          public class TestAnonymousArray{  
          
          //creating a method which receives an array as a parameter  
          
          static void printArray(int arr[]){  
          
          for(int i=0;i<arr.length;i++)  
          
          System.out.println(arr[i]);  
          
          }  
          
            
          
          public static void main(String args[]){  
          
          printArray(new int[]{10,22,44,66});//passing anonymous array to method  
          
          }}

          Output:

          10
          22
          44
          66
          

          Returning Array from the Method

          We can also return an array from the method in Java.

          //Java Program to return an array from the method  
          
          class TestReturnArray{  
          
          //creating method which returns an array  
          
          static int[] get(){  
          
          return new int[]{10,30,50,90,60};  
          
          }  
          
            
          
          public static void main(String args[]){  
          
          //calling method which returns an array  
          
          int arr[]=get();  
          
          //printing the values of an array  
          
          for(int i=0;i<arr.length;i++)  
          
          System.out.println(arr[i]);  
          
          }}

          Output:

          10
          30
          50
          90
          60
          

          ArrayIndexOutOfBoundsException

          The Java Virtual Machine (JVM) throws an ArrayIndexOutOfBoundsException if length of the array in negative, equal to the array size or greater than the array size while traversing the array.

          //Java Program to demonstrate the case of   
          
          //ArrayIndexOutOfBoundsException in a Java Array.  
          
          public class TestArrayException{  
          
          public static void main(String args[]){  
          
          int arr[]={50,60,70,80};  
          
          for(int i=0;i<=arr.length;i++){  
          
          System.out.println(arr[i]);  
          
          }  
          
          }}

          Output:

          Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
          	at TestArrayException.main(TestArrayException.java:5)
          50
          60
          70
          80
          

          Multidimensional Array in Java

          In such case, data is stored in row and column based index (also known as matrix form).

          Syntax to Declare Multidimensional Array in Java

          dataType[][] arrayRefVar; (or)  
          
          dataType [][]arrayRefVar; (or)  
          
          dataType arrayRefVar[][]; (or)  
          
          dataType []arrayRefVar[];  

            Example to instantiate Multidimensional Array in Java

            int[][] arr=new int[3][3];//3 row and 3 column  

            Example to initialize Multidimensional Array in Java

            arr[0][0]=1;  
            
            arr[0][1]=2;  
            
            arr[0][2]=3;  
            
            arr[1][0]=4;  
            
            arr[1][1]=5;  
            
            arr[1][2]=6;  
            
            arr[2][0]=7;  
            
            arr[2][1]=8;  
            
            arr[2][2]=9;

            Example of Multidimensional Java Array

            Let’s see the simple example to declare, instantiate, initialize and print the 2Dimensional array.

            //Java Program to illustrate the use of multidimensional array  
            
            class Testarray3{  
            
            public static void main(String args[]){  
            
            //declaring and initializing 2D array  
            
            int arr[][]={{1,2,3},{2,4,5},{4,4,5}};  
            
            //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
            2 4 5
            4 4 5
            

            Jagged Array in Java

            If we are creating odd number of columns in a 2D array, it is known as a jagged array. In other words, it is an array of arrays with different number of columns.

            //Java Program to illustrate the jagged array  
            
            class TestJaggedArray{  
            
                public static void main(String[] args){  
            
                    //declaring a 2D array with odd columns  
            
                    int arr[][] = new int[3][];  
            
                    arr[0] = new int[3];  
            
                    arr[1] = new int[4];  
            
                    arr[2] = new int[2];  
            
                    //initializing a jagged array  
            
                    int count = 0;  
            
                    for (int i=0; i<arr.length; i++)  
            
                        for(int j=0; j<arr[i].length; j++)  
            
                            arr[i][j] = count++;  
            
               
            
                    //printing the data of a jagged array   
            
                    for (int i=0; i<arr.length; i++){  
            
                        for (int j=0; j<arr[i].length; j++){  
            
                            System.out.print(arr[i][j]+" ");  
            
                        }  
            
                        System.out.println();//new line  
            
                    }  
            
                }  
            
            }

            Output:

            0 1 2 
            3 4 5 6 
            7 8 
            

            What is the class name of Java array?

            In Java, an array is an object. For array object, a proxy class is created whose name can be obtained by getClass().getName() method on the object.

            //Java Program to get the class name of array in Java  
            
            class Testarray4{  
            
            public static void main(String args[]){  
            
            //declaration and initialization of array  
            
            int arr[]={4,4,5};  
            
            //getting the class name of Java array  
            
            Class c=arr.getClass();  
            
            String name=c.getName();  
            
            //printing the class name of Java array   
            
            System.out.println(name);  
            
              
            
            }}

            Output:

            I
            

            Copying a Java Array

            We can copy an array to another by the arraycopy() method of System class.

            Syntax of arraycopy method

            public static void arraycopy(  
            
            Object src, int srcPos,Object dest, int destPos, int length  
            
            ) 

              Example of Copying an Array in Java

              //Java Program to copy a source array into a destination array in Java  
              
              class TestArrayCopyDemo {  
              
                  public static void main(String[] args) {  
              
                      //declaring a source array  
              
                      char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e',  
              
                              'i', 'n', 'a', 't', 'e', 'd' };  
              
                      //declaring a destination array  
              
                      char[] copyTo = new char[7];  
              
                      //copying array using System.arraycopy() method  
              
                      System.arraycopy(copyFrom, 2, copyTo, 0, 7);  
              
                      //printing the destination array  
              
                      System.out.println(String.valueOf(copyTo));  
              
                  }  
              
              }

              Output:

              caffein
              

              Cloning an Array in Java

              Since, Java array implements the Cloneable interface, we can create the clone of the Java array. If we create the clone of a single-dimensional array, it creates the deep copy of the Java array. It means, it will copy the actual value. But, if we create the clone of a multidimensional array, it creates the shallow copy of the Java array which means it copies the references.

              //Java Program to clone the array  
              
              class Testarray1{  
              
              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
                

                Addition of 2 Matrices in Java

                Let’s see a simple example that adds two matrices.

                //Java Program to demonstrate the addition of two matrices in Java  
                
                class Testarray5{  
                
                public static void main(String args[]){  
                
                //creating two matrices  
                
                int a[][]={{1,3,4},{3,4,5}};  
                
                int b[][]={{1,3,4},{3,4,5}};  
                
                  
                
                //creating another matrix to store the sum of two matrices  
                
                int c[][]=new int[2][3];  
                
                  
                
                //adding and printing addition of 2 matrices  
                
                for(int i=0;i<2;i++){  
                
                for(int j=0;j<3;j++){  
                
                c[i][j]=a[i][j]+b[i][j];  
                
                System.out.print(c[i][j]+" ");  
                
                }  
                
                System.out.println();//new line  
                
                }  
                
                  
                
                }}

                Output:

                2 6 8
                6 8 10
                

                Multiplication of 2 Matrices in Java

                In the case of matrix multiplication, a one-row element of the first matrix is multiplied by all the columns of the second matrix which can be understood by the image given below.

                Matrix Multiplication in Java

                Let’s see a simple example to multiply two matrices of 3 rows and 3 columns.

                //Java Program to multiply two matrices  
                
                public class MatrixMultiplicationExample{  
                
                public static void main(String args[]){  
                
                //creating two matrices    
                
                int a[][]={{1,1,1},{2,2,2},{3,3,3}};    
                
                int b[][]={{1,1,1},{2,2,2},{3,3,3}};    
                
                    
                
                //creating another matrix to store the multiplication of two matrices    
                
                int c[][]=new int[3][3];  //3 rows and 3 columns  
                
                    
                
                //multiplying and printing multiplication of 2 matrices    
                
                for(int i=0;i<3;i++){    
                
                for(int j=0;j<3;j++){    
                
                c[i][j]=0;      
                
                for(int k=0;k<3;k++)      
                
                {      
                
                c[i][j]+=a[i][k]*b[k][j];      
                
                }//end of k loop  
                
                System.out.print(c[i][j]+" ");  //printing matrix element  
                
                }//end of j loop  
                
                System.out.println();//new line    
                
                }    
                
                }}

                Output:

                6 6 6 
                12 12 12 
                18 18 18