The semicolon at the end of the if statement

Today, after half an hour of searching for an error, I found that you can put a semicolon after the if statement instead of code, for example:

if(a == b); // Do stuff 

Which basically means that everything will be executed independently a whether it is equal to b or not, and the if does not make any sense. Why doesn't Java give me an error? Are there any situations in which this would be helpful?

+63
java if-statement semicolon
Jan 01 '13 at 17:22
source share
18 answers

Why is this happening?

The Java Language specification says that:

Empty expression

An empty instruction does nothing.

 EmptyStatement: ; 

The execution of an empty instruction always runs normally

This essentially means that you want to execute an empty statement if a == b

 if(a == b); 

What to do:

There are two main solutions to this problem:

  • You can avoid problems with an empty statement by formatting the code and surrounding things inside an if with { and } . By doing this, your empty statement will be more readable.

     if(a == b){ ; } 
  • You can also check the tools used to analyze static code, for example:

    They can instantly highlight problems like this one.

I would recommend combining both solutions.

+82
Jan 01 '13 at 17:25
source share

Is there any situation in which this would be helpful?

Is it helpful? How in the section "makes your code cleaner, more understandable, faster, more convenient"? It's my pleasure. This is most likely bad, confusing code.

But it is not necessarily benign. Such an operator may perform actions and / or change state due to methods that cause side effects, and possibly evaluate these methods due to a short circuit of the operators .

 if( a() && b() ); 

Here a() or b() can do something, and b() will only execute if a() is true.

As for why, I think the answer simply is that it would be worse to deviate from certain expected behavior (e.g. statements like while(reader.read()); ) than an alternative to developers who write bad code .

Writing bad code is always possible. And just to repeat, it will be bad code almost anyway.

+28
Jan 01 '13 at 17:25
source share

Possible use case:

 if (a==b); else { // Do something } 

Not good, but possible.

However, I believe that the Java specification should ban empty if .

+19
Jan 01 '13 at 17:30
source share

If you use Eclipse, you can warn you about these statements:

Java-> Compiler-> Errors / Warnings

+11
May 7 '13 at 10:09
source share

If you use an if , the first statement after if will be executed if the condition is true. If you have a block after if (with curly braces), it expects the whole block. If there is no block, it takes into account only one statement. A single semicolon is an empty statement. You can also write code from an example:

 if(a==b) { ; } 
+7
Jan 01 '13 at 17:27
source share

This is the old remainder of the days when there is a stronger expression for syntactic sugar to distinguish expressions from statements.

Basically, the comma was used as a separator for list items, so the semicolon was used as a separator for the "list of operators". The disadvantage is the handling of null elements in lists and null statements in blocks.

Java uses the explicit null keyword in the list of elements, but the "null operator" is just an empty string. Allowing the existence of an empty string is a deduction from a tradition inherited from C.

What for? Especially with the if , when you know that no statements are executed: since some if statements have side effects:

  int c; if ((c = in.read()) != -1); 

Yes, this is not a good example, but basically it says that it reads a byte from a stream and does nothing. It may be useful in some cases, but even if this example is not the best, it illustrates the intention. We want to feel the side effects of the expression without accidentally making any statements.

+6
Jan 01 '13 at 22:13
source share

I can’t figure out where this is useful. This can be useful for cycles like

  while(do something); 

or

  for(init; do something; something else); 

If you regularly use code formatting in your IDE, these errors become apparent. Some IDEs highlight this as a likely mistake.

+5
Jan 01 '13 at 17:25
source share

I would agree with you that there is no useful goal for a person. I suspect it there because it simplifies the definition of language; this means that the thing that comes after if is the same as the thing that comes after while , for example.

+4
Jan 01 '13 at 17:27
source share

Why? This is because it is easier for compilers. You do not need to make a special case for checking the semicolon after if(cond) and has additional permission

 if (cond && maybeFunc()) ;// Code here I want to ignore 

Despite the fact that it’s a really scary idea to resolve this. It is simply easier to resolve, and then add a case to verify this.

+3
Jan 01 '13 at 23:57
source share

Java allows an empty block anywhere a statement block is allowed. I am sure that this general rule for all blocks simplifies the compiler.

I agree that this is primarily the cause of errors that are difficult to find. I always use curly braces around blocks, even if there is one statement, but Java allows you to make a block with curly braces at any time, so using curly braces cannot save you from this fate. For example, I once spent 4 hours finding something like this:

 while (condition); { statement; statement; } 

The semicolon at the end of the first line was a typo, accidentally making the statement block for the while loop empty. Since the syntax is valid, the program compiled and works fine, just not the way I wanted it to. It was really hard to find.

I can think of one situation when it is very nice that you are allowed to have empty blocks, and this is something like this:

 if (condition1) { do_action_1(); } else if (condition2) { //nothing really to do in this case } else if (condition3) { do_action2(); } else { do_action3(); } 

In the above example, you want to be able to separate the various conditions. Remember that these conditions can be overlapping, so it is not always possible to change the order. If one of the conditions really doesn’t need anything, it’s good that Java allows you to have an empty block. Otherwise, the language will need some form of the "noop" method to use when you really don't want to do anything.

I personally would prefer the explicit noop operator, but that's not how Java defines it.

+2
Jan 01 '13 at 23:02
source share

Just FYI about usability and what difference does it make or can make if there is such an operator

Consider the code snippet as shown below.

 int a = 10; if ((a = 50) == 50); System.out.println("Value of a = " + a); 

Obviously, in this case, the if changes the output. Thus, a similar expression may matter.

This is a situation where it can be useful or better said to affect the program.

+2
Jan 02 '13 at
source share
 if(a==b) println("a equals b"); 

You can use the IF statement without {} if there is only one line that needs to be executed, therefore, using if(a==b); , you say, if they are equal, they also execute an empty instruction ... Therefore, it will not do anything, and then return to your normal loop outside the IF block.

+1
Jan 01 '13 at 17:26
source share

Several definitions from jls explain this (chapter 14):

Blocks are expressions

As stated here , a Block is a StatementWithoutTrailingSubstatement , which in turn is a StatementNoShortIf , which is a Statement . Thus, when any of them is required, we can insert Block .

If clause

Although this also applies to for and while -loops, I will use if -statements. These rules are almost the same. The syntax for if-statements can be found here .

 IfThenStatement: if ( Expression ) Statement IfThenElseStatement: if ( Expression ) StatementNoShortIf else Statement IfThenElseStatementNoShortIf: if ( Expression ) StatementNoShortIf else StatementNoShortIf 

So, we can use our block here.

But what is the reason?

; defined as EmptyStatement ( reference ), which is also equal to StatementNoShortIf . Thus, in conditional code fragments, such as if-statement and loops, we can replace Block with EmptyStatement if StatementNoShortIf or Statement is required.

Thus, if(Expression)EmptyStatement works.

Why does this not give an error?

Pretty simple: java gives an error if it finds invalid syntax. But if(Expression)EmptyStatement is a perfectly valid syntax. Instead, javac issues a warning if it starts with the appropriate parameters. A complete list of warnings that can be turned off contains the empty warning name for this purpose. Thus, compiling with -Xlint:all or -Xlint:empty generates a warning about this.

Your IDE should also be able to enable this kind of alert. For eclipse see @nullptr answer . In IntelliJ, you can press Ctrl + Shift + A , enter empty body in the search field and enable the warning (marked on the image)

IntelliJ enable warning about empty body

What is it even used for?

Honestly, it is of little use from a minimalist point of view. There is usually a way to succeed without the “do nothing” command. It is rather a matter of personal preference, do you prefer to use

 if( a() && b() ); 

or

 if( a() ) b(); 

and this applies to other cases in which EmptyStatement is used. An important point to consider on this topic is code readability. There are times when the code becomes more readable using no-op. On the other hand, there are cases when the code becomes much more difficult to understand using EmptyStatement - the above example will count on a later IMO.

+1
May 12 '16 at 15:57
source share

The semicolon at the end,
if (a == b); just finish the statement in one line, which means to ignore the result of the condition and continue execution from the next line
This code is useful, on the other hand, sometimes introduces an error in the program, for example,

case 1.

a = 5;
b = 3,
if (a == b);
prinf ("a and b are equal"),
Happening
2.

a = 5;
b is 5;
if (a == b);
prinf ("a and b are equal"),
will print the same result on the screen ...

0
Jan 01 '13 at 23:40
source share

I can think of a scenario where an empty statement is required (not for the if condition, but for the while ).

When a program simply wants to receive explicit confirmation from the user. This may be required when the work after user confirmation is dependent on some other things, and the user wants to take control when to proceed.

  System.out.println("Enter Y to proceed. Waiting..."); System.out.println(""); while(!(new Scanner(System.in).next().equalsIgnoreCase("Y"))); System.out.println("Proceeding..."); // do the work here 
0
Jan 02 '13 at 8:31
source share

Watch this:

 int a,b,c = 0; if(a == b){ c =1; } System.out.print(c);//1 

So you can write like this:

 if (a == b)c=1; 

but if this code is like this:

 int a,b,c=0; if (a != b){ } if (a == b ){ c =1; } 

You can write like this:

 if(a != b); if(a == b )c=1; 

So, you will know if(a != b); note

0
Mar 10 '19 at 2:06
source share

The semicolon in if indicates the end of the if condition, as in java ; treated as the end of the statement and the statement after if is executed.

0
Apr 17 '19 at 20:52
source share

While working on a programming assignment for a class where I work with the N to N doodads grid and comparing the characteristics of random doodads with the ones above, bottom, left and right, I found a good use of this to prevent nested statements and possible boundary exceptions. My goal was to minimize code and not contain if statements in it.

 if (row == 0); else (method (grid[row][col], grid[row-1][col])); if (row == N-1); else (method (grid[row][col], grid[row+1][col])); if (col == 0); else (method (grid[row][col], grid[row][col-1])); if (col == N-1);<br> else (method (grid[row][col], grid[row][col+1])); 

where method(Doodad a, Doodad b) performs some operation between a and b.

Alternatively, you can use exception handling to avoid this syntax, but it works and works well for my application.

-2
Jun 27 2018-02-17T00:
source share



All Articles