When a program breaks the sequential flow and jumps to another part of the code.it is called branching.When the branching is based on a particular condition,is lnown as conditional branching.

Java language processes such decission making capabilities and supports the following statements known as control or decission making statements.

  1. if statements
  2. switch statements

if - Statement:

Syntax:

The syntax of an if statement is:
if(test expression)
{
statement-block;
}
statement-x;

If the Boolean expression evaluates to true, then the block of code inside the if statement will be executed. If not, the first set of code after the end of the if statement(after the closing curly brace) will be executed.

Example:

class ifTest
{
public static void main(String args[])
{
int i,count1,count2;
float[] weight={45.0f};
float[] height{176.0f};
count1 =0;
count2 =0;
for (i =0; i<=4;i++)
{
if(weight[i]<50.0&& height[i]>170.0)
{
count1 = count1 +1;
}
count = count +1;
}
count2 = count - count1;
System.out.print("number of persons with");
System.out.print("weight<50 and height>170 =" +count1);
System.out.print("others =" +count2);
}
}

if...else Statement:

if else is an extension of the simple if statement.The general form is

Syntax:

The syntax of an if...else is:
if(test-expression)
{
true-block statement(s)
}
else
{
false-block statement
}
statement-x

If the test expression id true,then the true-block statement(s) immediatly following the if statement, are executed true-block or fast-block will be executed,either true-block or false-block will be executed,not both.

Example:

class if- else
{
public static void main(String args[])Throws IOException
{
int  number[]={50,65};
int even =0; odd =0;
{
if ((number[i] %2)==0)
{
even +=1;
}
else +=1;
}
}
System.out.print("even numbers:"+even+" odd numbers :"+odd);
}
}

Switch Statement:

A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each case.

Syntax:

switch(expression)
{
case value-1:
   block-1
   break;
case value-2 :
     block-2
     break;
default:
     default-block  
	 break;
}
statement-x;

The default is an optional case.When present,it will be executed if the value of the expression does not match with any of the case values. If not present, no action takes palce when all,matches fail and the control goes to the statement-x;

Example:

class Switch
{
public static void main(String args[]) throws  IOException
{
Int a, b, c;
System.out.println ("Enter a, b values”);
try
{
Switch(c)
{
case'A':
System.out.println ("A+B=" + a+b");
break;
case'B':
case'C':
System.out.println ("A-B=" + a-b");
break;
case'D':
System.out.println("AxB=" + axb");
break;
default:
System.out.println("Thanking you");
}
}
catch(exception e)
{
System.out.println("I/O error");
}
}
}

News Walls


Copyrights © 2016. All Rights Reserved to Learn Computers Home, India. //Site Designed.