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

Java Class -6

The document provides an overview of decision-making structures in Java, detailing various statements such as if, if-else, nested if, and switch-case. It explains the syntax and examples for each type of statement, as well as the flow of control in loops like for and while. Additionally, it discusses the importance of break statements in switch cases and the coordination of boolean expressions in loops.

Uploaded by

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

Java Class -6

The document provides an overview of decision-making structures in Java, detailing various statements such as if, if-else, nested if, and switch-case. It explains the syntax and examples for each type of statement, as well as the flow of control in loops like for and while. Additionally, it discusses the importance of break statements in switch cases and the coordination of boolean expressions in loops.

Uploaded by

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

Decision making structures in Java

Decision making structures have one or


more conditions to be evaluated or
tested by the program, along with a
statement or statements that are to be
executed if the condition is determined
to be true, and optionally, other
statements to be executed if the
condition is determined to be false.
Following is the general form of a
typical decision making structure found
in most of the programming languages

Java programming language provides
following types of decision making
statements.
Sr. Statement &
No. Description

1 if statement
An if
statement c
onsists of a
boolean
expression
followed by
one or more
statements.
2 if...else
statement
An if
statement c
an be
followed by
an
optional els
e
statement,
which
executes
when the
boolean
expression
is false.
3 nested if
statement
You can use
one if or els
e
ifstatement
inside
another if or
else
if statement(
s).
4 switch
statement
A switch sta
tement
allows a
variable to
be tested for
equality
against a list
of values.

If statement in Java
An if statement consists of a Boolean
expression followed by one or more
statements.
Syntax
Following is the syntax of an if
statement −
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.
Flow Diagram

Example

public class Test {


public static void
main(String args[]) {
int x = 10;

if( x < 20 ) {
System.out.print("This is if
statement");
}
}
}
This will produce the following result −
Output
This is if statement.

If-else statement in Java


An if statement can be followed by an
optional else statement, which executes
when the Boolean expression is false.
Syntax
Following is the syntax of an if...else
statement −
if(Boolean_expression) {
// Executes when the
Boolean expression is true
}else {
// Executes when the
Boolean expression is false
}
If the boolean expression evaluates to
true, then the if block of code will be
executed, otherwise else block of code
will be executed.
Flow Diagram
Example

public class Test {

public static void main(String args[]) {


int x = 30;

if( x < 20 ) {
System.out.print("This is if
statement");
}else {
System.out.print("This is else
statement");
}
}
}
This will produce the following result −
Output
This is else statement
The if...else if...else Statement
Syntax
Following is the syntax of an if...else
statement −
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

public class Test {


public static void main(String args[]) {
int x = 30;

if( x == 10 ) {
System.out.print("Value of X is
10");
}else if( x == 20 ) {
System.out.print("Value of X is
20");
}else if( x == 30 ) {
System.out.print("Value of X is
30");
}else {
System.out.print("This is else
statement");
}
}
}
This will produce the following result −
Output
Value of X is 30

Nested if -statement in Java


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
The syntax for a nested if...else is as
follows −
if(Boolean_expression 1) {
// Executes when the
Boolean expression 1 is true
if(Boolean_expression 2) {
// Executes when the
Boolean expression 2 is true
}
}
You can nest else if...else in the similar
way as we have nested if statement.
Example

public class Test {

public static void


main(String args[]) {
int x = 30;
int y = 10;

if( x == 30 ) {
if( y == 10 ) {
System.out.print("X = 30 and Y
= 10");
}
}
}
}
This will produce the following result −
Output
X = 30 and Y = 10

Switch Case statement in Java


with example
Switch case statement is used when
we have number of options (or choices)
and we may need to perform a different
task for each choice.
The syntax of Switch case statement
looks like this –
switch (variable or an
integer expression)
{
case constant:
//Java code
;
case constant:
//Java code
;
default:
//Java code
;
}
Switch Case statement is mostly used
with break statement even though it is
optional. We will first see an example
without break statement and then we
will discuss switch case with break
A Simple Switch Case Example
public class
SwitchCaseExample1 {

public static void


main(String args[]){
int num=2;
switch(num+2)
{
case 1:
System.out.println("Case1:
Value is: "+num);
case 2:
System.out.println("Case2:
Value is: "+num);
case 3:
System.out.println("Case3:
Value is: "+num);
default:
System.out.println("Default:
Value is: "+num);
}
}
}
Output:
Default: Value is: 2
Explanation: In switch I gave an
expression, you can give variable also. I
gave num+2, where num value is 2 and
after addition the expression resulted 4.
Since there is no case defined with
value 4 the default case got executed.
This is why we should use default in
switch case, so that if there is no catch
that matches the condition, the default
block gets executed.
Task :
1. Java Program to find the largest of
three numbers using if..else..if
2. Java Program to check if number is
positive or negative
3. Java Program to check if number is
even or odd

Switch Case Flow Diagram


First the variable, value or expression
which is provided in the switch
parenthesis is evaluated and then based
on the result, the corresponding case
block is executed that matches the
result.

Break statement in Switch Case


Break statement is optional in switch
case but you would use it almost every
time you deal with switch case. Before
we discuss about break statement, Let’s
have a look at the example below where
I am not using the break statement:
public class
SwitchCaseExample2 {

public static void


main(String args[]){
int i=2;
switch(i)
{
case 1:
System.out.println("Case1 ");
case 2:
System.out.println("Case2 ");
case 3:
System.out.println("Case3 ");
case 4:
System.out.println("Case4 ");
default:
System.out.println("Default
");
}
}
}
Output:
Case2
Case3
Case4
Default
In the above program, we have passed
integer value 2 to the switch, so the
control switched to the case 2, however
we don’t have break statement after the
case 2 that caused the flow to pass to
the subsequent cases till the end. The
solution to this problem is break
statement
Break statements are used when you
want your program-flow to come out of
the switch body. Whenever a break
statement is encountered in the switch
body, the execution flow would directly
come out of the switch, ignoring rest of
the cases
Let’s take the same example but this
time with break statement.
Example with break statement
public class
SwitchCaseExample2 {

public static void


main(String args[]){
int i=2;
switch(i)
{
case 1:
System.out.println("Case1 ");
break;
case 2:
System.out.println("Case2 ");
break;
case 3:
System.out.println("Case3 ");
break;
case 4:
System.out.println("Case4 ");
break;
default:
System.out.println("Default
");
}
}
}
Output:
Case2
Now you can see that only case 2 had
been executed, rest of the cases were
ignored.
Why didn’t I use break statement
after default?
The control would itself come out of the
switch after default so I didn’t use it,
however if you still want to use the
break after default then you can use it,
there is no harm in doing that.
Few points about Switch Case
1) Case doesn’t always need to have
order 1, 2, 3 and so on. It can have any
integer value after case keyword. Also,
case doesn’t need to be in an ascending
order always, you can specify them in
any order based on the requirement.
2) You can also use characters in switch
case. for example –
public class
SwitchCaseExample2 {
public static void
main(String args[]){
char ch='b';
switch(ch)
{
case 'd':
System.out.println("Case1 ");
break;
case 'b':
System.out.println("Case2 ");
break;
case 'x':
System.out.println("Case3 ");
break;
case 'y':
System.out.println("Case4 ");
break;
default:
System.out.println("Default
");
}
}
}
3) The expression given inside switch
should result in a constant value
otherwise it would not be valid.
For example:
Valid expressions for switch:
switch(1+2+23)
switch(1*2+3%4)
Invalid switch expressions:
switch(ab+cd)
switch(a+b+c)
4) Nesting of switch statements are
allowed, which means you can have
switch statements inside another switch.
However nested switch statements
should be avoided as it makes program
more complex and less readable.
Task :
4. Java Program to check whether a
char is vowel or Consonant using
Switch Case
5. Java Program to make a Simple
Calculator using Switch Case

Looping structures in Java

A loop statement allows us to execute


a statement or group of statements
multiple times and following is the
general form of a loop statement in
most of the programming languages −
Java programming language provides
the following types of loop to handle
looping requirements.
Sr.No Loop &
. Descriptio
n

1 while loop
Repeats a
statement
or group of
statement
s while a
given
condition
is true. It
tests the
condition
before
executing
the loop
body.
2 for loop
Execute a
sequence
of
statement
s multiple
times and
abbreviate
s the code
that
manages
the loop
variable.
3 do...while
loop
Like a
while
statement,
except
that it tests
the
condition
at the end
of the loop
body.
For loop in Java with example

A for loop is a repetition control


structure that allows you to efficiently
write a loop that needs to be executed 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

6. The initialization step is executed
first, and only once. This step allows
you to declare and initialize any loop
control variables and this step ends
with a semi colon (;).
7. 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 will not be executed
and control jumps to the next
statement past the for loop.
8. After the body of the for loop gets
executed, the control jumps back up
to the update statement. This
statement allows you to update any
loop control variables. This
statement can be left blank with a
semicolon at the end.
9. The Boolean expression is now
evaluated again. If it is true, the loop
executes and the process repeats
(body of loop, then update step, then
Boolean expression). After the
Boolean expression is false, the for
loop terminates.
Flow Diagram
Example
Following is an example code of the for
loop in Java.

public class Test {

public static void main(String args[]) {

for(int x = 10; x < 20; x = x + 1) {


System.out.print("value of x : " + x );
System.out.print("\n");
}
}
}
This will produce the following result −
Output
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19

Example of Simple For loop


class ForLoopExample {
public static void
main(String args[]){
for(int i=10; i>1;
i--){

System.out.println("The value
of i is: "+i);
}
}
}
The output of this program is:
The value of i is: 10
The value of i is: 9
The value of i is: 8
The value of i is: 7
The value of i is: 6
The value of i is: 5
The value of i is: 4
The value of i is: 3
The value of i is: 2
In the above program:
int i=10 is initialization expression
i>1 is condition(Boolean expression)
i– Decrement operation
Infinite for loop
The importance of Boolean expression
and increment/decrement operation co-
ordination:
class ForLoopExample2 {
public static void
main(String args[]){
for(int i=1; i>=1;
i++){
System.out.println("The value
of i is: "+i);
}
}
}
This is an infinite loop as the condition
would never return false. The
initialization step is setting up the value
of variable i to 1, since we are
incrementing the value of i, it would
always be greater than 1 (the Boolean
expression: i>1) so it would never return
false. This would eventually lead to the
infinite loop condition. Thus it is
important to see the co-ordination
between Boolean expression and
increment/decrement operation to
determine whether the loop would
terminate at some point of time or not.
Here is another example of infinite for
loop:
// infinite loop
for ( ; ; ) {
// statement(s)
}
For loop example to iterate an
array:
Here we are iterating and displaying
array elements using the for loop.
class ForLoopExample3 {
public static void
main(String args[]){
int
arr[]={2,11,45,9};
//i starts with 0 as
array index starts with 0 too
for(int i=0;
i<arr.length; i++){

System.out.println(arr[i]);
}
}
}
Output:
2
11
45
9
10. Java Program to find sum of natural
numbers using for loop
11. Java Program to find factorial of a
number using loops
12. Java Program to print Fibonacci
Series using for loop

While loop in Java


A while loop statement in Java
programming language repeatedly
executes a target statement as long as
a given condition is true.
Syntax
The syntax of a while loop is −
while(Boolean_expression) {
// Statements
}
Here, statement(s) may be a single
statement or a block of statements.
The condition may be any expression,
and true is any non zero value.
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.
When the condition becomes false,
program control passes to the line
immediately following the loop.
Flow Diagram

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
public class Test {

public static void


main(String args[]) {
int x = 10;

while( x < 20 ) {
System.out.print("value of x :
" + x );
x++;
System.out.print("\
n");
}
}
}
This will produce the following result −
Output
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19

do… while loop in Java


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
Following is the syntax of a do...while
loop −
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
control jumps back up to do statement,
and the statements in the loop execute
again. This process repeats until the
Boolean expression is false.
Flow Diagram
Example

public class Test {

public static void


main(String args[]) {
int x = 10;

do {
System.out.print("value of x :
" + x );
x++;
System.out.print("\
n");
}while( x < 20 );
}
}
This will produce the following result −
Output
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19

Loop Control Statements


Loop control statements change
execution from its normal sequence.
When execution leaves a scope, all
automatic objects that were created in
that scope are destroyed.
Java supports the following control
statements.
Sr. Control
No. Statement
&
Description

1 break
statement
Terminates
the loop or
switch
statement
and
transfers
execution to
the
statement
immediately
following the
loop or
switch.
2 continue
statement
Causes the
loop to skip
the
remainder
of its body
and
immediately
retest its
condition
prior to
reiterating.

The break statement in Java


The break statement in Java
programming language has the
following two usages −
13. When the break statement is
encountered inside a loop, the loop
is immediately terminated and the
program control resumes at the next
statement following the loop.
14. It can be used to terminate a case
in the switch statement
Syntax
The syntax of a break is a single
statement inside any loop −
break;
Flow Diagram

Example – Use of break in a while


loop
In the example below, we have a while
loop running from o to 100 but since we
have a break statement that only occurs
when the loop value reaches 2, the loop
gets terminated and the control gets
passed to the next statement in program
after the loop body.
public class BreakExample1 {
public static void
main(String args[]){
int num =0;
while(num<=100)
{

System.out.println("Value of
variable is: "+num);
if (num==2)
{
break;
}
num++;
}
System.out.println("Out
of while-loop");
}
}
Output:
Value of variable is: 0
Value of variable is: 1
Value of variable is: 2
Out of while-loop
Example – Use of break in a for
loop
The same thing you can see here. As
soon as the var value hits 99, the for
loop gets terminated.
public class BreakExample2 {
public static void
main(String args[]){
int var;
for (var =100; var>=10; var
--)
{

System.out.println("var:
"+var);
if (var==99)
{
break;
}
}
System.out.println("Out of
for-loop");
}
}
Output:
var: 100
var: 99
Out of for-loop
Example – Use of break statement
in switch-case
public class BreakExample3 {

public static void


main(String args[]){
int num=2;

switch (num)
{
case 1:
System.out.println("Case 1
");
break;
case 2:

System.out.println("Case 2
");
break;
case 3:

System.out.println("Case 3
");
break;
default:

System.out.println("Default
");
}
}
}
Output:
Case 2

The Continue statement in Java


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.
15. In a for loop, the continue
keyword causes control to
immediately jump to the update
statement.
16. In a while loop or do/while loop,
control immediately jumps to the
Boolean expression.
Syntax
The syntax of a continue is a single
statement inside any loop −
continue;
Flow Diagram

Example: continue statement


inside for loop
public class ContinueExample
{
public static void
main(String args[]){
for (int j=0; j<=6; j++)
{
if (j==4)
{
continue;
}

System.out.print(j+" ");
}
}
}
Output:
0 1 2 3 5 6
Example: Use of continue in While
loop
Same thing you can see here. We are
iterating this loop from 10 to 0
for countervalue and when the counter
value is 7 the loop skipped the print
statement and started next iteration of
the while loop.
public class ContinueExample2
{

public static void


main(String args[]){
int counter=10;
while (counter >=0)
{
if (counter==7)
{
counter--;
continue;
}

System.out.print(counter+"
");
counter--;
}
}
}
Output:
10 9 8 6 5 4 3 2 1 0
Example of continue in do-While
loop
public class ContinueExample3
{
public static void
main(String args[]){
int j=0;
do
{
if (j==7)
{
j++;
continue;
}
System.out.print(j+ "
");
j++;
}while(j<10);

}
}
Output:
0 1 2 3 4 5 6 8 9

You might also like