Conditional Statement in Java|set 1

Conditional statements are used to perform different actions based on different conditions.

 If Statement:

The if statement is one of the most frequently used conditional statements.If the if statement’s condition expression evaluates to true, the block of code inside the if statement is executed. If the expression is found to be false, the first set of code after the end of the if statement (after the closing curly brace) is executed.
Syntax:

if (condition) {
//Executes when the condition is true
}

Any of the following comparison operators may be used to form the condition:
< less than
> greater than
!= not equal to
== equal to
<= less than or equal to
>= greater than or equal to

For example:

int x = 10;
if(x > 5) {
 System.out.println("Hi Rashmi");
}

Remember  two equal signs (==) to test for equality.

if…else Statements:

An if statement can be followed by an optional else statement, which executes when the condition evaluates to false.
For example:
int age = 25;

if (age < 16) {
 System.out.println("Too Young");
} else { 
 System.out.println("You are Young!");
}
//Outputs You are Young!

As age equals 25, the condition in the if statement evaluates to false and the else statement is executed.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s