Java if else Statement
In this chapter you will learn:
Description
The if
statement is a conditional branch statement.
We can add else statement to the if statement.
Syntax
Here is the general form of the if-else
statement:
if (condition)
statement1;
else
statement2;
The else
clause is optional. Each statement may be a single statement or a compound
statement enclosed in curly braces (a block). Only one statement can appear directly after the if
or the else
.
To include more statements, you'll need to create a block, as in this fragment.
Example
public class Main {
public static void main(String[] argv) {
int i = 1;//from w w w . j a va 2 s. c o m
if (i > 0) {
System.out.println("Here");
i -= 1;
} else
System.out.println("There");
}
}
]]>
The output:
It is good to include the curly braces when using the if
statement,
even when there is only one statement in each clause.
Next chapter...
What you will learn in the next chapter:
- What is Java if else ladder statement
- Syntax for Java if else ladder statement
- Example - Java if else ladder statement