0% found this document useful (0 votes)
25 views

Computer Application IX If Switch

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

Computer Application IX If Switch

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Conditional constructs in Java

All programming languages provide program constructs, which are used to control the
order (flow) in which statements are executed. There are three types of programming
constructs-
 Sequential construct: In sequential construct each statement is executed once in the
order in which they are written. All simple programs of previous chapters are the
examples of sequential construct.
 Conditional construct: It checks a condition and executes certain instructions,
depending on the condition whether it is true or false. There are two conditional
statements in Java- if and switch. In this chapter we shall learn about these topics.
 Iterative construct: It enables the execution of a set of statements to repeat,
depending upon a test condition. It is also known as looping. There are three
iterative statements in Java- for, while and do – while. In the next chapter we
shall learn about these topics.
(All above three programming constructs can be used together in a program.)

Conditional statements are also known as Decision making / Branching / Selection


statements. The if and switch are two conditional statements in Java.
We can do simple conditional work using conditional operator(? :) also. We learnt
about conditional (Ternary) operator in previous chapter (Operators).

The if statement is referred to as bi-directional branching. It can be used in many ways


in a program-
I. if statement executes a set of statements when the condition evaluates to true,
otherwise it ignores. Syntax-
False
If (condition )
{ True
Statements

}

Example: if (age >= 60)


System.out.print(“ Senior ”);
System.out.println(“ Citizen”);

Note: In case of single statement in the body of if, we may skip the curly braces.
II. if else statement is used when either of the two different actions are to be performed
depending upon the given condition. Syntax-
Computer Applications Notes Volume I (Class IX) for ICSE examinations 2022 by Hem Sir Page 23
False
If (condition )
{ True
Statements

}
else
{
Statements

}

Example: if ( num % 2 == 0)
{ System.out.println(“Even number”);
}
else
{ System.out.println(“Odd number”);
}
III. if else if ladder is used to check a series of conditions, where every condition has a
block of statements within itself. The conditions are evaluated from top to bottom and
execute only a block of statements whose condition evaluates to true. Syntax-

If (condition1 ) False
{ True
Statements

}
False
else if ( condition2 )
{
True
Statements

}

else
{
Statements
}

Computer Applications Notes Volume I (Class IX) for ICSE examinations 2022 by Hem Sir Page 24
Example: if ( sp > cp )
{
System.out.println(“Profit: ” + (sp-cp));
}
else if ( sp < cp)
{
System.out.println(“Loss: ” + (cp-sp));
}
else
{
System.out.println(“Equal : 0” );
}
IV. Nested if means a complete if statement inside another if statement (either in if
part or in else part). Syntax-

Example: if( a > b )


{ if ( a > c )
System.out.println( a +“ is the largest”);
else
System.out.println( c +“ is the largest”);
}
else
{ if( b > c )
System.out.println( b +“ is the largest”);
else
System.out.println( c +“ is the largest”);
}

Computer Applications Notes Volume I (Class IX) for ICSE examinations 2022 by Hem Sir Page 25
In case of nested if, it is advised that use proper curly braces. Without curly braces in
nested if, programmer may face an ambiguity that else belongs to which if ? This
situation is known as dangling else.
There is no such ambiguity with the compiler because it has following rules-
 Each else belongs to the nearest (closest) unmatched if.
 When compiler does not find if statement for any else statement, it flags an error-
“else without if”.

Example 1: if( (ch >= ‘A’ && ch <= ‘Z’ ) || (ch >= ‘a’ && ch <= ‘z’))
if(ch >= ‘A’ && ch <= ‘Z’)
System.out.println( “Capital Letter”);
else
System.out.println( “ Other than alphabet”);

(Above example is not fully correct due to dangling else problem, here else belongs to 2nd
if but it should belong to 1st if. To correct this problem we use curly braces as example 2.)

Example 2: if( (ch >= ‘A’ && ch <= ‘Z’ ) || (ch >= ‘a’ && ch <= ‘z’))
{ if(ch >= ‘A’ && ch <= ‘Z’)
System.out.println( “Capital Letter”);
}
else
System.out.println( “ Other than alphabet”);

switch statement: It is used to check multiple conditions, especially when we have to do


different task depending on different values of a variable or expression. These values must
be integer or character.
Syntax :
switch(variable / expression)
{
case value1:
statements; break;
case value2:
statements; break;
.
.
.
default:
statements; break;
}
Computer Applications Notes Volume I (Class IX) for ICSE examinations 2022 by Hem Sir Page 26
In above syntax following keywords are used-
switch: It is used to specify variable /expression whose value is to be check.
case: It is used to specify different values for given variable / expression. Each case has its
own set of statements.
default: It is the last case of switch statement. It executes only when the value stored in
switch variable / expression does not match with any case. It is optional.
break: It brings the program control out of the switch statement. It should be written
with every case. If we do not write the break statement, all the statements of other cases
after the matching case will also get executed. The unusual execution of more than one
case is known as fall through. Sometime fall through might be useful.

Example 1:
/**
Menu driven program using switch case to display-
1. Ceiling value
2. Floor value
3. Rounded value
*/
import java.util.Scanner;
public class Menu
{
public static void main (String args[])
{
Scanner sc = new Scanner(System.in);
System.out.println("ENTER YOUR REAL NUMBER");
double n = sc.nextDouble();

System.out.println("### Menu for selection ###");


System.out.println("1. Ceiling value");
System.out.println("2. Floor value");
System.out.println("3. Rounded value");

System.out.println("ENTER YOUR SELECTION NUMBER (1,2,3)");


int choice = sc.nextInt();
double r=0;
switch(choice)
{ case 1:
r = Math.ceil(n);
System.out.println("Ceiling Value =" + r);
break;

Computer Applications Notes Volume I (Class IX) for ICSE examinations 2022 by Hem Sir Page 27
case 2:
r = Math.floor(n);
System.out.println("Floor Value =" + r);
break;
case 3:
r = Math.round(n);
System.out.println("Rounded Value =" + r);
break;
default:
System.out.println("!!! Invalid Choice !!!");
break;
}
}
}

Output :
ENTER YOUR REAL NUMBER
35.67
### Menu for selection ###
1. Ceiling value
2. Floor value
3. Rounded value
ENTER YOUR SELECTION NUMBER (1,2,3)
1
Ceiling Value =36.0

Example 2:

/**
Program to check vowel using switch case
fall through is also implemented in this program
*/
import java.util.Scanner;
public class Vowel
{
public static void main (String args[])
{
Scanner sc = new Scanner(System.in);
System.out.println("ENTER YOUR CHARACTER");
char c = sc.next().charAt(0);

Computer Applications Notes Volume I (Class IX) for ICSE examinations 2022 by Hem Sir Page 28
switch(c)
{
case 'a':
case 'A':
case 'e':
case 'E':
case 'i':
case 'I':
case 'o':
case 'O':
case 'u':
case 'U':
System.out.println(c + " is a vowel");
break;
default:
System.out.println(c + " is not a vowel");
}
}
}

Output:
ENTER YOUR CHARACTER
B
B is not a vowel

System.exit(0); The exit() method of System class is used to terminate the currently
running program. Here 0 is a status code that indicates normal termination, and a
non-zero status code indicates abnormal termination.
Difference between if-else statement and Conditional (Ternary) operator :
if-else statement Conditional (Ternary) operator
Multiple expressions are allowed. Only single expression is allowed.
A nested form is easy. A nested form is difficult to understand.
Logic is very clear. Logic is less clear but code is neat and compact
Difference between if-else statement and switch statement:
if-else statement switch statement
Evaluates all relational and logical Only checks for equality.
expression.
Multiple variables or expressions can be Only single variable or expression is used.
used.
All data types are used in condition. Case value cannot be float and double type.
Computer Applications Notes Volume I (Class IX) for ICSE examinations 2022 by Hem Sir Page 29

You might also like