Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Java

Gabriel Bogo
Gabriel Bogo
416 Points

About the "if" statement.

Why isn't there a semicolon after the "if" statement is written?

1 Answer

Gavin Ralston
Gavin Ralston
28,770 Points

In one word: Braces.

The TL;DR:

if runs exactly one statement, and no more. So does while ..and else and for

if (1 == 1) System.out.println("sup");

That's all it can do. If something is true, do one thing.

So the way around that is curly braces. Everything inside the braces is packaged up as one "statement of statements" and fed into it.

So since everything inside those braces is a statement, and all statements have to end with a semi-colon, you can kind of think of that last statement inside the braces as being the "closing semicolon"

public static void main (String[] args)
    {
        { System.out.println("Sup"); }
    }   // perfectly valid way to write a one line main method, but hey...

So that means this if statement is successfully closed on the last line:

if (1 == 1)  {
    doOneThing();
    doAnotherThing(); 
    doTheLastThing();   // you ended your "statement of three statements" with a semi-colon, so we're happy
    }  // this brace is just closing up the package of statements you're sending in