Java if Statement
In this chapter you will learn:
- What is Java If Statement
- Syntax for Java If Statement
- Example - for Java If Statement
- Example - If statement and comparison operators
- Example - If statement and single boolean variable
Description
Java if statement is used to execute a block of code based on a condition.
Syntax
The following the simplest form of Java if statement:
if(condition)
statement;
condition
is a boolean expression. If condition
is true
,
then the statement
is executed. If condition
is false
, then
the statement
is bypassed.
Example
The following code outputs a message based on the value of an integer. It uses the if statement to do the check.
public class Main {
//from w w w .j a va 2 s . co m
public static void main(String args[]) {
int num = 99;
if (num < 100) {
System.out.println("num is less than 100");
}
}
}
The output generated by this program is shown here:
Example 2
If statement is often used to to compare two variables. The following code defines two variables,
x
and y
, the it uses the if statement to compare them and prints out messages.
public class Main {
//ww w . j ava 2s. c om
public static void main(String args[]) {
int x, y;
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");
}
if (x == y){
System.out.println("===");
}
}
}
The output generated by this program is shown here:
Example 3
We can also use a boolean value to control the if statement. The value of a boolean
variable
is sufficient, by itself, to control the if statement.
public class Main {
public static void main(String args[]) {
boolean b;//from ww w . j a v a2 s . c o m
b = false;
if (b) {
System.out.println("This is executed.");
} else {
System.out.println("This is NOT executed.");
}
}
}
There is no need to write an if
statement like this:
if(b == true) ...
The output generated by this program is shown here:
Next chapter...
What you will learn in the next chapter: