Java Code Snippets: Performing a Single line or Inline if else statement

For some reason I have the utmost trouble remembering how to do a single line or inline if else statement. This article is mainly for myself so hopefully I will remember the next time I want to do an inline if else statement.

The usual format for performing an if else statement is:

if( $val1 > $val2 ) {
    // code executed if true
} else {
    // code executed if false

If you are trying to set a variable to a value depending on a condition then it is often the case that an inline if else statement will be sufficient and easier to read. This is done by the use of ?. The full format is (condition) ? (true output) : (false output) or as an example:

$val = ($var1 > $var2) ? $var1 : $var2;

Comments & Questions

Add Your Comment