Automatically place a semicolon at the end of Java statements in Eclipse

We all know that Java statements are terminated by a semicolon (;), but they’re a bit of a pain to add to the end of a line. One way would be to press End (to move to the end of the line) then press semicolon, but this is tedious. Because this is something that you do often it’s worth learning how to do this faster.

It’s a good thing Eclipse can automatically put the semicolon at the end of the line, no matter where you are in the statement. It’s as easy as setting one preference and there’s a bonus preference for adding braces to the correct position as well. For something so small, it saves a lot of time.

So in the example below, if you imagine that your cursor is placed after the word blue since you were editing the string. Pressing semicolon will cause Eclipse to place the semicolon after the closing bracket at the end. Nice.


System.out.println("The house is blue")

How to set the semicolon preference

The preference is disabled by default, so you have to enable it. Go to Window > Preferences > Java > Typing. Then enable Semicolons under the section Automatically insert at correct position.

Now when you press semicolon from anywhere in a statement, Eclipse adds a semicolon to the end of the line and places the cursor right after the semicolon so you can start editing the next line.

The preference should look like this:

Notes:

  • Sometimes you’d want to add a semicolon to a string literal instead of at the end of the line. Eclipse caters for this by allowing you to press Backspace after you pressed semicolon. Pressing Backspace will remove the semicolon from the end of the line, move your cursor to the original position in the string and add the semicolon to the string.
  • If there’s already a semicolon at the end of the line, Eclipse won’t try to add another to the end. It will just add the semicolon to wherever you placed it.
  • Eclipse is smart enough to know that for for loops you’d want to add the semicolon to the middle of the statement (eg. when editing the initialiser, condition and increment code).

Bonus Tip: You can also add braces automatically at the correct position by selecting the Braces option on the preference page. This comes in handy when your coding standards require braces to be on the same line as the control structure statement. For example, when adding a for or while loop, you can type { at any place in the first line and Eclipse will insert it at the end of the line.

Related Tips

Support Eclipse On E

4 thoughts on “Automatically place a semicolon at the end of Java statements in Eclipse

  1. thanks buddy, it worked . My version of eclipse is actually in Window > Preferences > Java > Editor > Typing . Missed the Editor on your tutorial, but took me close enough to figure it out. Thank you very much!!!!!

Leave a Reply

Your email address will not be published. Required fields are marked *