# Java program to find common elements in three sorted arrays

The common elements in three sorted arrays are the elements that occur in all three of them. An example of this is given as follows −

Array1 = 1 3 5 7 9
Array2 = 2 3 6 7 9
Array3 = 1 2 3 4 5 6 7 8 9
Common elements = 3 7 9

A program that demonstrates this is given as follows −

## Example

public class Example {
public static void main(String args[]) {
int arr1[] = {1, 4, 25, 55, 78, 99};
int arr2[] = {2, 3, 4, 34, 55, 68, 75, 78, 100};
int arr3[] = {4, 55, 62, 78, 88, 98};
int i = 0, j = 0, k = 0, x = 0;
System.out.print("Array1: ");
for(x = 0; x < arr1.length; x++) {
System.out.print(arr1[x] + " ");
}
System.out.print("Array2: ");
for(x = 0; x < arr2.length; x++) {
System.out.print(arr2[x] + " ");
}
System.out.print("Array3: ");
for(x = 0; x < arr3.length; x++) {
System.out.print(arr3[x] + " ");
}
System.out.print("The common elements in the 3 sorted arrays are: ");
while (i < arr1.length && j < arr2.length && k < arr3.length) {
if (arr1[i] == arr2[j] && arr2[j] == arr3[k]) {
System.out.print(arr1[i] + " ");
i++;
j++;
k++;
}else if (arr1[i] < arr2[j]) {
i++;
}else if (arr2[j] < arr3[k]) {
j++;
}else {
k++;
}
}
}
}

## Output

Array1: 1 4 25 55 78 99
Array2: 2 3 4 34 55 68 75 78 100
Array3: 4 55 62 78 88 98
The common elements in the 3 sorted arrays are: 4 55 78 