Is it ok if I omit curly braces in Java?

vedran picture vedran · Nov 5, 2011 · Viewed 61k times · Source

I've searched for this, but couldn't find an answer and for whatever reason I was too ashamed to ask professor, due to that feeling when hundreds of people stare at you...

Anyhow, my question is what's the importance of having brackets? Is it OK if I omit them? Example:

for (int i = 0; i < size; i++)  {
   a += b;
}

vs

for (int i = 0; i < size; i++)
   a += b;

I know both of them will work, but if I omit the brackets (which I tend to do a lot, due to visibility) will that change anything, anything at all? As I said, I know it works, I tested it dozen of times, but now some of my uni assignments are getting larger, and for some reason I have irrational fear that in the long run, this my cause some problems? Is there a reason to fear that?

Answer

Jon Skeet picture Jon Skeet · Nov 5, 2011

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).