0% found this document useful (0 votes)
10 views23 pages

Control Structurenotes

The document explains decision-making statements in Java, including if statements, if-else, if-else if-else, nested if-else, and switch statements. It also covers looping mechanisms such as while loops, do-while loops, for loops, and nested loops, along with examples for each. Additionally, it introduces the conditional (ternary) operator and the break keyword for controlling loop execution.

Uploaded by

vpn12981298
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views23 pages

Control Structurenotes

The document explains decision-making statements in Java, including if statements, if-else, if-else if-else, nested if-else, and switch statements. It also covers looping mechanisms such as while loops, do-while loops, for loops, and nested loops, along with examples for each. Additionally, it introduces the conditional (ternary) operator and the break keyword for controlling loop execution.

Uploaded by

vpn12981298
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Java Decision Making

There are two types of decision making statements in


Java. They are:

 if statements
 switch statements
(1) The if Statement
An if statement consists of a Boolean expression followed
by one or more statements.
Syntax:
The syntax of an if statement is:
if(Boolean_expression)
{
//Statements will execute if the Boolean expression is true
}

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:

public class Jdemo


{
public static void main(String st[])
{
int n1 = 10;
int n2 = 20;
if( n1 < n2 )
{
[Link]("N1 is less than N2");
}
}
}
This would produce following result:
N1 is less than N2

===============================================

(2) The if...else Statement:


An if statement can be followed by an optional else statement,
which executes when the Boolean expression is false.
Syntax:
if(Boolean_expression)
{
//Executes when the Boolean expression is true
}
else
{
//Executes when the Boolean expression is false
}

Example:
import [Link].*;
public class JDemo
{
public static void main(String st[])
{
Scanner sr=new Scanner([Link]);
int n1,n2;
[Link]("Enter First Number");
n1=[Link]();
[Link]("Enter Second Number");
n2=[Link]();
if(n1>n2)
{
[Link]("N1 Is Greater Than N2");
}
else
{
[Link]("N1 Is Not Greater Than N2");
}
}

This would produce following result:


Enter First Number
5
Enter First Number
66
N1 Is Not Greater Than N2

(3) The if...else if...else Statement:


An if statement can be followed by an optional else if...else statement,
which is very useful to test various conditions using single if...else if
statement.
When using if , else if , else statements there are few points to keep in mind.

 An if can have zero or one else's and it must come after any else if's.
 An if can have zero to many else if's and they must come before the else.

 Once an else if succeeds, none of he remaining else if's or else's will be


tested.

Syntax:

if(Boolean_expression 1)
{
//Executes when the Boolean expression 1 is true
}
else if(Boolean_expression 2)
{
//Executes when the Boolean expression 2 is true
}
else if(Boolean_expression 3)
{
//Executes when the Boolean expression 3 is true
}
else
{
//Executes when the none of the above condition is true.
}
Example:

import [Link].*;
public class Demo5
{
public static void main(String st[])
{
Scanner sr=new Scanner([Link]);
int n1,n2,n3,max;
[Link]("Enter First Number");
n1=[Link]();
[Link]("Enter Second Number");
n2=[Link]();
[Link]("Enter Third Number");
n3=[Link]();

if(n1>n2&&n1>n2)
{
max=n1;
}
else if(n2>n1&&n2>n3)
{
max=n2;
}
else
{
max=n3;
}
[Link]("Largest number is "+max);
}
}

This would produce following result:


Enter First Number
56
Enter Second Number
67
Enter Third Number
34
Largest number is 67
(4) Nested if...else Statement:
It is always legal to nest if-else statements, which means you can use
one if or else if statement inside another if or else if statement.

Syntax:
if(Boolean_expression 1)
{
//Executes when the Boolean expression 1 is true
if(Boolean_expression 2)
{
//Executes when the Boolean expression 2 is true
}
}

Example:
import [Link];
public class NestedDemo
{
public static void main(String st[])
{
int age;
Scanner sr=new Scanner([Link]);
[Link]("Enter Age ");
age=[Link]();
if(age>=18)
{
if(age<=120)
{
[Link]("Eligible For Voting");
}
else
{
[Link]("Not Eligible For Voting");
}
}
else
{
[Link]("Not Eligible For Voting");
}
}
}
Output Will Be
Enter Age
18
Eligible For Voting

Conditional Operator/Ternary Operator ? :


Conditional operator is also known as the ternary operator. This operator consists of three
operands and is used to evaluate boolean expressions. The goal of the operator is to decide which
value should be assigned to the variable. The operator is written as :

variable x = (expression) ? value if true : value if false

Example1:
import [Link];
public class TernaryExample1
{
public static void main(String st[])
{
int a,b,max;
Scanner sr=new Scanner([Link]);
[Link]("Enter Value Into A ");
a=[Link]();
[Link]("Enter Value Into B ");
b=[Link]();
max=(a>b)?a:b;
[Link]("Largest Value= "+max);
}
}

Output Will Be

Enter Value Into A


45
Enter Value Into B
7
Largest Value= 45
Example2:
import [Link];
public class TernaryExample2
{
public static void main(String st[])
{
int a,b,c,max;
Scanner sr=new Scanner([Link]);
[Link]("Enter Value Into A ");
a=[Link]();
[Link]("Enter Value Into B ");
b=[Link]();
[Link]("Enter Value Into C ");
c=[Link]();
max=(a>b&&a>c)? a :(b>c)?b:c;
[Link]("Largest Value= "+max);
}
}

Output Will Be
Enter Value Into A
22
Enter Value Into B
3
Enter Value Into C
44
Largest Value= 44

(4) The 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 :
//Statements
break; //optional
case value :
//Statements
break; //optional
//You can have any number of case statements.
default : //Optional
//Statements
}

The following rules apply to a switch statement:

 The variable used in a switch statement can only be a byte, short, int, or char.
 You can have any number of case statements within a switch. Each case is followed by
the value to be compared to and a colon.

 The value for a case must be the same data type as the variable in the switch, and it must
be a constant or a literal.

 When the variable being switched on is equal to a case, the statements following that case
will execute until a break statement is reached.

 When a break statement is reached, the switch terminates, and the flow of control jumps
to the next line following the switch statement.

 Not every case needs to contain a break. If no break appears, the flow of control will fall
through to subsequent cases until a break is reached.

 A switch statement can have an optional default case, which must appear at the end of the
switch. The default case can be used for performing a task when none of the cases is true.
No break is needed in the default case.

 The variable used in a switch statement can only be a


byte, short, int, , char and a string.

Example1

import [Link];
public class SwitchDemo1
{
public static void main(String st[])
{
Scanner sr=new Scanner([Link]);
int ch,bill=0,qty=0;
[Link]("Fast Food Menu");
[Link]("1-Chowmin Per Plate 65 Rupees");
[Link]("2-Dosa Per Plate 70 Rupees");
[Link]("3-Burger Per Plate 50 Rupees");
[Link]("Enter Choice ");
ch=[Link]();
[Link]("Enter Number Of Plate ");
qty=[Link]();
switch(ch)
{
case 1 :
bill=qty*65;
break;
case 2:
bill=qty*70;
break;
case 3:
bill=qty*50;
break;
default :
[Link]("Invalid Choice");
}
[Link]("Your Bill is " + bill);

}
}

Output Will Be

Fast Food Menu


1-Chowmin Per Plate 65 Rupees
2-Dosa Per Plate 70 Rupees
3-Burger Per Plate 50 Rupees
Enter Choice
2
Enter Number Of Plate
4
Your Bill is 280

Example2
import [Link];
public class SwitchDemo2
{
public static void main(String st[])
{
Scanner sr=new Scanner([Link]);
char ch;
[Link]("Enter any Alphabet ");
ch=[Link]().charAt(0);
switch(ch)
{
case 'a':
case 'A':
case 'e':
case 'E':
case 'i':
case 'I':
case 'o':
case 'O':
case 'u':
case 'U':
[Link]("Input Alphabet is a Vowel");
break;
default:
[Link]("Input Alphabet is Not a Vowel");
}
}
}

Output Will Be
Enter any Alphabet
A

Input Alphabet is a Vowel

Example3
import [Link].*;
public class SwitchDemo3
{
public static void main(String st[])
{
Scanner sr=new Scanner([Link]);
String str;
char ch;
int c=0;
[Link]("Enter any String ");
str=[Link]();
String str2=[Link]();
for(int i=0;i<[Link]();i++)
{
ch=[Link](i);
switch(ch)
{

case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
c++;
}
}
[Link]("Number of Vowels in given String is "+c);
}
}

Output Will Be
Enter any String
HelloEveryBody
Number of Vowels in given String is 5

Example4
import [Link].*;
public class Myprog {
public static void main(String[] args)
{
Scanner sr=new Scanner([Link]);
String str;
[Link]("COUNTRY LIST ");
[Link]("INDIA");
[Link]("CHINA");
[Link]("NEPAL");
[Link]("BHUTAN");
[Link]("Enter COUNTRY NAME FROM THE LIST ");
str=[Link]();
str=[Link]();
switch(str)
{

case "INDIA":
[Link]("CAPITAL OF INDIA IS NEW DELH ");
break;
case "CHINA":
[Link]("CAPITAL OF CHINA IS BEIJING ");
break;
case "NEPAL":
[Link]("CAPITAL OF NEPAL IS KATHMANDU ");
break;
case "BHUTAN":
[Link]("CAPITAL OF BHUTAN IS THIMPHU ");
break;
default:
[Link]("WRONG CHOICE ");

Output Will Be
COUNTRY LIST
INDIA
CHINA
NEPAL
BHUTAN
Enter COUNTRY NAME FROM THE LIST
Bhutan
CAPITAL OF BHUTAN IS THIMPHU

Java Loops
There may be a situation when we need to execute a block of code several number of times, and
is often referred to as a loop.

Java has very flexible three looping mechanisms. You can use one of the following three loops:

 while Loop
 do...while Loop
 for Loop
 enhanced for loop

The while Loop:


A while loop is a control structure that allows you to repeat a task a certain number of times.
Syntax:

The syntax of a while loop is:


while(Boolean_expression)
{
//Statements
}

When executing, if the boolean_expression result is true then the actions inside the loop will be
executed. This will continue as long as the expression result is true.

Here key point of the while loop is that the loop might not ever run. When the expression is
tested and the result is false, the loop body will be skipped and the first statement after the while
loop will be executed.

Example:
import [Link];
public class DigitSum {
public static void main(String[] args)
{
Scanner sr=new Scanner([Link]);
int num,sum=0,rem;
[Link]("Enter number ");
num=[Link]();
while(num>0)
{
rem=num%10;
sum=sum+rem;
num=num/10;
}
[Link]("Sum of Digit is = "+sum);

Output Will Be

Enter number
7689
Sum of Digit is = 30
The do...while Loop:
A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute
at least one time.

Syntax:

The syntax of a do...while loop is:


do
{
//Statements
}while(Boolean_expression);

Notice that the Boolean expression appears at the end of the loop, so the statements in the loop
execute once before the Boolean is tested.

If the Boolean expression is true, the flow of control jumps back up to do, and the statements in
the loop execute again. This process repeats until the Boolean expression is false.

Example:
import [Link];
public class ReverseDigit
{
public static void main(String[] args)
{
Scanner sr=new Scanner([Link]);
int num,rev=0,rem;
[Link]("Enter number ");
num=[Link]();
do
{
rem=num%10;
rev=(rev*10)+rem;
num=num/10;
}while(num>0);
[Link]("Reverse of Digit is = "+rev);
}
}

Output Will Be
Enter number
8976
Reverse of Digit is = 6798
The for Loop:
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to
execute a specific number of times.

A for loop is useful when you know how many times a task is to be repeated.

Syntax:
The syntax of a for loop is:

for(initialization; Boolean_expression; update)


{
//Statements
}

Here is the flow of control in a for loop:

 The initialization step is executed first, and only once. This step allows you to declare
and initialize any loop control variables. You are not required to put a statement here, as
long as a semicolon appears.
 Next, the Boolean expression is evaluated. If it is true, the body of the loop is executed. If
it is false, the body of the loop does not execute and flow of control jumps to the next
statement past the for loop.

 After the body of the for loop executes, the flow of control jumps back up to the update
statement. This statement allows you to update any loop control variables. This statement
can be left blank, as long as a semicolon appears after the Boolean expression.

 The Boolean expression is now evaluated again. If it is true, the loop executes and the
process repeats itself (body of loop, then update step, then Boolean expression). After the
Boolean expression is false, the for loop terminates.

Example:
public class LoopDemo3
{
public static void main(String st[])
{

for(int i=1;i<=10;i++)
{
[Link]("i= "+i);

}
}
}

Nested Loop
Example:
public class NestedLoop
{
public static void main(String st[])
{

for(int i=1;i<=5;i++)
{
for(int j=1;j<=i;j++)
{
[Link](j+" ");
}
[Link]();
}
}
}

Output Will Be

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
The break Keyword:
The break keyword is used to stop the entire loop. The break keyword must be used inside any
loop or a switch statement.

The break keyword will stop the execution of the innermost loop and start executing the next line
of code after the block.

Syntax:

The syntax of a break is a single statement inside any loop:


break;

Example1:
import [Link];
public class DigitSum {
public static void main(String[] args)
{
Scanner sr=new Scanner([Link]);
int num,sum=0,rem;
[Link]("Enter number ");
num=[Link]();
for(;;)
{
if(num==0)
{
break;
}
rem=num%10;
sum=sum+rem;
num=num/10;
}
[Link]("Sum of Digit is = "+sum);

Output Will Be
Enter number
4567
Sum of Digit is = 22
Example2:
import [Link];
public class BreakDemo2
{
public static void main(String st[])
{

Scanner sr=new Scanner([Link]);


int i,ln,j,f=0;
String str;
[Link]("Enter Any String ");
str=[Link]().toUpperCase();
ln=[Link]();
for(i=0,j=ln-1;i<ln/2;i++,j--)
{
if([Link](i)!=[Link](j))
{
f=1;
break;
}
}
if(f==0)
{
[Link]("String is Palindrome");
}
else
{
[Link]("String is Not Palindrome");
}

}
}

Output Will Be
Enter Any String
graphic
String is Not Palindrome

Output Will Be
Enter Any String
arora
String is Palindrome
The continue Keyword:
The continue keyword can be used in any of the loop control structures. It causes the loop to
immediately jump to the next iteration of the loop.

 In a for loop, the continue keyword causes flow of control to immediately jump to the
update statement.

 In a while loop or do/while loop, flow of control immediately jumps to the Boolean
expression.

Syntax:

The syntax of a continue is a single statement inside any loop:

continue;

Example:

import [Link];
public class ContinueDemo
{
public static void main(String st[])
{

Scanner sr=new Scanner([Link]);


int i,ln,c=0;
String str;
[Link]("Enter Any String ");
str=[Link]();
[Link]("Enter Searching key ");
char ch=[Link]().charAt(0);
ln=[Link]();
for(i=0;i<ln;i++)
{
if(ch!=[Link](i))
{
continue;
}
c++;
}
[Link]("Number Of Time ["+ch+"] Occur= "+c);
}
}

Output Will Be
Enter Any String
we are learning java
Enter Searching key
a
Number Of Time [a] Occur= 4

Java's Labeled break Statement


A labeled break marks a block of code and gets you out of that block when executed within
from that block. The condition is that the break statement should be executed within from the
same block and properly labeled.

The syntax of labeled break statement goes here:


break label;

Example:
public class LabelBreakDemo
{
public static void main(String st[])
{

Outer:
for(int i=1;i<=5;i++)
{
for(int j=1;j<=i;j++)
{

if(j==3)
{
break Outer;
}
[Link](j+" ");
}
[Link]();
}
}

Output Will Be
1
1 2
1 2

Java's Labeled continue Statement

public class LabelContinuDemo


{
public static void main(String st[])
{

String str="Graphic";
int ln=[Link]();

Outer:
for(int i=0;i<ln;i++)
{
for(int j=0;j<=i;j++)
{

if(j==2)
{
continue Outer;
}
[Link]([Link](j));
}
[Link]();
}
}
}

Output Will Be

G
Gr
GrGrGrGrGr

You might also like