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 Java Basics Perfecting the Prototype Reviewing Our Feedback

Advantages of a "code block"

What are the advantages of a code block, what is it used for?

3 Answers

A code block is used when we want to group together a set of statements that are meant to be executed together. A code block is represented by an opening and closing curly brackets.

Functions are code blocks. Creating code blocks makes your program much more flexible in terms of what it can do based on user interaction. As manav said, it's basically just a set of statements that run together.

The if-statement can only have a single statement in its body. So this won't work as the indentation might suggest:

if (2 < 3)
    console.printf("Looks like we");
    console.printf("know some math");

Code blocks are a way around this. You can group multiple statements together, so they act like a single one.