Loop in JAVA

 LOOP CONTROL STATEMENT

IF-ELSE STATEMENT 

It is used to execute two statements to a single condition.

The syntax of an if-else statement in c looks like that of c++ and javascript, java has a similar syntax too. 

 if (condition to be checked){
   
    statement if condition true;

      }

else{

       statement if condition false;
           }




SWITCH OPERATOR 


The switch statement is a multi-way branch statement, it provides an easy way to dispatch execution to different parts of code based on the value of the expression.

    The switch expression is evaluated once. 


The value of the expression is compared with the value of the expression is compared with the value of each case, if there is a match, the associated block of code is executed 

The break and default keywords are optional.


switch (0)

{

case 1 :

------
------
------
break ;



case 2 :
------
------
------
break ;

 

case 3 :
------
------
------
break ;

 default :
---
----
----

}

 

There are three types of loop 


1 . FOR LOOP 

2.  WHILE LOOP

3. DO WHILE LOOP


FOR LOOP 

A for loop is usually used to execute a piece of code for a specific number of time 


WHILE LOOP 

If the number becomes false, the while loop keeps getting executed, such a loop is known as while loop 


Do while loop 

this loop is similar to while loop except for the fact that is guaranteed to execute at least once 


NOW THAT TIME WE USE ADVANCED OR ENHANCED FOR LOOP 

for-each loop


The for-each loop introduced in JAVA 5, it is mainly used to traverse array or collection element, the advantage for each loop is that it eliminates the possibility of bugs and makes the code more readable.

Advantage of for each loop :


It makes the code more readable 

It eliminates the possibility of programming error 

  Syntax of for each loop 


for (data type variable :array | collection 

{

}


   class for each loop 

            {
public static void main (string args[])

{

int a[] = { 56 , 78 , 23 , 90 , 41 };


// new method 
for (int z:a)
{

system .out.println(z);

}
   }
      }
                   }


LABELLED LOOP 


According to nested loop, if we put break statement in inner loop, compiler will jump out from inner loop and continue the outer loop again, what if we need to jump out from the outer loop using break statement given inside inner loop? the answer is we should define label along with colon (i) sign before loop.



BREAK STATEMENT 



    the break statement is used to exit the loop irrespective of whether the condition is true or false.
        whenever a break is encountered inside the loop, the control is sent outside the loop.


                    

continue statement 


the continue statement is used to immediately move to the next iteration of the loop, the control  is taken  the next iteration thus skipping everything below continue inside the loop for that iteration
               



Post a Comment

0 Comments