The if Statement in java

The Java if statement works much like the IF statement in any other language. Further, it is syntactically identical to the if statements in C, C++, and C#.

Syantax

if(condition) statement;

Here, condition is a Boolean expression. If condition is true, then the statement is executed. If condition is false, then the statement is bypassed. Here is an example

if(num < 100) System.out.println(“num is less than 100”);

In this case, 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 bypassed.

Example

IfSample.java

class IfSample {
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");
// this won't display anything
if(x == y) System.out.println("you won't see this");
}
}

Output:

x is less than y
x now equal to y
x now greater than y

Leave a Comment