How to make eclipse automatically add braces to an IF statement?

JavaEclipseCurly Braces

Java Problem Overview


In Java the following is completely valid:

if (x == null)
    Y();
else
    Z();

I personally don't like it at all. I like all my IF statements to have braces:

if (x == null) {
    Y();
} else {
    Z();
}

The eclipse formatter is wonderful and can beautify my code in many other ways.

Is there a way to have it add the braces to IF statements?

Java Solutions


Solution 1 - Java

Under "Preferences": Java > Editor > Save Actions

  1. Check "Additional actions"

  2. Click "Configure…"

  3. Go to the "Code Style" tab

  4. Check "Use blocks in if/while/for/do statements" and configure to your preferences

Solution 2 - Java

Yes.

Eclipse menu: Source -> Clean Up...

Configure... -> Code Style -> Use blocks in if/while/for/do statements.

Solution 3 - Java

In Eclipse Oxygen (2017+), that option is now at:

 -> Preferences
 -> Java
 -> Code Style
 -> Clean Up
 -> Edit
 -> second tab "Code Style"

After changing, select the corresponding parts of your code and run the "Clean Up" option.

Solution 4 - Java

This is what I did: Eclipse -Preferences-Java-Code Style-Formatter-Edit-Braces Select next line as desired in each box then save as a different name (your choice).

Solution 5 - Java

I usually do it by creating a code formatter by copying the built in eclipse formatter, here:

Windows > Preferences > Java > Code Style > Formatter 

Select the profile that you have just created. and click on Edit and go to "Braces" tab.

Change the braces placement as you like (it's a WYSIWYG kind of editor, makes it easy) .

When I need to format, I just select all the text and Ctrl+Shift+F and it works fine for me.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBromideView Question on Stackoverflow
Solution 1 - Javagk5885View Answer on Stackoverflow
Solution 2 - JavaChrisHView Answer on Stackoverflow
Solution 3 - Javauser1050755View Answer on Stackoverflow
Solution 4 - JavaPeterView Answer on Stackoverflow
Solution 5 - JavaAyusmanView Answer on Stackoverflow