Doubt between blocks and statement

2

On this question, what would be the right answer?

  

How many statements are there in the code below? Warning: This is a   tricky one. The code is valid.

{ println("Step 2");
  { println("Step 2a");
    { println("Step 2a.1");
  { }
    }   
  }
}

a.1
b.3
c.4
d.7
e.None of the above

I believe it's C because a block is a statement. However it can be D as well. Which one is correct?

    
asked by anonymous 19.10.2017 / 01:49

2 answers

2

Initially I answered generically and searching over there was documentation that implied that a block is not a statement .

Seeing the Java specification makes it clear that the right answer is D, there are 7 statements . There are 4 blocks that are considered statements by the language and the 3 commands that print something.

In fact, section 14.5 of the specification the grammar shows that the block itself is a statement . Outside this part is not so clear that this is true.

See What are statements and operators? .

    
19.10.2017 / 02:04
1

Based on the Java Language Specification 14.5 Statements and linked chapters - here only the important parts (IMHO):

Statement:
    StatementWithoutTrailingSubstatement

StatementWithoutTrailingSubstatement:
    Block
    ExpressionStatement

Block:
     { [BlockStatements] } 

BlockStatements:
    BlockStatement {BlockStatement} 

BlockStatement:
    Statement

ExpressionStatement:
    StatementExpression ;

StatementExpression:
    MethodInvocation

So the block, empty or not, counts as a Statement (by JLS), and obviously each println is also a Statement ( MethodInvocation ).

    
19.10.2017 / 19:19