-2

I am a beginner in Java. I need to compare two arrays of string and find out if any value from the first array matches any value in second array?

Here is my function which does not work as expected,

public static boolean CheckStatAppearinLeftAndRight1(String[] array1, String[] array2)
{
    boolean b = false;
    for (int i = 0; i < array2.length; i++) 
    {
        for (int a = 0; a < array1.length; a++)
        {
            if (array2[i] == array1[a])
            {
                b = true;
                break;
            }
            else
            {
                b = false;
            }
        }
   }
   return b;
}  

Can someone please point out the issue here?

Amar
  • 13,202
  • 7
  • 53
  • 71

4 Answers4

1
if (array2[i] == array1[a])

should be

if ((array2[i]).equals(array1[a]))
0

try>>>

import java.util.Arrays;

public class Main {
   public static void main(String[] args) throws Exception {
      int[] ary = {1,2,3,4,5,6};
      int[] ary1 = {1,2,3,4,5,6};
      int[] ary2 = {1,2,3,4};
      System.out.println("Is array 1 equal to array 2?? "
      +Arrays.equals(ary, ary1));
      System.out.println("Is array 1 equal to array 3?? "
      +Arrays.equals(ary, ary2));
   }
}
Muthuraja
  • 551
  • 5
  • 13
0

Use array2[i].equals(array1[i]) instead of using == operator. == operator compares the two references and would give you false. equals() method is already overriden in class String which matches the exact characters from two different String Objects.

Nishant Lakhara
  • 2,295
  • 4
  • 23
  • 46
-1
    boolean b = false;
    for (int i = 0; i < array2.length; i++) 
    {

        for (int a = 0; a < array1.length; a++)
        {

            if (array2[i].equals(array1[a]))
            {
                b = true;
                break;
            }
            else
            {
                b = false;

            }
        }
        if(b)
            return b;
    }
}  
Vasanth
  • 34
  • 3