Automatically Place a Semicolon at the End of Java Statements in Eclipse
Join the DZone community and get the full member experience.
Join For Freewe 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.
Opinions expressed by DZone contributors are their own.
Comments