Doubt between block and statement

Asked

Viewed 81 times

2

In that 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 is the C, because a block is a statement. However it can be D too. Which is the correct one?

  • Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site.

2 answers

2

Initially I answered generically and researching 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 language and the 3 commands that have something printed.

In fact in Section 14.5 of the specification grammar shows that the block itself is a statement. Apart from that part it’s not so clear that it’s true.

Behold What are statements and operators?.

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).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.