Decision Making Statements
A java program has many statements,
these statements are executed sequentially.
If a program has two or more conditions and user want to
perform a particular condition which satisfy user's need, then Decision Making
concept is used.
JAVA has some following Decision Making Statements:
- IF statements
- switch statements
if statements: if statements are used to check the condition in true or false.
- Simple if statement
- if-else statement
- if-else-if ladder
- Nested if
Simple if: If condition is true then particular statement block will be executed otherwise skipped.
syntax:
if(condition){
//block of
statement;
}
|
public class Eligibility{
public static
void main(String[] args){
int
age = 19;
if(age
> 18){
System.out.println("Person
is eligible");
}
}
}
|
if-else: In this statement if condition is followed by an else condition. If condition is true if block will be executed otherwise false block executed.
syntax:
if(condition){
//true statement
block;
}
else{
//false
statement block;
}
|
public class Number{
public static
void main(String[] args){
int
num = 22;
if(num
% 2 == 0){ System.out.println("Number
is even");
}
else{
System.out.println("Number
is odd");
}
}
}
|
if-else-if ladder: It is used when there is multiple choices. if-else-if ladder has one if then else if statement and so on.
syntax:
if(condition 1){
//condition 1
statement block;
}
else if(condition 2){
//condition 2
statement block;
}
else if(condition 3){
//condition 3
statement block;
}
else{
//when all conditions
are false
}
|
class Result{
public static void main(String[] args){
int marks = 67;
if(marks >= 65){
System.out.println("Grade A");
}
else if(marks >= 50){
System.out.println("Grade B");
}
else(marks > 35){
System.out.println("Grade C");
}
}
}
|
nested if: In nested if statements there can be one or more if statements within if statement.
syntax:
if(condition1){
if(condition 2){
//both
conditions are true;
}
else{
//condition1
is true;
}
}
else{
//No condition
satisfy;
}
|
Program:
class Person{
public static void main(String[] args){
int age = 20;
char sex = 'f';
if(sex == 'm'){
if(age >= 21){
System.out.println("Person is eligible");
}
else{
System.out.println("Person is not eligible");
}
}
else{
if(sex == 'f'){
if(age >= 18){
System.out.println("Person is eligible");
}
else{
System.out.println("Person is not eligible");
}
}
}
}
}
|
Switch Statements: Switch Statement is used to perform equality operation. When there is multiple choices for if then using equality operation switch is used.
syntax:
switch(expression){
case 1:
//statements
break;
case 2:
//statements
break;
.
.
.
default:
//statements
}
|
Program:
class Number;
{
public static
void main(String[] args){
int
value = 3;
switch(value){
case
1:
System.out.println("Value
is 1");
break;
case 2:
System.out.println("Value is 2");
break;
case 3:
System.out.println("Value is 3");
break;
defalut:
System.out.println("Wrong
choice");
}
}
}
|
Comments
Post a Comment