Compare Two Long Arrays
We will now implement the compare()
method to compare two long arrays. We will create two arrays named array1
and array2
with respective values, then we will use a for
loop to iterate through both arrays and compare respective elements at the same index. Then we will create separate output messages for results greater, smaller, or equal to 0.
import java.lang.Long;
public class LongCompare {
public static void main(String[] args){
long[] array1 = {1L, 2L, 3L, 4L, 5L};
long[] array2 = {2L, 2L, 3L, 4L, 7L};
for (int i = 0; i < array1.length; i++) {
int result = Long.compare(array1[i], array2[i]);
if (result > 0){
System.out.println(array1[i] + " is greater than " + array2[i]);
} else if (result < 0){
System.out.println(array2[i] + " is greater than " + array1[i]);
} else {
System.out.println(array1[i] + " and " + array2[i] + " are equal.");
}
}
}
}
To run this code, we need to use the following command in the terminal:
javac LongCompare.java && java LongCompare
The output will look like this:
1 is less than 2
2 and 2 are equal.
3 and 3 are equal.
4 and 4 are equal.
5 is less than 7