3

I am aware that semicolons are required to end statements, as in this piece of code:

public class Main{
    public static void main(String[] args){
        System.out.println("blah blah blah and stuff")
    }
}

A semicolon is required at the end of the println statement, or else the program won't compile.

Recently, I accidentally placed two semicolons at the end of the println statement:

System.out.println("blah blah blah and stuff");;

I noticed it, so I began to place semicolons everywhere in my program

public class Main{;;;;;;
    public static void main(String[] args){;;;;;;;;
        System.out.println("blah blah blah and stuff");;;;;;
    };;;;;;
};;;;;

This code compiles, prints the string, with no errors or unexpected results. I have searched about why the compiler appears to have simply ignored these semicolons, but never found anything that specifically mentions this. So, why are these semicolons not producing a syntax error?

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140

4 Answers4

8

That is known as the empty statement and it is valid.

An empty statement does nothing.

It doesn't have many uses

while (checkCondition()) // may have some side effects
    ;
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
2

A semicolon is used to terminate statements indicating the end of a statement

so when you say

int i=5;
;

it just means that that is an empty statement. Though there is no use of it, it is not considered as an error as it simply denotes an end of statement which is empty.

Thirumalai Parthasarathi
  • 4,541
  • 1
  • 25
  • 43
1

This is how compiler works.

When compiler compiles your code it follows certain rules called Context Free Grammar, which is defined differently for different languages.

In the C programming language, there might be a rule such as

statement -> (optional_other_stuff) + ';'

which implies each statement must end with a semicolon.

In other words, missing semicolon will make the statement unrecognizable by a compiler, but extra semicolon merely considered as an empty statement for compiler

miushock
  • 1,087
  • 7
  • 19
0

Its empty statement and when you compile the class it is removed from it.

So it make no difference.

Kick
  • 4,823
  • 3
  • 22
  • 29