Free Puzzle Questions with Answer using Java, C#, JavaScript and PHP

Java Quiz - Filter Common Array Elements

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package filtercommonarrayelements;

/**
 *
 * @author Bereket
 */
public class FilterCommonArrayElements {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        int[] sample1 = {};
        int[] sample2 = {1, 2, 3};
        
        int[] result = FilterCommonElement(sample1, sample2);
        
        for(int i=0; i< result.length; i++){
            System.out.println(result[i]);
        }
    }
    
    static int[] FilterCommonElement(int[] firstArray, int[] secondArray){
        int[] output = {};
        
        if(firstArray == null || secondArray == null){
            return null;
        }
        else if(firstArray.length == 0 || secondArray.length == 0){
            return output;
        }
        else{
            int commonElementArraySize;
            
            if(firstArray.length > secondArray.length){
                commonElementArraySize = secondArray.length;
            }
            else{
                commonElementArraySize = firstArray.length;
            }
            
            int[] commonElements = new int[commonElementArraySize];
            int counter = 0;
            
            for(int i=0; i < firstArray.length; i++){
                for(int j=0; j < secondArray.length; j++){
                    if(firstArray[i] == secondArray[j]){
                        commonElements[counter] = firstArray[i];
                        counter = counter + 1; //counter++
                    }
                }
            }
            
            if(counter == commonElementArraySize){
                return commonElements;
            }
            else{
                int[] finalCommonElements = new int[counter];
                
                for(int x=0; x < finalCommonElements.length; x++){
                    finalCommonElements[x] = commonElements[x];
                }
                
                return finalCommonElements;
            }
        }
    }
    
}