Expressions are the core components of statements which are ended with a semicolon: statement;

Statements may be grouped into blocks by using brackets. A block can also be empty, having no statements at all: { 0_to_N_statements }

You can use if statements with statements or blocks, although it’s always recommended to use blocks for legibility reasons.

The syntax of the if-then form is:

1

2

3

4

if(expression)

statement_or_block

Example:

1

2

3

4

5

if(i>0){

result=i;

}

The syntax of the if-then-else form is:

1

2

3

4

5

6

if(expression)

statement_or_block

else

statement_or_block

Example:

1

2

3

4

5

6

7

8

if(i>0){

result=10/i;

}

else{

result=0;

}

Be careful of tricky questions in the exam that try to confuse you by using a wrong indentation that doesn’t help you to match every if with its corresponding else:

1

2

3

4

5

6

7

8

if(false)

if(true)

System.out.println("Statement");

else{

System.out.println("Block");

}

In the previous example, the else at line 5 corresponds to the if (true) statement at line 3 and not to the if (false) at line 2 (as it could be inferred from the intentional wrong indentation). The final output of this code is nothing: lines 3 to 7 are never reached.

Note that using false as the expression for if is allowed by the Java Language Specification (e.g. for debug purposes) and doesn’t generate an Unreachable code compiler error.

That’s all coders! If you have any comments or questions, you can drop me a line or leave a comment below and I will be pleased to help you.

In case you’re looking for a complete (but still short, precise and to-the-point) study guide to help you get your valuable Oracle® Java Programmer certification, including many tricky real-exam-like questions, study sheets, and other bonuses, then the Java Certification Roadmap book is your book.

Finally, if you found this content useful and know more programmers, colleagues or friends that may be interested in getting the Java Certification, click one of the buttons belowclick the button on the bottom left corner of your screen to let them know about the Java Certification Roadmap.