Evaluation of the expression 1 <= month <= 12

I am trying to evaluate an expression (1 <= month <= 12) in an if condition.

This statement seems valid in javascript, but not in Java.

In Java,

 int month = 0; boolean flag = (1 <= month <= 12); 

It produces the following error:

The operator <= is undefined for the argument type (s) boolean, int

In javascript

 var month = 0; console.log('Expression evaluates to: ', (1 <= month <= 12)); 

It always returns true no matter what the value of the month is.

Can someone explain:

  • If this is a valid expression or not?
  • Why does it always return true in javascript?
  • Why does java consider this an invalid expression?

And I know that I can make it work like this (1 <= month && month <= 12) . So, not looking for a solution, but an explanation.

Thanks. Also let me know if my questions are not clear.

+6
source share
3 answers

<= not associative, so you cannot use it by repeating. You can specify it with:

 1 <= month && month <= 12 

The reason is because the JavaScript parser parses 1 <= month <= 12 as:

 (1 <= month) <= 12 

This is a consequence of the JavaScript grammar, they could define it differently, but that would complicate things a bit. Most grammars define expressions as:

 expr -> [0-9]+ expr -> identifier expr -> expr '<=' expr 

(with LALR).

And Java uses the following (approximate) grammar:

 expr -> numExpr '<=' numExpr expr -> numExpr numExpr -> identifier numExpr -> [0-9]+ (...and so on...) 

In Java, in this way, it is even impossible to parse such an expression (unless you make a throw that numExp will make it numExp ).


For the JavaScript part, why does it always return true ?

Now (1 <= month) is logical (true / 1 or false / 0 ), and this value cannot compare (reasonably) with 12 ( 0 and 1 always less than or equal to 12 ). Only very limited programming languages ​​are supported.

+10
source

Regarding the subquery

Why does java consider this an invalid expression?

This is because Java rates it as follows:

 (1 <= month) <= 12 boolean <= int 

Boolean and int cannot be compared due to type safety.

+3
source

The reason is related to short circuit assessment (which is the method used by most programming languages ​​to evaluate logical expressions). Essentially, what happens is that the expression evaluates from left to right and transforms along the way so ...

 1 <= month <= 12 

Gets rated as:

 (1 <= month) <= 12 

Anything gives you:

 true <= 12 /* or */ false <= 12 

As you can see, in Java (since it is type safe) you get a type error. Because you cannot use the <= operator on a logical level. In JS, booleans are always <= for a number (you can check this on your console).

Hope that answers your question!

+3
source

Source: https://habr.com/ru/post/984622/


All Articles