Conditional Statements - Java Programming
Java allows code to be executed conditionally using the keywords if and else.
if Statements
An if statement consists of the keyword if followed by parentheses containing a boolean expression. This expression is called the condition. After this, code is included to specify what instructions must occur if the boolean evaluates to true.
else Statements
An else statement is used to specify what instructions must occur if the boolean in the if statement evaluates to false. It is a “catch-all statement.” If nothing is supposed to happen in the case, a semicolon can be used to specify that no instructions should occur. The faster way to do this is to simply not include an else statement at the end.
else if Statements
If using more than two conditions, all middle conditions can be specified with an else if statement, including a boolean expression in parentheses, just like with an if statement.
Blocks
If multiple instructions are to be included for any conditional statement, they must be enclosed in braces opening after the condition. This is called a block.
Declaring Variables
When declaring a variable in a block, the variable can only be used until the end of the block because it is only visible in the block. Declare the variable outside of the block to make it visible anywhere.