Читать книгу OCP Oracle Certified Professional Java SE 17 Developer Study Guide - Jeanne Boyarsky - Страница 171

Statements and Blocks

Оглавление

As you may recall from Chapter 1, “Building Blocks,” a Java statement is a complete unit of execution in Java, terminated with a semicolon (;). In this chapter, we introduce you to various Java control flow statements. Control flow statements break up the flow of execution by using decision-making, looping, and branching, allowing the application to selectively execute particular segments of code.

These statements can be applied to single expressions as well as a block of Java code. As described in Chapter 1, a block of code in Java is a group of zero or more statements between balanced braces ({}) and can be used anywhere a single statement is allowed. For example, the following two snippets are equivalent, with the first being a single expression and the second being a block containing the same statement:

// Single statement patrons++; // Statement inside a block { patrons++; }

A statement or block often serves as the target of a decision-making statement. For example, we can prepend the decision-making if statement to these two examples:

// Single statement if(ticketsTaken> 1) patrons++; // Statement inside a block if(ticketsTaken> 1) { patrons++; }

Again, both of these code snippets are equivalent. Just remember that the target of a decision-making statement can be a single statement or block of statements. For the rest of the chapter, we use both forms to better prepare you for what you will see on the exam.

While both of the previous examples are equivalent, stylistically using blocks is often preferred, even if the block has only one statement. The second form has the advantage that you can quickly insert new lines of code into the block, without modifying the surrounding structure.

OCP Oracle Certified Professional Java SE 17 Developer Study Guide

Подняться наверх