Search code examples
javalogical-or

Logical OR in Java shows unexpected results


Here's my code:

Scanner s = new Scanner(System.in);
int t = s.nextInt();
String [] pair_left = new String[t];
String [] pair_right = new String[t];

for (int i = 0; i < t; i++) {
    pair_left[i] = s.next();
    pair_right[i] = s.next();
}
HashSet hs1=new HashSet();
HashSet hs2=new HashSet();
int j=0;
for(int i=0;i<t;i++){
    if(hs1.add(pair_left[i])||hs2.add(pair_right[i])){
      j++;
      System.out.println(j);
    }
    else {      
       System.out.println(j);
    }
}

and the input is :

5
john tom
john mary
john tom
mary anna
mary anna

now when i=2 then hs1.add(pair_left[i]) returns false and then it goes to hs2.add(pair_right[i])which also return 'false'so hs1.add(pair_left[i])||hs2.add(pair_right[i]) should return 'false' but in my case it shows true. Why?

And when I replace logical OR with bitwise OR then it shows correct result. If there any better approach of doing this then give that also.


Solution

  • You should be aware that || logical OR is short circuited, so if hs1.add(pair_left[i]) returns true, hs2.add(pair_right[i]) is not evaluated.

    On the other hand, as you noticed, when you use |, which is non-short circuited logical OR (note that | is not only bitwise OR), both operands are always evaluated.