انتقل إلى المحتوى
أمين أبوزيد
منشورBEG-008-L02

العبارات والفاصلة المنقوطة والكتل

  • الدرس 2 من 6
  • 11 دقيقة قراءة
  • مبتدئ
في هذا الدرس 11 موضوعات

هذا الدرس متاح حاليًا باللغة الإنجليزية فقط، ولم تُنشر نسخته العربية بعد.

Lesson Overview

In Lesson 1 you learned that a program is a class, that the class holds main, and that main holds statements. This lesson looks closely at what happens between the braces: what counts as a statement, why every one ends with a semicolon, what a block is, and how to lay out code so a human can read it.

In the recipe-card picture, statements are the numbered steps and each semicolon is the full stop at the end of a step. A block is a group of steps that belong together, and braces are the brackets around that group. A recipe with no full stops or with a bracket left open is hard to follow for a person, and impossible for the compiler.

Why this matters: the two most common beginner compile errors, a missing semicolon and an unbalanced brace, both come from this lesson. If you understand the rule, you will find them in seconds.

This lesson builds on Lesson 1 (class, main, braces, statements run top to bottom). It only uses System.out.println statements, which you know from Hello World.

Learning Objectives

By the end of this lesson you will be able to:

  • Define a statement and say what ends it.
  • Define a block and say where blocks appear in a program.
  • Explain which pieces of a program end with a semicolon and which do not.
  • Match every { with its } and spot an unbalanced pair.
  • Indent a program consistently so that nesting is visible.
  • Explain why indentation and blank lines do not change how the program behaves, and why you still use them.

Written Explanation

What a statement is

A statement is one complete instruction to the computer. In this module, every statement you write is a call to System.out.println or System.out.print:

java
System.out.println("Order received");

The Java Language Specification defines many kinds of statements. What matters now is the shared rule: a simple statement ends with a semicolon. The semicolon tells the compiler "this instruction is finished, the next one starts after this." It plays the part of a full stop in a sentence.

The compiler reads your file as a stream of words and symbols and uses semicolons and braces to find where each instruction ends. That is why the layout of your lines does not matter to it, but the semicolons do.

What a block is

A block is a group of statements inside a pair of braces. The specification describes a block as statements between braces that are carried out in order, first to last.

You have already written blocks without naming them:

java
public class Tidy {                                   // the class body is a block of members
    public static void main(String[] args) {          // main's body is a block of statements
        System.out.println("Order received");
        System.out.println("Order saved");
    }
}

The braces after main(String[] args) contain the method body, and the statements inside run top to bottom. Later in the course you will meet if, for, and other constructs that each use a block of their own. The idea is always the same: braces group things together.

Which pieces end with a semicolon?

Here is the rule of thumb for this course:

PieceEnds with ;?
A statement such as System.out.println("x");Yes
A class declaration: public class Tidy { ... }No, it ends with its closing brace
A method declaration: public static void main(String[] args) { ... }No, it ends with its closing brace
A block { ... }No, it ends with its closing brace

A semicolon right after the main line is an error. If you write public static void main(String[] args); and then the opening brace on the next line, javac complains that the method has no body, because the semicolon said the method ended there.

An extra semicolon after a statement is not an error. The specification calls a lone ; an empty statement, which does nothing. So System.out.println("A");; compiles. Do not write it on purpose, but do not panic if you find one.

Matching braces

Every opening { needs a closing }. A good way to check is to count: walk through the file and add one for each { and subtract one for each }. At the end of the file the count must be zero, and it should never go negative on the way.

If the count ends above zero, you forgot a closing brace, and the compiler will tell you it "reached end of file while parsing". If the count goes below zero, you wrote an extra closing brace, and the compiler will complain that a class, interface, enum, or record was expected. Lesson 5 explains these messages.

Indentation: for people, not for the compiler

Java ignores extra spaces, tabs, and blank lines between tokens. The specification lists spaces, tabs, and line breaks as white space that only separates tokens. Compare these two programs. They compile to the same behaviour:

java
public class Tidy {
    public static void main(String[] args) {
        System.out.println("Order received");
        System.out.println("Order saved");
    }
}
java
public class Tidy2 { public static void main(String[] args) { System.out.println("Order received"); System.out.println("Order saved"); } }

Both print:

text
Order received
Order saved

So why do we indent? Because programs are read far more often than they are written, mostly by other people and by your future self. A common style, used throughout this course, is:

  • Put each statement on its own line.
  • Indent each nested block four spaces further than the line that opened it.
  • Put the closing } on its own line, lined up with the line that opened the block.
  • Use blank lines to separate groups of steps.

One exception to "spaces are free": spaces inside quotation marks belong to the text. "a b" prints three spaces between a and b. We return to this in Lesson 3.

Most IDEs, including IntelliJ IDEA, can reformat a file for you. The shortcut and menu name vary by version and operating system, so look for a "Reformat Code" action in the menus. If the IDE's re-indentation looks wrong, that is often a clue that a brace is missing.

Where the compiler points for a missing semicolon

The compiler cannot know a semicolon is missing until it reads the start of the next thing. So it usually reports the problem at the end of the line that needs the semicolon, with a caret ^ placed right after the last character. In some cases it can look as though the compiler points at the following line. Always check the line it names and the line above it.

Examples

Example 1: the same program, two layouts (simple)

The two Tidy programs above show the point. Run both. Both print Order received and then Order saved. Only one of them is pleasant to read. Notice also that on the long one-line version, you cannot tell at a glance which } closes which {. That is the problem indentation solves.

Example 2: a block nested inside main (practical)

A block can appear directly inside another block. This is legal Java and shows nesting clearly:

java
public class Blocks {
    public static void main(String[] args) {
        System.out.println("Start");
        {
            System.out.println("Inside the block");
            System.out.println("Still inside");
        }
        System.out.println("End");
    }
}

Output:

text
Start
Inside the block
Still inside
End

The inner block is indented one level deeper. A block on its own like this is rarely written in real programs, but it shows what later if and for bodies look like: braces around a group of statements, indented one step further in.

Count the braces as a check: the file has three { (class, main, inner block) and three }, so the count ends at zero.

Example 3: finding the missing brace by indentation (realistic)

A colleague sends you this program, and it fails to compile:

java
public class Miss {
    public static void main(String[] args) {
        System.out.println("A");
        {
            System.out.println("B");
    }
}

Count: the lines have { for the class, main, and the inner block (three), but only two } (the lines } and }). The count ends at 1, so one closing brace is missing. The compiler reports it at the end of the file:

text
Miss.java:7: error: reached end of file while parsing
}
 ^
1 error

Where should the missing } go? Re-indenting the code shows the inner block was never closed. After System.out.println("B");, add a } aligned with the inner {. The corrected version is the Blocks program from Example 2 with different text. (The exact message wording can vary between JDK versions.)

The lesson: the compiler tells you that a brace is missing. Indentation helps you see which one.

Backend Insight

Production code is reviewed by other engineers, and consistent layout is part of that review. Teams agree on a formatting style and often let a tool apply it automatically, so that arguments about spaces never reach the review. You will see formatters and code style checks in build tools later in the course.

A second backend reason: compile errors from unbalanced braces appear in build logs on servers, with only a file name and a line number to go on. Being able to count braces and read nesting fast turns a long log into a short fix.

Common Mistakes

Mistake 1: Forgetting the semicolon on a statement

  • Incorrect: System.out.println("A")
  • Correct: System.out.println("A");

Every statement ends with ;. If you forget on two lines, the compiler reports two errors, one for each line.

Mistake 2: Adding a semicolon after the main line or a class line

  • Incorrect: public static void main(String[] args);
  • Correct: public static void main(String[] args) {

Classes, methods, and blocks end with a closing brace, not a semicolon.

Mistake 3: Putting a statement outside a method

If you place System.out.println("A"); directly inside the class braces but outside main, javac rejects it with messages such as <identifier> expected. Statements go inside main.

Mistake 4: Trusting indentation to fix the structure

Indentation only shows you the structure. It does not create it. A line indented under main is not inside main unless the braces say so.

Exercises

Try each exercise yourself before opening the solutions. Hands-on items must be done on your machine.

Level A: Foundation

A1. What ends a statement in Java? What do you call a group of statements inside braces?

أظهر الحل A1

A1. A semicolon ends a statement. A group of statements inside braces is a block.

A2. Which of these end with a semicolon: (a) System.out.println("x") (b) the class declaration line (c) the main method's closing brace?

أظهر الحل A2

A2. Only (a) needs one, so as written it is incomplete: it should be System.out.println("x");. The class line (b) and a closing brace (c) do not take a semicolon.

A3. How many { and } are in the program in Example 2? What must the count be at the end of a file?

أظهر الحل A3

A3. Three { (class, main, inner block) and three }. At the end of a file the count of { and } must balance, so the running count ends at zero.

Level B: Application

B1. Re-indent this program neatly, with each statement on its own line, then compile and run it. What does it print?

java
public class Menu { public static void main(String[] args) { System.out.println("Tea"); System.out.println("Coffee"); System.out.println("Juice"); } }
أظهر الحل B1

B1.

java
public class Menu {
    public static void main(String[] args) {
        System.out.println("Tea");
        System.out.println("Coffee");
        System.out.println("Juice");
    }
}

It prints Tea, Coffee, and Juice, each on its own line.

B2. Predict what javac will say about this program, and where, then check by compiling:

java
public class Gap {
    public static void main(String[] args) {
        System.out.println("One")
        System.out.println("Two")
    }
}
أظهر الحل B2

B2. There are two missing semicolons, so expect two errors, ';' expected, one for line 3 and one for line 4. The caret appears at the end of each line. After adding the two semicolons it prints One and Two on separate lines.

B3. Write a Blocks-style program, called Sections, that prints Header, then a nested block that prints Item 1 and Item 2, then prints Footer. Indent it correctly.

أظهر الحل B3

B3. For example:

java
public class Sections {
    public static void main(String[] args) {
        System.out.println("Header");
        {
            System.out.println("Item 1");
            System.out.println("Item 2");
        }
        System.out.println("Footer");
    }
}

Output: Header, Item 1, Item 2, Footer, each on its own line.

Level C: Challenge

C1. A program has two statements on one line, System.out.println("A"); System.out.println("B");. Does it compile? What does it print? Would you accept it in a code review? Explain.

أظهر الحل C1

C1. It compiles, because the semicolons end each statement and the line break is just white space. It prints A and B on separate lines, because each is println. In a code review you would ask for each statement on its own line, since it is easier to read and to change.

C2. Count the braces in this program and say what the compiler will complain about. Then fix it.

java
public class Net {
    public static void main(String[] args) {
        System.out.println("Connecting");
    }
}
}
أظهر الحل C2

C2. There are two { and three }, so one closing brace is extra: the running count goes below zero at the last line. The compiler complains there with a message such as class, interface, enum, or record expected. The fix is to delete the final }, because it has nothing left to close.

Mini Challenge

Write a program named Checklist that prints a four-item packing list, one item per line, with a title line above it. Put the four item lines inside a nested block, indented one level deeper. Then deliberately remove one semicolon and one closing brace, one at a time, and record the compiler message for each.

Check your work: the program compiles and prints five lines when intact, the semicolon error names the line you edited, and the brace error says "reached end of file while parsing" or similar.

Summary & Next Lesson

Key takeaways

  • A statement is one instruction and ends with a semicolon.
  • A block is a group of statements inside braces. Classes, methods, and nested blocks all use braces and do not take a semicolon.
  • Every { needs a matching }. Count them to check.
  • Spaces, tabs, and blank lines do not change how a program behaves, but indentation makes nesting visible to people.
  • A missing semicolon is usually reported at the end of the line that needs it, so check the line above the one the compiler names.

Next lesson

You can write correct statements. Next, "Printing output" looks at what goes inside the parentheses of println: text, numbers, joining values with +, and the difference between print and println.

Self-check

  1. What ends a statement?
  2. Does a method declaration like public static void main(String[] args) { ... } end with a semicolon?
  3. If your brace count ends at 1, what is wrong?
  4. Do extra blank lines change the program's output?
  5. Why is the line above the reported one worth checking?
أظهر الإجابات
  1. A semicolon.
  2. No. It ends with its closing brace.
  3. One closing brace is missing.
  4. No. White space between tokens is ignored, though spaces inside quoted text are part of the text.
  5. The compiler notices a missing semicolon only when it reads the next token, so the report can look like it is one line late.

References

التطبيق

طبّق هذا الدرس بمختبر الوحدة وتمارينها واختبارها.

المختبر والتمارين الاختبار

تعليم الدرس كمكتمل اختياري ويمكنك التراجع عنه في أي وقت. يبقى تقدمك محفوظًا في هذا المتصفح.

اكتب للبحث في المستويات والمراحل والوحدات والدروس.