Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When would you put a semicolon after a method closing brace?

Tags:

java

syntax

I've been programming in Java for a while, and I've just come across this syntax for the first time:

public Object getSomething(){return something;}; 

What's interesting me is the final semicolon. It doesn't seem to be causing a compiler error, and as far as I know isn't generating runtime errors, so it seems to be valid syntax. When would I use this syntax? Or is it just something that is allowed but generally not used?

like image 766
froadie Avatar asked Apr 27 '10 19:04

froadie


People also ask

Can you use a semi-colon after a bracket?

Sometimes the parenthetical material is part of a longer sentence part that will be set off by a comma, colon, or semicolon. These pieces of punctuation always come after the parenthetical material, never before it or inside the parentheses.

What is the use of semicolon and curly braces?

Semicolons go at the end of lines that do not end in a curly brace or to separate statements on the same line. It does no harm to use them after a closing brace, or to wear suspenders and a belt, but it does look a little nerdy.

Do you need semicolon after curly braces Javascript?

Avoid! You shouldn't put a semicolon after a closing curly bracket } . The only exceptions are assignment statements, such as var obj = {}; , see above. It won't harm to put a semicolon after the { } of an if statement (it will be ignored, and you might see a warning that it's unnecessary).

Which loops needs a semi-colon after?

while' loop syntax needs a semicolon at the end. Whereas for and while loop do not need a semi-colon terminator at end.


2 Answers

It's allowed by the grammar as a concession to harmless syntax errors, but it's not generally used and doesn't mean anything different (than leaving the semicolon out).

Just as a }; inside a method (such as after an if block) is a null statement and is allowed, an errant semicolon outside a method is considered a null declaration and is allowed.

Specifically, the following production from the Java Language Specification allows this:

ClassBodyDeclaration:
  ; 
  [static] Block
  ModifiersOpt MemberDecl
like image 83
Greg Hewgill Avatar answered Oct 26 '22 20:10

Greg Hewgill


It's simply an empty statement - it is most likely a typo.

Consider the fact that in all C-based languages, a statement is terminated with a semicolon. A hanging semicolon like this simply terminates the current statement which in this case is nothing.

like image 22
Andrew Hare Avatar answered Oct 26 '22 20:10

Andrew Hare