Wednesday, 25th April 2012
Follow WikiJava on twitter now. @Wikijava

If else statements

From WikiJava

Jump to: navigation, search



This article shows you the syntax of the if else statements, these are the most commonly used and it's important to understand them well

Contents

the article

In an if statement the condition is written between parentheses right after the if keyword and the command to execute is written after the closing parenthesis. In case you want to execute more than one command you can write everythin within curly brackets.

You can use the if to check multiple conditions using the else if (condition) syntax, and you can put at the end a default case by using the else syntax.

if (condition1) {
//commands if condition1 is true
} else if (condition2) {
//commands if condition 1 is false and condition2 is true
} else {
//commands if both condition1 and condition2 are false
}

Which is pretty straight forward to understand, it executed a block after an if statement only in case the condition between the parentheses is true. It does nothing when it's false.

This can be used also in its shorter version:

if (condition1) {
//commands if condition1 is true
} else {
//commands to execute if condition1 is false
}

in which there's only one condition and if that's false then the else commands are executed.

The else clause can be omitted:

if (condition1) {
    //commands if condition1 is true
}

in this case, if the condition1 is true, the code gets executed, otherwise nothing happens.

A related construct is the ?: operator, which is used to choose one of two expressions to evaluate to (unlike the if-else statement, which as a statement does not "return" anything):

condition1? /*expression to return if condition1 is true*/ : /*expression to return if false*/

Here the entire expression evaluates to the subexpression between ? and : if condition1 is true; otherwise it evaluates to the subexpression after :.

This is often useful if you want to perform an assignment, return a value, or call a function on an argument which depends on a condition. Instead of having to write it twice, you can just do the choosing inside the expression. So the following:

foo = condition1 ? expression1 : expression2;

is equivalent to

if (condition1)
    foo = expression1;
else
    foo = expression2;

but the former is much more concise; and without repeating the "foo =" part.

This form makes the code much harder to read so it's better to limit the use of it to very specific situations.

See Also

IfElseDemo.java

Comments from the users

To be notified via mail on the updates of this discussion you can login and click on watch at the top of the page


Comments on wikijava are disabled now, cause excessive spam.