Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

why no curly brackets in "case"?

Why do we not enclose the content that is executed after a condition in an if statement, like below?

switch (item.getItemId()) { case R.id.nextImage: imageIndex ++; if (imageIndex >= imageResIds.length) { image = 0; } loadimage(); break; }

1 Answer

saykin
saykin
9,835 Points

It's just how the Java compiler works. For single line of code after an if/for/while statement, it doesn't need curly brackets.

While this doesn't create a syntax error, coding convention in Java is to use curly brackets if you have any code inside an if/for/while statement. This is to avoid confusion and makes the code easier to read.

Though looking at your code, you are enclosing the code being executed in the if statement.