Is it ok if I omit curly braces in Java? [closed]

It won’t change anything at all apart from the maintainability of your code. I’ve seen code like this:

for (int i = 0; i < size; i++)
   a += b;
   System.out.println("foo");

which means this:

for (int i = 0; i < size; i++)
   a += b;
System.out.println("foo");

… but which should have been this:

for (int i = 0; i < size; i++) {
   a += b;
   System.out.println("foo");
}

Personally I always include the brackets to reduce the possibility of confusion when reading or modifying the code.

The coding conventions at every company I’ve worked for have required this – which is not to say that some other companies don’t have different conventions…

And just in case you think it would never make a difference: I had to fix a bug once which was pretty much equivalent to the code above. It was remarkably hard to spot… (admittedly this was years ago, before I’d started unit testing, which would no doubt have made it easier to diagnose).

Leave a Comment