According to JLS, the grammer of basic for statement is

for ( [ForInit] ; [Expression] ; [ForUpdate] ) Statement

It's also said on the JLS that 'The Expression must have type boolean or Boolean , or a compile-time error occurs.'

So to check if the syntax is valid, the parser check the code against the EBNF grammer. But the grammer doesn't specify that the [Expression] has to return boolean/Boolean value - then how does a compiler catchs that the expression isn't returning boolean during compile time?

Edited by iamcreasy

2 Years
Discussion Span
Last Post by JamesCherrill

Generally, the Expression is a comparison of two operands, such as i >= 0. This is a boolean expression which will return true if i is greater than or equal to zero, and false if less than zero. This is basic stuff. I would suggest you do some study of formal (boolean) logic. In my engineering studies we had to take one philosophy class. Since formal logic was part of the philosophy curriculum, I decided to take that. It was the most valuable educational experience for my future career in software engineering.


Java is strongly typed, which means the compiler can work out the type of an expression. See the Java Language Spec section 15.1 for details.

(or are you asking how the parser knows about the "must be boolean" rule? - in which case its because parsing the sysntax is just the easy bit of the compiler - that's followed by huge amounts of "semantic" checking, as specified in the 99% of the JLS that's not BNF syntax specs)

Edited by JamesCherrill

This article has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.