One-line if statement

This question already has an answer here:

  • Is it ok if I omit curly braces in Java?

    15 answers
  • Java one line if statement [duplicate]

    8 answers

as someone who has learned programming by himself and some wiki articles on different api’s etc. I have a question!

I’ve seen people do if-statements like this:

if(bool)
    return false;

Is this some sort of easier/faster way of doing this?

if(bool) {
    return false;
}

Does that mean it only executes until the semi-colon (Only one line)?

The primary reason for using curly braces in a case like this is to avoid problems when you come back and add additional logic to the if statement. If you add another line of code but forget to put in the curly braces, it will not behave the way you expect. I avoid this problem by always using curly braces for a one-line if statement even though it is optional as far as the compiler is concerned.

Yes, it is. For example,

if(bool)
    bool=false;
    someothervar=true;

will not execute like

if(bool){
    bool=false;
    someothervar=true;
}

because if no semicolon is read by the Java compiler, then it will only execute the next statement. In this case, in the first example, someothervar will always be set to true, while in the second one, someothervar will only be set to true if the condition is true.

Yes it is okay to do this. The functionality of the two statements will be identical. It really only will come down to personal preference on how your code will look. Just keep in mind that you should stick to whatever convention you choose use in your code for consistency. Keep in mind that

if(bool) return false;

will also do the same thing as and (in my opinion) is also less susceptible to errors in later editing of said code. If you do choose to format your code this way note that something of the form

if(value)
   for(int i;i<x;i++)
     x=i;

will be syntactically valid, but should not be used as it will only serve to confuse (in my opinion).