Selection Statements in JAVA

As we discussed JAVA has mainly two types of selection statements: 

if and switch. 

Both the statements can be used to control the flow of your program’s execution, whatever is the condition at runtime.let’s have closer look 😀

Let’s have closer look 😀

if Statement

if statement is JAVA’s conditional branch statement used to route the program execution in two different paths,

Syntax:

if(condition) Statement1;
else Statement2;

Here, the condition is any statement that returns boolean value i.e. true or false.
and statements can be a single line or multiple lines, enclosed in { statements }.

Example:if-statement

int a=10, b=15;
//.. other code
if(  a > b )   // here a > b will return false
{
System.out.println(” a is Bigger number “);
}
else
{
System.out.println(” b is Bigger number “);
}

Output:       b is Bigger number

switch Statement

switch statement is used for multiway branching. If you have more than two paths and the condition have to decide the path to follow then, you should go with switch statement

Syntax:

switch( expression )
{
case value1:
// statement sequence
break;

case value2:
// statement sequence
break;
.
.
case valueN:
// statement sequence
break;

case default:
// default statement sequence
}

Here, the expression must be of type byte, short, int or char. each value specified in the case must be compatible with the expression. Each case must be a unique literal/constant. Duplicate cases are not allowed.

Also, the value of the expression will be matched with all the values of cases. Thus, any one of the cases will match according to that statement sequence to execute and then break statement will be executed. With break statement, the control will come out the of switch.

Suppose, if the expression value does not match with any case literal/constant then the default case will be executed at the end.

Example: switch-case

 

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 )

Google+ photo

You are commenting using your Google+ 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 )

w

Connecting to %s

Powered by WordPress.com.

Up ↑

%d bloggers like this: