0 ratings 0% found this document useful (0 votes) 4 views 10 pages Java Loops
The document provides an overview of Java looping mechanisms, including the while, do...while, for, and enhanced for loops, along with their syntax and examples. It also discusses the break and continue keywords used to control loop execution. Additionally, the document introduces decision-making statements in Java, such as if, if...else, and switch statements, with their respective syntax and examples.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here .
Available Formats
Download as PDF or read online on Scribd
Carousel Previous Carousel Next
Save Java Loops For Later Java Loops - for, while and do...while
Advertisments
Previous Page
Next Page
‘There may bea situation when we need to execute a black of code several number oftimes, and is often referred to
‘2s alloop,
Java has vory exe three looping mechanisms. You can use ene ofthe following three loops:
whi
Loop
o..while Lasp,
far Loop
5 of Java 5, the emhanced ferloop was intraduced, This is mainly used for Arrays.
The while Loop:
Awhile loop is a control structure that allows you te repeat lask.a certain number of times.
Syntax:
‘The syntax ofa while loops:
while (Soolean_expressicn)
ii
When executing, ifthe boolean _oxpression res.ullis tue, then the actions inside the loop will be executed. This will
‘continue as long as Gre exprassion rasuitis tus,
Here, key int of the while loop i thatthe loop might nol ever fun, When the expres sion is tested and the result is
false, the loop body will be skipped and the first statement after the while loop will be exzculed.
Example:
UE Print ("value of x
yatem.out print ("
“This would produce the following resultvelue of xt 10
value of xt 11
value of xt 12
value of xt 13
value of xt 1é
value of x: 15
value of # : 16
value of x 117
value of x + 18
valve of x + 19
The do...while Loop:
‘Ado...while loop is similar to awhile foop, amept thata do,..while loop is guaranteed to execute atleast one sme,
hile loop is:
//stavenents
while (Boolean.
sxpres sion):
‘Notice that the Boolean expression appears atthe endof the foap, sothe statements. the loop exncute ance before
the Boolean is tested,
lithe Boolean expression is true, the flow of contol jumps back up fo do, and the statements in the loop erecule
‘apain, This process repeats until the Boolean expression is false.
Example:
public ela:
public static void mainisteing arge(})
do
jem,our sprint (“value of 3% + 8 08
Syoten-out print ("\n%) ;
while ( x Me
“This would produce the following result:
of
of
of
of
of
of.
value of
valve of
value of
we of
10
rar
raeThe for Loop:
‘Aor loop is a repetition contol structure that allows you to affientlywrita a loop that noads to emeute a specific
umber of times.
‘A for loop is useful when you know how many times a task is to be repeated.
Syntax:
“The syntax of afor loop is:
dot(iniGiald sation? Boclean expresalony update)
/1ecacenenes
Here's the flow of contr in for oop:
“The initialization stop is executed frst, and onlyonce. This step allows you to declare and jnitalize anyloap contrat
\arisble, You are not required to puta statement here, as long as a semicolon appears.
‘Nex, the Boolean expression is evaluated. itis tue, tro Body of the loop Is exseuted. Ii is fale
Joep do2s nat exocula and flow of contra jumps to the ned statement past ine forloap.
be badyof the
‘Ator tho bedy of tho for loop exxeutes, tha flow of contal jumps back up to the Updaie statement. This statemont
allows you lo update any loop contol variables, This statment can baleftblank, as fong as a semicolon appears
‘afer the Boolean exmession.
‘The Boolean expression is now evaluated again itis tue, the loop executes and the process repaats ilsolf (body of
oop, thee Update step, then Boolean expression), ARer te Boolean expression is false, the for loop terminates,
a < 20¢ 8 = ROL)
print value of x ae
print (Na)
‘This would produce the fallowing result:
value of
value of
value of
value of
valid 6£
valve of
value of
value of
value of
10
pavalue of xt 19
Enhanced for loop in Java:
‘4s of Java 5, the enhanced far loop was introduced, This is mainly used for Arrays.
Syntax:
‘The syntax af enhanced for loop is
for(declaration : expression)
7/Statonents.
Declaration: The newly declared black variable, which is of a ype compatible with the elements ofthe array you are.
accessing, The variable will be available within the for block and its value would te the same as the cuerent array
‘element.
Expression: This avsluates to the array you naed t© loop through, The expression can be an armay variable or
‘method call thatretums an array.
Example:
public claza Teat
public static void mainist
int [| numbers = (10,
bare}
print( x)
for(int ©: m
ng name; nam
sour print name 1%
This would produce the following result
10,20, 30,40, 50,
Janes, Lakry, Tom, Lacy,
The break Keyword:
‘The broak keyword is used lo stop the entira loop. The break keyword must be used inside any loop or a switch
‘stalement
‘The break Keyword will stop the execution of the innermost loop and start executing the next line afeoda aftr the
block,
Syntax:
‘The syntax of a break isa single statement inside any loop:public static void ma A
ine [| numbers 50)
for(int + num
print ( x)
print c\n")
“This would produce the following result
10
20
The continue Keyword:
‘he ciatiquekayword canbe used nay fe log conte! cuties. Iteauses Bislop lo mnnadliny mp tote
tes leraton of ha loop.
Ia for loop, the continue keyword causes flaw of control to immediataly jump to the update statement.
Ina while loop oF dohwhile loop, fow of control immediately jumps to the Boolean expression.
Syntax:
“The syntax ofa continue is a single statement inside anyloop!
Example:
panic elses: Test
int [] mumbera - (10, 20, 30, 49, 5:
for(int #2 nuabers
Hix — 30)
em. out print
‘This would produce the following result:Whatis Next?
{nthe following chapter, wo wil be leaming about decision making statements in Java programming,
Java Decision Making
‘Advedisements
Previous Page
‘Thore 16 twa types of decision making statements in Java, They are:
itstaloments
‘switch statements
The if Statement:
‘0 if statement consists of a Boolean expression followed by ono or more statements.
Syntax:
‘The syntax of an if statement is
Boolean expression)
{/Seakenents will ewecute if the Boolean expression is true
Ii the Boolean epression evaluates to tue then the block of code inside the i siatement will be executed. Inotthe:
first sat al code after the end of the if statement (after the clasing curlybrace) will be emcuted,
Example:
public clase 7
void main‘This would produce the following result:
This ie Lf statement
The if...else Statement:
0 if statementcan be followed by an optional eise statement, which executes whenthe Boolean expressionis false.
Syntax:
4£(BooLean_expression )(
Jiteectes vhen the Usolesn expression is trie
alae|
[ieeecutas ven the Boolean expression (3 false
Example:
public €laos Test
public static void maintstring args (1)
prints
This would produce the following result
This {s else staesent
The if...else if...else Statement:
4n if stalementcanbe followed by an optional else if.e/se stalement, which is veryusetul to test verious conditions
using single if else if statement.
When using if else ese statements there ae few points to keepin mind.
‘An itcan have zero or one else's and it mustcome ater anyelse ifs
‘An ifcan have zero to many else ifs and they must come before the else
‘Once an else succeeds, none of
(fs or else's will be tasted,
{f (Boolean expression 1)(
//€xecutes when the Boolean expression 1 4a
else (£(Beo lean expression 2)/PPxecutes when the Boolesn expression 21a true
else {f(Boo lean expression 3)/
//executes vhen the Boolean expression 3s true
else |
/(Ececutes when the none of the above condition i# true.
Example:
sedblic: claw! te8h
public static veld mainiString arge[)
ine x = 307
ony
n.OUE Prine ("Value Of x +
SUE print ("alte BE x de 30") r
out print ("this
‘This would produce the following result:
Value of X is 30
Nested if...else Statement:
tt is always legal tonest iets statements which means you can use one or aise if statementinside another ifor
‘alse statement,
Syntax:
“The syntax fora nested it.olse is as follows:
if (Boolean expreasion 1)/
[Executes ven the Boo
Af (moolean expression 2)
Tfexecutes when the Boolean expreseion 2 is true
wan expression tia
‘You can nest eise ifefse in ihe similarwayas we have nested Hf statament.
Example:
public class Test
public static void mainist
int x = 30;
int y = 10“This would produce the following result:
X= 30 and ¥ = 10
The switch Statement:
‘A swiich statementallows a vriableio be tested for equalityagainsta listof values. Each value is called a case, and
the variable beings witched on js checked for each case.
Syntax:
“Tho syntax af enhanced for loop is
switch(enpression) (
case value ¢
(/Skatenents
break; //optional
case valve :
7/Statenents
break: //optional
//rou can have any nunber of case statensnta.
default : //optional
/fStatenants
‘The following rules apply to a switch statement:
“Tho variable used in a switch staterentcan only be a byto, short, int, ar char
‘You canhave anynumberot case statements within a switch. Each case is folowad by the value to be compared to
land a colon,
‘The value fora case mustbe the same data type as the variable in the switch and it must be a canstant ora literal
When the variable being switched on is equal to a case, the statements ‘ollowing that case will execute un
2 break statements reached
\Whon a by0ok siatomentis reached, theswiteh torminatos, andthe Now of contotjumps to the nox line following the
‘swited statement,
Not every case needs to containa break. if nobreak appears, teow of contol wil fal throughto subs equent cases
‘until break is reached
‘A aiteh staloment ean have an optional dataultease, which mustappear at he and ofthe switch, The detault case
‘can be used for performing a task when none ofthe cases is irve, No breaks neaded inthe defaultcase,
Example:
public class Test
fehar qrad O} cha rar cOr
war qrade
higraderSystem.out
break
case th
system.out printin ("Well done”
brea)
yatem.outeprintin( "You passed")
eee
Systemout -printin(*Bettar try again"
brooke
default
Systemout ,printin(*i
nbn (*excedtent |")
System out. printin(*¥o
‘Compile ang run above program using various command line arguments. This would produce the following result
S java Test
Well done
Your grade isa
3
Whatis Next?
(Next chapter discuses about the Number class (in the java.lang package} and its subclasses in Java Language.
‘We will be looking into some of the siusations whare you wauld use instantiatons of these classes rather then the
Primitive data ypes. as wallas classes such as formating, mathematical functions thalyou neadto knowabout when
‘working with Numbers,