Tutorial # 6
The
Enhanced for loop
It is also
sometime called as “for each loop” which mainly help to go through all the
collection
elements efficiently.
elements efficiently.
Syntax:-
For(Type identifier: Expression)
{
//statements;
}
Where, type
represents the data-type or object used & Identifier refers to the name of
the
variable & Expression is an instance of java.lang.Iterable interface or simply an array.
variable & Expression is an instance of java.lang.Iterable interface or simply an array.
E.g=>
consider the following statement:
int numarray[3]={56,48,79}
for (int k=0;k<=3;k++)
{
If(numarray[k]>50
&& numarray[k]<100])
{
System.out.println(“the
selected value is”+numarray[k]);
}
}
& the above code can
be equivalent to the following code-
int numarray[3]={56,48,79}
for (int k:numarray)
{
If(k>50 &&
k<100)
{
System.out.println(“the
selected value is”+k);
}
}
Jumps
in loop
Jump is mainly used to change the
continuous flow of execution of the program
according to a given predefined condition.
according to a given predefined condition.
·
Jumping out of the loop
Can be accomplished by using “break” statement. But remember friends,
it can only be
used with switch statement & looping statements thats too just to exit from the
immediate single loop in which the programming is currently executing.
used with switch statement & looping statements thats too just to exit from the
immediate single loop in which the programming is currently executing.
·
Skipping a part of the loop
Can be mainly accomplished by using “continue” statement, It mainly tells
the compiler to skip the following
statements & continue with the next iteration.
Labelled loop
In java we
can give a label to any block of statements. A label is simply any valid java
variable
name.
name.
To give a label to a block simply
place it before the block with colon at the end.
E.g=>
loop1: for(……)
{
…………
…………
}
………………
NOTE-
If we want to
jump outside a nested loops or to continue a loop that is outside the current
one, then we simply have to use the labeled break & labeled continue statement respectively.
E.g=>
//Use of continue & break statement
class ContinueBreak
{
public static void main(String args[])
{
Loop1: for (int i=1;i<100;i++)
{
System.out.println(" ");
if(i>=10) break;
for(int j=1;j<100;j++)
{
System.out.println("*");
if(j==i)
continue Loop1;
}
}
System.out.println("termination by break");
}
}
one, then we simply have to use the labeled break & labeled continue statement respectively.
E.g=>
//Use of continue & break statement
class ContinueBreak
{
public static void main(String args[])
{
Loop1: for (int i=1;i<100;i++)
{
System.out.println(" ");
if(i>=10) break;
for(int j=1;j<100;j++)
{
System.out.println("*");
if(j==i)
continue Loop1;
}
}
System.out.println("termination by break");
}
}
No comments:
Post a Comment