1

In a program, I needed an if statement and by mistake, I put semicolon at the end of the statement. However, there were neither compile-time error nor run-time error. I tried to figure out what this code means but hopeless.

if (i == 10); 
{
    System.out.println("It is here");
    break;
} 

If you enlighten me on this topic, that will be appreciated.

imtheman
  • 4,713
  • 1
  • 30
  • 30
Ken Vors
  • 197
  • 1
  • 3
  • 14

1 Answers1

6

The if statement has nothing to do with the following block:

if (i == 10);

This is a valid statement as ; denotes an empty statement: if (i == 10) then do nothing.

{
    System.out.println("It is here");
    break;
}

This is a valid code block. It is syntactically correct although it does not help a lot in this case. This block will be executed in all cases and is not affected by the if statement above.

Community
  • 1
  • 1
Tobias
  • 7,723
  • 1
  • 27
  • 44
  • I do not get the idea of acceptance this statement by the compiler. If "if (i == 10);" does not do anything, how is it allowed ? – Ken Vors Sep 10 '15 at 18:06
  • @KenVors It is syntactically valid. It does not do anything, but `int i;` doesn't do anything either if `i` is never used again. – Tobias Sep 10 '15 at 18:20
  • Thank you for the answer. Ok, you are right int i; does not do anything but there is a possibility of using the i in the future. But, the thing is not same with the if. You cannot use such an if statement in no way in the future. – Ken Vors Sep 10 '15 at 18:24
  • @KenVors The task of a compiler is to compile code, not to make sense of it. Okay, another example: `if(1 == 2) throw new RuntimeException("Oops!");`. This is valid as well and will never be executed as `1` is never equal to `2`. And another example: `for(int i = 5; i > 5; i++) { ... }` will never even run once because `5` is never greater than `5`. Not everything that compiles has to make sense ;) – Tobias Sep 10 '15 at 18:30
  • Ok, I got your point and you are right but may be, I could not express good myself. (English is not my mother language:) In your examples, The code blocks are logical but you write them illogical (from a human view). But, the same situation with if, it is illogical from both computer view and human view. The same compiler warns you when you write " while(true); ". I just wanted to learn what is special with if statement. However, I learned that nothing special with it. Thank you for your answer and it is selected as the answer in any case ;) – Ken Vors Sep 10 '15 at 18:40