Task #3: Arrays and Methods
In this task, you are being asked to write a method that manipulates arrays in Java.
Write a method called printCommon that accepts two integer arrays as arguments and
print all the common elements from the two arrays.
You may use the following header for this method:
static void printCommon(int[] firstArray, int[]
secondArray)
For example, if the elements of two arrays are {4, 2, 3, 17, 19, 12, 16, 7, 100}
and {3, 9, 5, 12, 6, 17, 8, 7}, then the method should print {3, 17, 12, 7}.
NOTE:
● Declare and initialize both arrays without taking input from user.
● Both arrays do not need to be of the same size.
1. Create a program called ArrayPrintCommonLab2.java
2. Correctly display appropriate messages.
class Main {
public static void main(String[] args) {
int[] arr1 = {4, 2, 3, 17, 19, 12, 16, 7, 100};
int[] arr2 = {3, 9, 5, 12, 6, 17, 8, 7};
printCommon(arr1, arr2);
}
private static void printCommon(int[] firstArray, int[] secondArray) {
for (int i : firstArray) {
for (int j : secondArray) {
if (i == j) {
System.out.print(i + " ");
}
}
}
}
}
Comments
Leave a comment