A basic part of Java syntax (as well as that of most C-based languages) is that semicolons are required at the end of every statement.
However, I managed to write the following program, without using any semicolons:
class Hello extends Exception
{
Hello(String s)
{
super(s)
}
}
public class HelloWorld
{
public static void main(String[] args) throws Hello
{
world((char)130)
}
static void world(char c) throws Hello
{
throw new Hello(new String(new char[]{c}))
}
}
Running NetBeans 7.4, it warned me about the lack of semicolons, but it did work properly. However, when I posted this on CodeGolf.SE, others commented that it didn't work with javac
or the Eclipse IDE. So, are semicolons required, or not?
Mostly yes, semicolons are required.
When exactly they are required can be found in the Java Language Specification. For example (from chapter 14):
14.4. Local Variable Declaration Statements
LocalVariableDeclarationStatement:
LocalVariableDeclaration ;
14.6. The Empty Statement
EmptyStatement:
;
14.8. Expression Statements
ExpressionStatement:
StatementExpression ;
14.10. The assert Statement
AssertStatement:
assert Expression1 ;
assert Expression1 : Expression2 ;
14.13. The do Statement
DoStatement:
do Statement while ( Expression ) ;
And so on and so on. As you can see the semicolons are actually right there in the spec, as literal text. I find these language specs always a bit funky to read but basically they are defining the syntax from small, sort-of atomic concepts such as 'EmptyStatement', keywords and literal text, up to the higher level structures such as do-while, if-then-else etc. So if you want to know exactly when you need a semicolon or not, study the spec carefully.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With