java-semicolon after for loop,while loop,if statement



In this tutorial we will discuss about the problem by adding the semicolon after for-loop,while-loop and if-statement. This concept is very important to know from Selenium WebDriver perspective as well. We mainly use for-loop for iterating the List of WebElements.
Also, one important key-note here is adding semicolon does not throw any compilation error in Eclipse.
So, it would be difficult to understand the reason why the code is not working as expected.
Else we can depend on the static code checking tools such as following which helps in identifying those issues.

Semicolon

java-semicolon after for loop,while loop,if statement

Adding Semicolon for if-Statement:

int i = 1;
if(i==2);//condition is false
{
System.out.println("if-statement");//Empty Statement will be executed
}

Output:

if-statement

Conclusion:

if(i==2); Adding semi-colon for if-statement the line is ended.
The code in the curly braces executes irrespective of the condition is true or false.


Adding Semicolon for for-loop:


for(int i=0;i>10;i++);//condition is false
{
System.out.println("in for-loop");//Empty Statement will be executed
}

Output:

in for-loop

Conclusion:

for(int i=0;i>10;i++); Adding semi-colon for-loop the line is ended.
The code in the curly braces executes irrespective of the condition is true or false.


Adding Semicolon for while-loop:

int j = 1;
while(j>10);
{
System.out.println("in while-loop");//Empty statement will be executed.
}

Output:

in while-loop

Conclusion:

while(j>10); Adding semi-colon for while-loop ends the line.
The code in the curly braces executes irrespective of the condition is true or false.

Therefore adding the semicolon executes the empty statements without any errors.

Highlighting the Empty Statements with Errors in Eclipse

Enable Empty Statement

Enable Empty Statement


Enabling Empty Statements shows the following Errors during compilation in Eclipse:
Empty Statement Errors

Empty Statement Errors


2 comments on “java-semicolon after for loop,while loop,if statement

  1. sunil

    i mean like below:
    if(i==0);
    System.out.println(i);
    if(j==0);
    System.out.println(j);

    actual code is as below:
    if(i==0){
    System.out.println(i);
    if(j==0){
    System.out.println(j);
    }
    }

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *