Login
Your Email
Pasword
Home
Write
Trending
History
Liked
Dashboard

How to compare arrays in Java? How to use Final and Jagged array?

Unlike C++ an arrays are first class objects in the Java.

Do you have similar website/ Product?
Show in this page just for only $2 (for a month)
Create an Ad
0/60
0/180
An easy way is to run a loop and compare elements one by one. Java provides a direct method Arrays.equals() to compare two arrays. There is a list of equals() methods in Arrays class for different primitive types (int, char, ..etc) and one for Object type (which is base of all classes in Java).
import java.util.Arrays;
 class Test
{
 public static void main (String[] args)
 {
int arr1[] = {1, 2, 3};
 int arr2[] = {1, 2, 3};
if (Arrays.equals(arr1, arr2))
 System.out.println("Same");
else
 System.out.println("Different");
}
}

Deep comparison of  array contents
Arrays.equals() is not able to do deep comparison but Java provides another method for this Arrays.deepEquals() which does deep comparison.
import java.util.Arrays;
 class Test
{
 public static void main (String[] args)
 {
 int inarr1[] = {1, 2, 3};
 int inarr2[] = {1, 2, 3};
 Object[] arr1 = {inarr1}; 
arr2 = {inarr2};
if (Arrays.deepEquals(arr1, arr2))
 System.out.println("Same");
 else
 System.out.println("Different");
 }
 } 

Final arrays in Java
The array arr is declared as final, but the elements of array are changed without any problem. Arrays are objects and object variables are always references in Java.
class Test
 {
 public static void main(String args[])
 {
 final int arr[] = {1, 2, 3, 4, 5};
 // Note: arr is final
 for (int i = 0; i < arr.length; i++)
 {
 arr[i] = arr[i]*10;
 System.out.println(arr[i]);
 }
 }
 }
Run the code on IDE to check the output.
class Test
 {
 int p = 20;
 public static void main(String args[])
 {
 final Test t = new Test();
 t.p = 30;
 System.out.println(t.p);
 }
 }

Jagged Arrays in Java
Jagged array is array of arrays such that member arrays can be of different sizes, we can create a 2-D arrays but with variable number of columns in each row. These type of arrays are also known as Jagged arrays.
class Main
{
 public static void main(String[] args)
 {
 int arr[][] = new int[2][]; // Making  array Jagged 
 arr[0] = new int[3];
 arr[1] = new int[2];
 int count = 0; 
for (int i=0; iarr[i][j]=count++;
System.out.println("Contents of 2D Jagged Array");
for (int i=0; i{
for (int j=0; jSystem.out.print(arr[i][j] + " ");
System.out.println();
 }
 }
 }
Run the code on IDE to check the output.
CONTINUE READING
array comparison
Final array
Jagged array
Java
Ayesha
Tech writer at newsandstory