Flow control part 2 Iterative Method

Iterative Method

Iterative statement

  • while()
  • do-while()
  • for()
  • for-each()  1.5v

while()

If we don't know the number of iterations in advance then we should go for a while loop.

Example-:

while(rs.next()){
}

while(e.hasMoreElements()){
}

while(itr.hasNext()){
}

the argument should be the boolean type if we are trying to provide any other type then we will get compile time error.

syntax-:

while(b){
    statements;
}

this syntax is applicable to c and C++ but this terminology is not allowed in Java.

while(1){
    System.out.print("hello");
}
// compile time error-:
// incompatible type error
// found int type
// required boolean.

curly-braces are optional and without curly braces, we can take only one statement under while which should not be a declarative statement.

Example-:

while(true)
    statement; // valid

while(true); // valid

while(true)
    int x=10; // invalid

while(true){
    int x=10;
} // valid
while(true){
    System.out.print("hello");
}
System.out.print("hi");
// compile time error: unreachable statement

while(false){
    System.out.print("hello");
}
System.out.print("hi");
// compile time error: unreachable statement

int a=10,b=20;
while(a<b){
    System.out.print("hello");
}
System.out.print("hi");
// output "hello" infinite time

int a=10,b=20;
while(a>b){
    System.out.print("Hello");
}
System.out.print("Hi");
// output-"Hi"

final int a=10,b=20;
while(a<b){
    System.out.print("Hello");
}
System.out.print("Hi");
// compile time error: unreachable statement

final int a=10,b=20;
while(a>b){
    System.out.print("Hello");
}
System.out.print("Hi");
// compile time error: unreachable statement

Note-: Every final variable will be replaced by a value at compile time only.

Note -: If every argument is the final variable (compile time constant) then that operation should be performed at compile time only.

do-while()

if we want executed loop body at least once then we should go for do while.

syntax-:

do{
    body;
}while(condition);

curly braces are optional and without curly braces, we can take only one statement b/w do and while which should not be a declarative statement.

do{
    statement;
}while(true); // valid

do;
    while(true); // valid

do
    int x=10;
while(true); // NotValid

do{
    int x=10;
}while(true); // valid

do
    while(true); // NotValid

Special Case

do while(true)
    System.out.print("hello");
while(false);

// we can write this:
do
    while(true)
        System.out.print("Hello");
while(false); // is valid

1 Comments

Anonymous said…
this one good