0

I have encountered the following strange behavior in Java using jdk 13.0:

String foo = "Something";
String bar = "Other";

if (foo.equals(bar));
{
   System.out.println("Face palm");
}

Sadly, the above comparison succeeds and the "Face palm" is printed out. What causes this behavior is the existence of the semi-colon in the end of the if statement.

The correct way of doing this is:

String foo = "Something";
String bar = "Other";

if (foo.equals(bar))
{
   System.out.println("Face palm");
}

Could anyone explain why Java behaves like this ?

Could that be just an uncaught syntax error by the compiler ?

thanos.a
  • 2,246
  • 3
  • 33
  • 29
  • 3
    `if (foo.equals(bar));` is equivalent to `if (foo.equals(bar)) {}` – Eran Nov 03 '19 at 09:44
  • 1
    some IDEs have an option to signal an empty statement (as warning or even as error) – user85421 Nov 03 '19 at 09:53
  • It is not really a syntax *error* per se. `if` (and `while` and `for`) require a *statement* to follow them. It just so happens that `;` by itself is a valid statement. There are uses of if/for/while with an empty statement (if the expressions have side effects), but they are somewhat confusing. – Andy Turner Nov 03 '19 at 10:15

1 Answers1

4

It does not mean that comparison succeeds - basically you just created if statement with empty body and then opened the local anonymous code block (starting from {)

The Face palm value in this case will be printed out always - no matter what the condition result will be

Read more here:

m.antkowicz
  • 13,268
  • 18
  • 37