Pages

Thursday, September 8, 2016

java for loop

at is for loop in java

Explanation

Loop mean in java to repeat some thing for many time,So In java whenever if you want to repeat something you will depenently need a loop, there are three types of basic loops,ie for loop,while and do while loop

for loop

Today we are going to discuss about for loop.

for loop Syntax

for ( initialization ; limit ; incrementation ){

body ;

If you will look to the syntax of foor loop.So its clear that there are 4 things use in a for loop, initialize value, limit value , incrementation and body
Statement 1 = initialization

Statement 2 = limit 

Statement 3 = body 

Statement 4 = incrementation 

syntax logic


Java compiler when execute a for loop so the proccess of this execution is as below



1.java compiler first go to the variable where its initialized like in the above we have int i = 0;
2.then it goes to the second statemet limit part which is in above example <= 5 so it checks whether is this i <= 5 is this in limit? is this statement true? so if its true then it goes to the next part.


3.statement no 3 is the body part .....what ever in the body is it executed once, if our 2nd statement ie (limit part) is true.In above lope as we have printed out "hey" so it will print out"hey" And then it goes to the next part.


4.statement no 4 is the incrementation part..When body executed so java compliler then goes to the incrementation statement, where it increments the value(increments mean to increase a value by ( + ) , decrement mean to decrease a value by ( - )by its given order, As above is i++.So this is mean our value should increment by one,So our will be adding with one so it will get 2..


5 .After incrementation compiler goes back to the second statement limit part and checks whether the value is still in limit or not if it is, so it goes to the body part again and the whole procces will execute again and again , until there come a point where the second statementlimit become false and the i value goes higher than 5 and hence java compiler reject to execute body again and that way for loop finishes.

So the result for this loop would look like this

console

hey
hey
hey
hey
hey

No comments:

Post a Comment