Looping In Java
Topics Covered
While Loop
Do – while Loop
For Loop
Enhanced/Modern for loop
Continue statement
Break statement
Use of [Link]
Inner Loop / Nested Loop
for within a while and vice versa
Logical programs using loops
Loops in Java
loops are used in performing repetitive work in programming.
There are 3 types of loops :
while loop
do while loop
for loop
While loop
Syntax
Initialization;
while (condition)
{
statements to be executed;
Increment/ decrement;
}
do-while loop
Syntax
Initialization;
do
{
some code/s;
Increment/ decrement;
}while (condition);
for loop
Syntax
for(initialization ; condition ; increment / decrement)
{
code/s to be executed;
}
Enhanced/Modern for loop
In Java, the for-each loop is used to iterate through elements
of arrays and collections (like ArrayList). It is also known as the
enhanced for loop
The syntax of the Java for-each loop is:
for(datatype item : array)
{
...
}
Continue statement
1. It is sometimes desirable to skip some statements inside the loop.
In such cases, continue statements are used
break Statement
[Link] is used in terminating the loop immediately after it is
encountered.
2. The break statement is used with conditional if statement and in all
three loops such as for, while and do-while
Use of [Link]
[Link] is a void method. It takes an exit code, which it passes on to
the calling script or program.
Exiting with a code of zero means a normal exit:
[Link](0);
We can pass any integer as an argument to the method. A non-zero status
code is considered as an abnormal exit.
Calling the [Link] method terminates the currently running JVM and
exits the program. This method does not return normally.
This means that the subsequent code after the [Link] is effectively
unreachable and yet, the compiler does not know about it.
Use of [Link]
[Link](0);
[Link]("This line is unreachable");
It’s not a good idea to shut down a program with [Link](0).
It gives us the same result of exiting from the main method and also
stops the subsequent lines from executing,
The typical use-case for [Link] is when there is an abnormal
condition and we need to exit the program immediately.
Also, if we have to terminate the program from a place other than the
main method, [Link] is one way of achieving it.
Nesting of for loop
Definition:
Loop statement inside another looping statement. This type of looping is
called nested loop.
Syntax
for(initialization ; condition ; increment/decrement)
{
for(initialization ; condition ; increment/decrement)
{
inner code/s to be executed;
}
Outer code/s to be executed;
}
for within a while and vice versa
Syntax
for(initialization ; condition ; increment/decrement)
{
Initialization;
while (condition)
{
statements to be executed;
Increment/ decrement;
}
Outer code/s to be executed;
}
for within a while and vice versa
Syntax
Initialization;
while (condition)
{
for(initialization ; condition ; increment/decrement)
{
code/s to be executed;
}
statements to be executed;
Increment/ decrement;
}