Is used for implementing selection algorithms. Executes a certain code section only if a condition is true.
Format:
if (expression) {
'Statements.
}
The
expression to be evaluated is placed within parenthesis. Curly braces are used to open a block, immediately after the expression. If the result of evaluating the expression is true, all statements within the curly braces will execute. If the expression returns false, the statements within the curly braces will be skipped.
An expression is a combination of
literal values or variables, and
operators.
In the example below, the user is asked to enter a number. The
if statement determines if the number is
less than (
less than operator < ) 100 and prints a message to screen, if it is. It then goes on to ask the user to enter their name. The
if statement determines if the name has a
length (String length) of more than 5 characters and prints a message to screen if it does.
Note that the if statement opens a code block with
curly braces.
To recap, if the user enters a number that is less than 100, they will get the message "The number you entered was less than 100" and if the user enters a name that has a length greater than 5, they will get a message saying "The length of your name is longer than 5 characters long".
Here is the output:
Evaluating multiple expressions in an if statement
In this example, if the user enters a number that is greater than 50 AND less than 100, they will get the message "The number you entered was greater than 50 AND less than 100" and if the user enters a name that has a length greater than 5 AND less than 20, they will get a message saying "The length of your name is longer than 5 characters long AND shorter than 20".
also see:
"The if-then and if-then-else Statements (The Java™ Tutorials > Learning the Java Language > Language Basics)" (
http://bit.ly/zflbUx )
Here's a cat...