Do While loop in Java

Do – While loop is same as While loop except in this case loop is confirmed to execute once(Means in any case statements in Do-While block will execute atleast once).

Syntax of Do-While Loop

 


do {
     // Do Something Here
} while (expression);
	

As you can see in this loop expression is evaluated in the end. So for the first time block will executed irrespective of the value of expression.

Sample code

 


/*
 * Here we will learn about the Do-While loop in Java.
 */
class JBT_DoWhileLoop {

	public static void main(String[] args) {
		/*
		 * Create do-while loop to Print the string until var is 4
		 */
		int i=0;
		do {
			System.out.println("Inside Do-While Loop");
			System.out.println("Value of expression is :"+(i<5));
			i++;
		} while (i<5);

		System.out.println("Outside of Do-While Loop");
		System.out.println("Value of expression is :"+(i<5));
	}
}

	

Output of the above program would be


Inside Do-While Loop
Value of expression is :true
Inside Do-While Loop
Value of expression is :true
Inside Do-While Loop
Value of expression is :true
Inside Do-While Loop
Value of expression is :true
Inside Do-While Loop
Value of expression is :true
Outside of Do-While Loop
Value of expression is :false

	
By | 2013-03-18T16:16:52+00:00 March 18th, 2013|Learn By Example|3 Comments

About the Author:

3 Comments

  1. rewati August 8, 2013 at 5:31 pm - Reply

    why is this page not mentioned under the list of core java topics? May i have the whole list at one place please. thankyou

    • admin August 9, 2013 at 4:54 am - Reply

      Hi Rewati,

      Thanks for your comment. Not all articles are listed under Core Java Section(My Mistake). Some might be missing.

      Soon i will update site to have next and previous button for better navigation. And also add missing topic in Core Java Section. If you are looking for some topic please search it.

      If you are searching for a particular article which is not present in site do let me know so that i can add the same.

      Thanks

  2. orkun October 1, 2014 at 5:23 pm - Reply

    Hi,

    Thanks for putting so much effor in this site. It is very useful.

    But could you please, as rewati mentioned, provide a complete site map? It is hard to follow through when some articles are missing, or the order isn’t clear.

    The previous and back buttons you have placed seem to be directing us to the wrong page, not really related to the current topic.

Leave A Comment