Java if statement is a conditional branch statement.
Here is the general form of the if statement:
if (condition) statement1; else statement2;
Here, condition
is a Boolean expression.
The condition
is any expression that returns a boolean value.
The else clause is optional.
If condition
is true
, then the statement1
is executed.
If condition
is false
, then the statement2
is executed.
Here is an example:
if(num < 100) System.out.println("num is less than 100");
In the code above, if num
contains a value that is less than 100, the conditional expression is true, and println()
will execute.
If num contains a value greater than or equal to 100, then the println()
method is by passed.
Java defines a full complement of relational operators which may be used in a conditional expression.
Here are a few:
Operator | Meaning |
---|---|
< | Less than |
> | Greater than |
== | Equal to |
Notice that the test for equality is the double equal sign.
Here is a program that illustrates the if statement:
//Demonstrate the if. public class Main { public static void main(String args[]) { int x, y;//from www. ja v a 2 s . c om x = 10; y = 20; if(x < y) System.out.println("x is less than y"); x = x * 2; if(x == y) System.out.println("x now equal to y"); x = x * 2; if(x > y) System.out.println("x now greater than y"); // this won't display anything if(x == y) System.out.println("you won't see this"); } }
The line
int x, y;
declares two variables, x and y, by use of a comma-separated list.
You can create a sequence of nested ifs is the if-else-if ladder.
It looks like this:
if(condition) /*from www . j a v a2 s .com*/ statement; else if(condition) statement; else if(condition) statement; . . . else statement;
The if statements are executed from the top.
If one of the conditions is true, the statement associated with that if is executed.
If none of the conditions is true, then the final else statement will be executed.
Here is a program that uses an if-else-if ladder to determine which season a particular month is in.
// Demonstrate if-else-if statements. public class Main { public static void main(String args[]) { int month = 3; // April String season;//from w w w . j a v a2 s .c o m if(month == 12 || month == 1 || month == 2) season = "Winter"; else if(month == 3 || month == 4 || month == 5) season = "Spring"; else if(month == 6 || month == 7 || month == 8) season = "Summer"; else if(month == 9 || month == 10 || month == 11) season = "Autumn"; else season = "Bogus Month"; System.out.println("April is in the " + season + "."); } }