-2

I started learning myself Java fundamentals a few months ago (at the amateur level familiar with PHP for several years).

To practise I use a OCA Java SE 8 Programmer 1 Study Guide and an example exam question is given which confuses me about use of curly braces and semicolons in if-statement and can't find back in Java documentation.

I do not understand why answer E is allowed and compiles.
I've tried in Netbeans 10 (JDK 11) to evaluate warnings en hints but doesn't lead me to understand fundament.
Also trying multiple combinations that will compile ( only warning of Empty statement).
if (true) ; {;;{}{}{}} ;;;;;;;;
if (true) ;;{}{{}{}{}}; {;;{}{}{}} ;;;;;;;;
if (true) ;;{}{{}{}{}}; {;;{}{}{}}

Question:Which of the following statements will not compile?
A. if (true) ;
B. if (true) {}
C. if (true) {;}
D. if (true) {;;}
E. if (true) ; {} ;
F. All statements will compile(=correct answer)

Please help! Thanks in advance.

scorpion
  • 75
  • 9

2 Answers2

2

I do not understand why answer E is allowed and compiles.

In Java, a ; can either be a statement terminator or an empty statement, depending on the context.

Here's is how the (valid) Java code in option E is parsed:

  if (true) // <-- "if" and its condition
  ;         // an empty statement which is the "then" part of the "if"
  {}        // an (empty) block statement
  ;         // an empty statement

The first two lines are the complete if statement. The third and fourth lines are statements following the if statement.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • OK, I get it. The third en fourth line has nothing to do with the if-statement. I tried in IDE en third and fourth lines compiles even without first two lines. – scorpion Mar 31 '19 at 15:13
0

Answer E will compile because the symbol ; is allowed statement in java. In this case if statement just has empty body and make no sense, but it's valid.

From java specification 14.6. The Empty Statement:

An empty statement does nothing. EmptyStatement: ;

Execution of an empty statement always completes normally.


The {} is just an empty block of code that is allowed in java also.

See java spec 14.2. Blocks

Ruslan
  • 6,090
  • 1
  • 21
  • 36