Loops in Java - Indiana University

Download Report

Transcript Loops in Java - Indiana University

Loops in Java
What are loops?
Loops are used for repeated execution of a block.
There are following types of loops in Java:

while Loop

do…while loop

for loop
While Loop
Syntax:
while (Boolean Expression)
{
//your code
}
e.g. Example_while.java
Do...while Loop
Syntax:
do
{
//your code
}while(Boolean_expression);
e.g. Example_dowhile.java
For Loop
Syntax:
for(initialization; Boolean_expression; update)
{
//Statements
}
Initialization: The first step in execution for initializing your loop variable.
Boolean_expression: Condition for evaluation. If evaluated to true, loop executes, else
goes to the next statement.
Update: After the body of the for loop executes, the flow of control jumps back up to the
update statement. This statement allows you to update any loop control variables.
The code block is re-executed till the time the Boolean expression evaluates to true.
Example: Example_for.java
Enhanced for loop in Java:
Typically used for arrays.
Syntax:
for(declaration : expression)
{
//your code
}
Example: Example_efor.java
Break & Continue
Break: for breaking out of the loop immediately and execute what's
after the block.
Continue: it causes the flow of control to jump to the next iteration.
Syntax:
break; // for break
continue; //for continue
Example: Example_break_continue.java
Methods
What is it all about?
A Java method is a collection of statements that are grouped together
to perform an operation.
Syntax:
modifier returnValueType methodName(list of parameters) {
// Method body;
}
Example: Example_method.java
Constructors

A constructor is used for initializing an object.

It has the same name as the class.

It looks similar to a method.

It does not have a return type.
Example: Example_constructor.java
Example_cons_invkd.java