Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if(boolean) always executed

Tags:

java

Here's my code simplified

private static boolean isTrue()
{
    return false;
}


public void Update()
{
    if (isTrue())
        doSomething();
}

For some odd reason doSomething() gets always executed, no matter what isTrue() returns. Why?

Edit: I had a semicolon somewhere off screen directly after closing the if statement like this:

if (false);
    doSomething();

Like this doSomething() gets executed always.

like image 801
TheDespite Avatar asked Jun 16 '26 14:06

TheDespite


1 Answers

For some odd reason DoSomething() gets always executed, no matter what IsTrue returns. Why?

This can be only if one or more of the following occurs:

  • There are other threads calling doSomething().
  • You have ; after if. ✓
  • You're calling it from somewhere else.
  • This is not the code.
  • The day has arrived, computers control the world.

Important note, more than the question: Please follow the Java Naming Conventions.


After your edit, I'll explain why it's always executed.

It's simply because

if(something);
{
   System.out.println("I'll be always printed!");
}

Is equivalent to

if(something) { }
{
   System.out.println("I'll be always printed!");
}

It's a good practice to always have { and }, even if the body of the if includes only one statement, it's clearer and will help you to avoid possible bugs in the future, like @GrijeshChauhan mentioned, if you want to add lines in the future.

like image 187
Maroun Avatar answered Jun 19 '26 03:06

Maroun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!