Is it the right way to compare the arrays? If not, write a better code to first
ID: 3834018 • Letter: I
Question
Is it the right way to compare the arrays? If not, write a better code to first check the lengths of these two arrays and then compare each element from the two arrays to display the right answer which is "The arrays are the same" public class Lesson3 {Public Lesson3(){} public static void main(string[] args) {//TODO Auto-generated constructor stub int [] f Array = {5, 10, 15, 20, 25}; int [] sArray = {5, .10, 15, 20, .25}; if(f Array == S Array) {System.out.println ("The arrays are same");} else {System.out.println ("The arrays are not the same");}}}Explanation / Answer
1. No, it is not the right way to compare the arrays. In the above program, arr1 and arr2 are two references to two different objects. So when we compare arr1 and arr2, two reference variables are compared, therefore we get the output as “Not Same”
2.A simple way to compare two arrays in java is to run a loop and compare elements one by one.Java provides a direct method Arrays.equals() to compare two arrays.
Here is the code to compare the two given arrays.
public class Lesson3 {
public class Lesson3 {
}
public static void main(String[ ] args)
{
int arr1[ ] = {5,10,15,20,25};
int arr2[ ] = {5,10,15,20,25};
if (Arrays.equals(arr1, arr2))
{
System.out.println("The arrays are same");
}
else
System.out.println("The arrays are not the same");
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.