Welcome to my next tutorial. Today i am gonna teach you the Do-While loop in java. This is another variation of loops in java. But unlike while loop this do-while loop will execute at least once, no matter the condition is false before reaching to the loop. Because it do the work before and check the condition after doing work. But in while loop the condition is checked first and then decision is taken to execute the loop or not. Lets see a code example.
public class WhileLoopTest {
public static void main(String[] Args)
{
int counter = 0;
do
{
System.out.println("Value of the counter is " + counter);
counter++;
}while(counter < 5);
}
}
So you can see the above code. Its almost similar to previous two loops examples. But here we have do-while loop. As you can see first we are asking the program to do first and then we are checking the condition. So if the condition is false the code have been run once. And don't forget to put a semicolon after the condition(). Most of the guys do this syntax mistake.
Here is the output of the code.
Value of the counter is 0
Value of the counter is 1
Value of the counter is 2
Value of the counter is 3
Value of the counter is 4
And this is the end of our class. Be ready for the next class. Bye
No comments:
Post a Comment