Search code examples
javalogical-operatorsparentheses

What is difference between using logical operators using parentheses?


I am getting different results: -1 if I use parentheses and 1 if I don't use parentheses.

For test case "30/10/2019" I am getting -1 if I use parentheses and 1 if I don't use parentheses in the following line:

else if((mm==1||mm==3||mm==5||mm==7||mm==8||mm==10||mm==12) && mm<13 && mm>0 && dd>0 && dd<32) return 1;

What is the difference between above line and below line?

else if(mm==1||mm==3||mm==5||mm==7||mm==8||mm==10||mm==12 && mm<13 && mm>0 && dd>0 && dd<32) return 1;
public class Utility {
   public static int checkDate(String date){
     String []st;
   if((date.charAt(2)=='.' && date.charAt(5)=='.')||(date.charAt(2)=='/' && date.charAt(5)=='/')||(date.charAt(2)=='-' && date.charAt(5)=='-'))
   {
       String token = Character.toString(date.charAt(2));
       if(date.charAt(2) == '.') st = date.split("\\.");
       else st = date.split(token);

       int dd = Integer.parseInt(st[0]);
       int mm = Integer.parseInt(st[1]);
       int yy = Integer.parseInt(st[2]);

        if(mm == 2 && dd>0 && dd<30 && mm<13 && mm>0) return 1;

        else if((mm==1||mm==3||mm==5||mm==7||mm==8||mm==10||mm==12) && mm<13 && mm>0 && dd>0 && dd<32) return 1;

        else if((mm==4||mm==6||mm==9||mm==11) && dd>0 && dd<31 && mm<13 && mm>0) return 1;

        else return -1;
   }
   else return -1;
 }
}

import java.util.Scanner;


public class DateValidation {

    public static void main(String[] args) {

       // STUDENT CODE BEGINS HERE
        Scanner sc = new Scanner(System.in);
    String dt=sc.next();
    Utility ut = new Utility();
    int flag = ut.checkDate(dt);
    if(flag==1)
        System.out.println("Valid");
    else
        System.out.println("Invalid");
       // STUDENT CODE ENDs HERE

    }
}

Solution

  • Parentheses decide the order these booleans are resolved. And binds stronger than Or. In your case you ask for:

    mm==12 && mm<13
    

    So left comparison and right comparison must resolve to true. They don't, as you are in month 10. With parenthesis you decide to check if your month value is valid at all, this resolves to true, and then the && check resolves to true as well.