KEMBAR78
Flow Control | PDF | Control Flow | Boolean Data Type
0% found this document useful (0 votes)
22 views14 pages

Flow Control

The document provides an overview of flow control statements in Java, categorizing them into selection (if, if-else, else-if, switch), iteration (for, for-each, while, do-while), and transfer statements (break, continue, try, return). It includes syntax examples and explanations for each type, along with practical examples and assignments for better understanding. Additionally, it covers the use of the Scanner class for user input and various scenarios for implementing flow control in programming.

Uploaded by

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

Flow Control

The document provides an overview of flow control statements in Java, categorizing them into selection (if, if-else, else-if, switch), iteration (for, for-each, while, do-while), and transfer statements (break, continue, try, return). It includes syntax examples and explanations for each type, along with practical examples and assignments for better understanding. Additionally, it covers the use of the Scanner class for user input and various scenarios for implementing flow control in programming.

Uploaded by

kiran
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 14

Flow Control

Flow Control statements

There are three types of flow control statements in java


a. Selection/conditional Statements
if : to take only one option
if-else : to take two options
else-if : to take more than two options.
switch : take the multiple options of same type of
case labels.

b. Iteration/looping statements
for
for-each
while
do-while

c. Transfer/jumping statements
break
continue
try
return
goto (unused)

1. if : to take only one option


syntax :
if (cond)
{ true body
}
if statement is taking condition that condition must be boolean type.

ex:
class Test
{ public static void main(String[] args)
{ int x = 20, y = 10;
if (x > y)
{ System.out.println("x is greater than y");
}
}
}

ex:
int x = 20, y = 10;
if (x > y) {
System.out.println("x is greater than y");
}

2. if-else: takes two options


syntax :
if (cond)
{ true body
}
else
{ false body
}

case 1: here taking normal condition.

class Test
{ public static void main(String[] args)
{ int age = 20;
if (age>22)
{ System.out.println("Eligible for marriage");
}
else
{ System.out.println("not Eligible for marriage try after
some time....");
}
}
}

import java.util.Scanner;
class Test
{ public static void main(String[] args)
{ Scanner s = new Scanner(System.in);
System.out.println("Enter u r age:");
int age = s.nextInt();

if (age>22)
{ System.out.println("Eligible for marriage");
}
else
{ System.out.println("not Eligible for marriage try after
some time....");
}
}
}

case 2: To the if condition it is possible to provide Boolean constants directly.


if (true)
{ System.out.println("true body");
}
else
{ System.out.println("false body");
}

case 3: in c-language 0-false & 1-true but these conventions are not allowed in
java.
if (0)
{ System.out.println("true body");
}
error: incompatible types: int cannot be converted to boolean

case 4 : comparision vs. assignment


valid: == : this is comparision : returns boolean value
int x=20;
if (x==20)
{ System.out.println("true body");
}

invalid : = : assignment
int x=10;
if (x=20)
{ System.out.println("true body");
}

case 5 : The curly brasses are optional but without curly braces it is possible to
take only one statement that should not be a initialization.
class Test
{ public static void main(String[] args)
{ if (true)
System.out.println("true body");
else
System.out.println("false body");
}
}

Observation: without curly braces it is possible to take only one statement that
should not be a initialization.
class Test
{ public static void main(String[] args)
{ if (true)
int a=10;
else
System.out.println("false body");
}
}
error: variable declaration not allowed here

case 6 : To take the input from end-user use Scanner class.


Scanner class present in java.util package, so import the class using
import statement.
Scanner class introduced in java-5.

To read the byte data : nextByte()


To read the short data : nextShort()
To read the int data : nextInt()
To read the long data : nextLong()
To read the float data : nextFloat()
To read the double data : nextDouble()
To close the scanner object : close()

To read the String data : next() "Addanki ratan" : next() method will take the
data upto space(one word)
To read the complete line: nextLine() "Addanki ratan" : it will read the
complete line with spaces.

case 6 : taking input from end user using Scanner object.


Scanner class present in java.util so import the class.

To read the int data : nextInt()


To read the byte data : nextByte()

To read the float data : nextFloat()


To read the double data : nextDouble()

To read the String data : next() "Addanki ratan" :


next() method will take the data upto space(one word)
To read the complete line : nextLine() "Addanki ratan" : it
will read the complete line with spaces.

To close the scanner object : close()

import java.util.Scanner;
class Test
{ public static void main(String[] args)
{
Scanner s = new Scanner(System.in);

System.out.println("Enter emp id:");


int eid = s.nextInt();

System.out.println("Enter emp name:");


String ename = s.next();

System.out.println("Enter emp sal");


double esal = s.nextDouble();

System.out.println("Emp id: "+eid);


System.out.println("Emp Name: "+ename);
System.out.println("Emp sal: "+esal);

s.close();
}
}
Assignments

Assignment 1: take the number from end user check it is even or odd?

Assignment 2: take the two numbers from end user print the bigger number?

Assignment 3: take the year from end user check it is leap year or not?

Assignemnt 4:take the number from end user


(use nested if-else condition).
ouptut :
enter a num : 2
Number is positive & even
ouptut :
enter a num : 3
Number is positive & odd

ouptut :
enter a num : -6
Number is Negative & even

ouptut :
enter a num : -7
Number is Negative & odd

else if: takes more than two options


syntax:
if (cond)
{ st(s)
}
else if (cond)
{ st(s)
}
else if (cond)
{ st(s)
}
else
{ st(s)
}
ex-1:
class Test
{ public static void main(String[] args)
{ int a = 300;
if (a==10)
{ System.out.println("Tharun don't sleep");
}
else if (a==20)
{ System.out.println("don't sleep");
}
else if (a==30)
{ System.out.println("ravi don't sleep");
}
else
{ System.out.println("ramu don't sleep");
}
}
}

ex-2:
import java.util.Scanner;
class Test
{ public static void main(String[] args)
{ Scanner s = new Scanner(System.in);
System.out.println("Enter a number:");
int num = s.nextInt();

if (num>0)
{ System.out.println("number is positive");
}
else if (num<0)
{ System.out.println("number is negative");
}
else
{ System.out.println("zerooooooooooo........");
}
}
}
Assignments : else-if
ex 1: Assignment
Take student name from user
Take the marks from user
maths marks :
science marks :
social marks :

grade varaible with empty value : ''


calculate the percentage

avg>=70 : Assign grade varible with 'A'


avg 60-69 : Assign grade varible with 'B'
avg 50-59 : Assign grade varible with 'C'
avg 40-49 : Assign grade varible with 'D'
avg<40 : print the mesage "sorry you are failed....."

I need Output message : hi "student-name" your marks:136 & your grade is:"grade"
hi ratan your marks:236 & your grade is:A
ex-3: write the code using else if.
take the day from end user
Enter day : suday
mon,tue : Discount 2%
web , thr : Discount 4%
sat, sun : Discoutn 6%
if user enter invalid data give proper error message.

//switch : multiple options


a. Switch statement is used to declare multiple options.
b. Switch is taking the argument, the allowed arguments are
byte,short,int,char (primitive data types)
2147483647
Byte, Short,Integer,Character (wrapper calsses) java 1.5
enum (java 1.5 v)
String (java 1.7 v)

c. Inside the switch possible to declare multiple cases but it is possible to


declare only one default.
d. Based on the provided argument the matched case will be executed if the cases
are not matched default will be executed.
e. Float,double,long is not allowed as a switch argument because these are having
too large values.
f. boolean is not allowedd beacuse boolean contains too short values.

syntax:
switch(argument)
{ case label-1 : statements;
break;
case label-2 : statements;
break;
| |
| |
case label-n : statements;
break;
default : statements;
break;
}

case 1: normal example


class Test
{ public static void main(String[] args)
{ int a=20;
switch (a)
{ case 10:System.out.println("ratan");
break;
case 20:System.out.println("anu");
break;
default:System.out.println("naresh");
break;
}
}
}

case 2:
a. Inside the switch statement break is optional.
b. If we are not declaring break statement then from the matched case onwards up to
the next break statement will be executed, if there is no break statement then end
of the switch will be executed.
c.The above situation is called as "fall though" inside the switch.

class Test
{ public static void main(String[] args)
{ int a=10;
switch (a)
{ case 10:System.out.println("ratan");
case 20:System.out.println("anu");
break;
default:System.out.println("naresh");
}
}
}

case 3: default is optional


class Test
{ public static void main(String[] args)
{ int a=100;
switch (a)
{ case 10:System.out.println("ratan");
}
}
}

case 4:cases are optional


class Test
{ public static void main(String[] args)
{ int a=10;
switch (a)
{ default:System.out.println("naresh");
}
}
}

case 5: both case & default is optional.


class Test
{ public static void main(String[] args)
{ int a=10;
switch (a)
{
}
}
}

case 6:Invalid : Inside the switch independent statements are not allowed. If we
are declaring the statements that statement must be inside the case or default.

int a=100;
switch (a)
{ System.out.println("ratan");
}

case 7 : default can be any statement


int a=100;
switch (a)
{ case 10:System.out.println("ratan");
default:System.out.println("naresh");
case 20:System.out.println("anu");
}

case 8:
class Test
{ public static void main(String[] args)
{ int a = 10;
switch (a)
{ case 10:System.out.println("ratan");
case 10:System.out.println("anu");
}
}
}
error: duplicate case label

case 9: unicode conversions


class Test
{ public static void main(String[] args)
{ //a = 97 A=65
char ch='a';
switch (ch)
{ case 'b':System.out.println("ratan");
case 97:System.out.println("anu");
}
}
}

case 10: unicode conversion


class Test
{ public static void main(String[] args)
{ //a = 97 A=65
int x = 100;
switch (x)
{ case 'd':System.out.println("ratan");
case 99:System.out.println("anu");
}
}
}

case 11: if we are passing byte as a switch argument the case labels must be
with in the range of the byte.
class Test
{ public static void main(String[] args)
{ byte b = 127;
switch (b)
{ case 127:System.out.println("ratan");
case 128:System.out.println("anu"); //error
}
}
}

case 12: The swith argument is string means inside the switch the case labels
must string only.
class Test
{ public static void main(String[] args)
{
String str = "aaa";
switch (str)
{ case "aaa":System.out.println("ratan");
case 'b':System.out.println("anu");
}
}
}
error: incompatible types: char cannot be converted to String

case 13: fall througt inside the switch.


import java.util.*;
class Test
{ public static void main(String[] args)
{ Scanner s = new Scanner(System.in);
System.out.println("Enter u r option");
int option = s.nextInt();
switch (option)
{ case 1:
case 2:
case 3: System.out.println("Q-1");;
break;
case 4:
case 5:
case 6: System.out.println("Q-2");;
break;
case 7:
case 8:
case 9: System.out.println("Q-3");;
break;
default : System.out.println("U entered Invalid option");
break;
}
s.close();
}
}

case 14: for multiple cases writing same logics.


Enter A day :
mon,tue,wed : 3%
thr,fri : 4%
sat,sun : 5%
when user entered other than these days give some error.

================================
Looping statements :
================================
for
for-each
while
do-while

for :
1 2 4
for (initialization; condition ;inc)
{ body 3
}

case 1:
class Test
{ public static void main(String[] args)
{ for (int i=0;i<10 ;i++)
{ System.out.println("ratan world..."+i);
}
}
}

case 2:initialization part is optional but the semicolon is mandatory.


int i=0;
for ( ;i<10 ;i++)
{ System.out.println("ratan world..."+i);
}

case 3: in the initialization part possible to take SOP


int i=0;
for (System.out.println("ratan");i<10 ;i++)
{ System.out.println("ratan world..."+i);
}

case 4:
Invalid: in the initialization declaration of data types two times not
allowed
for (int i=0,int j=0;i<10 ;i++)
{ System.out.println("ratan world..."+i);
}

Valid: one data type with multiple variables are allowed.


for (int i=0,j=0;i<10 ;i++)
{ System.out.println("ratan world..."+i);
}

case 5: condition part is optional by default the compiler will place true value.
for (int i=0; ;i++)
{ System.out.println("ratan world..."+i);
}

case 6: inc/dec part is optional.


for (int i=0;i<10;)
{ System.out.println("ratan world..."+i);
i++;
}

case 7 : inc/dec possible to take the sop


for (int i=0;i<10 ;System.out.println("Anu"))
{ System.out.println("ratan");
i++;
}

case 8 : infinite loop because the condition is true


for (;;)
{ System.out.println("ratan world...");
}

//unreachable statement:
case 1 : error: unreachable statement
for (int i=0;true;i++)
{ System.out.println("ratan world...");
}
System.out.println("Anu world"); //error

case 2:error: unreachable statement


for (int i=0;false;i++)
{ System.out.println("ratan world..."); //error
}
System.out.println("Anu world");

case 3:
for (int i=1;i>0;i++)
{ System.out.println("ratan world...");
}
System.out.println("Anu world");
the above example no error because the condition may be chance of fail.

Note : we will get unreachable statement when we give only boolean constants.
once we write the condition even the condition is shows infinite
times, but compiler will not generate error message => because may be a chance of
the condition is fail.

ex: break vs. continue


import java.util.Scanner;
class Test
{ public static void main(String[] args)
{ Scanner s = new Scanner(System.in);
System.out.println("Boys Enter a num:");
int bnum = s.nextInt();
for (int i=0;i<10;i++)
{ if (i==bnum)
break;
System.out.println(i);
}

System.out.println("Girls Enter a num:");


int gnum = s.nextInt();
for (int i=0;i<10;i++)
{ if (i==gnum)
continue;
System.out.println(i);
}
}
}
we can use the break statement only two areas
1. inside the switch
2. inside the loops

if (true)
{ System.out.println("Ratan");
break;
System.out.println("Ratan");
}
error: break outside switch or loop

Assignment-1: print the even values from 1-20

Assignment-2:
in application take the pin=1234
take the pin from end user.
if the application pin & user pin both are valid print the message :
congratulations pin is valid stop the execution
if the pin is invalid take four attempts after four attempts say bye bye.

for-each loop : java 1.5 version :


syntax :
for (type temp_var : iterate_data)
{ System.out.println(temp_var );
}

ex:
class Test
{ public static void main(String[] args)
{ int[] a = {10,20,30,40};
System.out.println(a[0]);
System.out.println(a[1]);
System.out.println(a[2]);
System.out.println(a[3]);

for (int i=0;i<a.length ; i++)


{ System.out.println(a[i]);
}

for (int aa : a)
{ System.out.println(aa);
}
}
}

//for loop possible to apply the conditions : start end inc


i have 1000 but i want to print 333 444
for (int i=333;i<444;i++)
{ System.out.println(i);
}

//for-each loop prints the data starting to end


no conditions appy

while:
syntax :
while (cond)
{ body
}
The body will be executed until the condition is fail.

ex-1:
class Test
{ public static void main(String[] args)
{
int i=0;
while (i<10)
{ System.out.println("ratan....");
i++;
}

for (int j=0;j<10 ;j++)


{ System.out.println("ratan....");
}
}
}

to print the data 10-time it is recommended to use for loop.

ex-2:
import java.util.Scanner;
class Test
{ public static void main(String[] args)
{ int guss = 25;
Scanner s = new Scanner(System.in);
while (true)
{ System.out.println("Enter your guss value:");
int userguss = s.nextInt();
if (userguss==guss){
System.out.println("Congratulations you won gift");
break;}
else if (userguss>guss){
System.out.println("your value is more then guss");
}
else{
System.out.println("your value is less then guss");
}
}
}
}

Note : if you know the number of iterations use =>for loop.


if you don't know the number of iterations use while loop.

ex-3: Assignment
take the emp id,emp name ,emp esal from end user
after taking the print the data
after printing give the message do you want one more record(yes/no)
yes : again take the data & print the data
no : stop the execution

import java.util.*;
class Test {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
while (true)
{ System.out.println("Etner a number");
int num = s.nextInt();
if (num==0)
{ System.out.println("Congratulations....");
break;
}
else if (num>0)
{ System.out.println("U r number is positive");
}
else
{ System.out.println("U r number is Neagtive");
}
}
}
}

Entry controlled loop : for,while


Exit control loop : do-while

do-while: if you want to execute body first then use do-while


do
{ body;
}while (cond);

ex 1:
class Test
{ public static void main(String[] args)
{ int i=0;
do
{ System.out.println("Good Morning");
i++;
}while (i<10);
}
}

ex 2:
class Test
{ public static void main(String[] args)
{ do
{ System.out.println("Good Morning");
}while (false);
System.out.println("Good Night");
}
}

Note:
the minimum occurrences in for,while : 0
the minimum occurrences in do-while : 1

You might also like