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

Verifying Parentheses Syntax

Оглавление

When working with parentheses, you need to make sure they are always valid and balanced. Consider the following examples:

long pigeon = 1 + ((3 * 5) / 3; // DOES NOT COMPILE int blueJay = (9 + 2) + 3) / (2 * 4; // DOES NOT COMPILE

The first example does not compile because the parentheses are not balanced. There is a left parenthesis with no matching right parenthesis. The second example has an equal number of left and right parentheses, but they are not balanced properly. When reading from left to right, a new right parenthesis must match a previous left parenthesis. Likewise, all left parentheses must be closed by right parentheses before the end of the expression.

Let's try another example:

short robin = 3 + [(4 * 2) + 4]; // DOES NOT COMPILE

This example does not compile because Java, unlike some other programming languages, does not allow brackets, [], to be used in place of parentheses. If you replace the brackets with parentheses, the last example will compile just fine.

OCP Oracle Certified Professional Java SE 17 Developer Study Guide

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