if-else

General

These statements basically create conditions; your code will only run if these conditions are met.

For example, we'll make a simple code snippet that prints out the highest of two numbers:

if (int a > b){
  System.out.print(a);           
}
else{
  System.out.print(b);
}

The parenthesis after the if contain the condition that needs to be met for the statement to run. If this condition is met the if statement(s) will be executed. If however, the condition is not met, the else statement will run.
Note: The else is not necessarily needed. You may have an if that stands alone.

Style

When writing an if statement, curly braces are not a necessity, however they are needed if you would like to preform more than one action in either the if or the else. It is therefore good form to always include curly braces so as not to create an error when adding more statements to your if at a later time.

Visual If - Else

ifelse.bmp

The Safra Error

There once was a boy who went by the name of Elliot Safra, he was writing a program one evening, when he made one small error, an error so small, but so imporant that it became known as "The Safra Error". If you mistakenly use a single = instead of == the condition will not do what you intended and the compiler will not catch the error. For example:

if ( a = b ){
  System.out.println("a equal b");
}

This code will not work as intended. What is actually happening is that the condition of the if is an assignment. So a is assigned the value that was in b and the expression evaluates to the value of a. Basically, if b was true then the condition is true and if b was false the condition is false.

This error can only occur when dealing with boolean values. If a and b were ints the compiler would catch the error because the condition would evaluate to an int which is not legal.

So remember, next time you want to say "If something is equal to something else", just remember "If I'm equal to you, it's gotta' be two".

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License