16

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?

double-beep
  • 4,567
  • 13
  • 30
  • 40
froadie
  • 75,789
  • 72
  • 163
  • 232
  • 2
    note: the same applies to classes - you can terminate them with `;` in `C++`-style; comes in handy when using directly ported code. –  Jul 12 '15 at 16:41

4 Answers4

19

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
Greg Hewgill
  • 890,778
  • 177
  • 1,125
  • 1,260
11

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.

Andrew Hare
  • 333,516
  • 69
  • 632
  • 626
9

Or is it just something that is allowed but generally not used?

Yeap, that's it. It is valid Java but doesn't do anything:

public class X  {
    ;;;;;;;;;;;;;;;;;;
    ;;;;;
    ;
}
OscarRyz
  • 190,799
  • 110
  • 376
  • 555
0

A semicolon is interpreted as an empty statement, which is permissible whereever a statement is permissible.

EmptyStatement:
 ;

As Java specification says

http://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.6

Anisuzzaman Babla
  • 6,066
  • 4
  • 34
  • 58