top of page
realcode4you

Loops In Java (While, Do While and For) : Java Loops Programming and Optimization Help

What is Loops In Java?: Loops in Java is a feature used to execute a particular part of the program repeatedly if a given condition evaluates to be true.



For Loop:

  • A counted loop

  • Great choice if you know exactly how many loops to perform, or if that number can be supplied by the user


Do-While Loop:

  • The loop always runs at least once

  • Great choice when asking a question, the answer to which will determine if you loop again


While Loop:

  • A good multi-use loop for dealing with:

o User input

o Numbers

o Strings



Let's Understand In Brief...

1. Do-While Loops

Do-While loops work almost exactly like While loops. Code inside a do-while loop will run once first, then check to see if the condition is met.



Example 1:

Compare the results of this program using a While Loop vs a Do-While Loop:


While Loop

x = 1;
while(x > 5)
{
 System.out.println("Looping");
 x = x + 1;
}
System.out.println("Done");

Do While Loop

x = 1;
do 
{
 System.out.println("Looping");
 x = x + 1;
} while ( x > 5 );
System.out.println("Done");

For Loops

For Loops allow you to easily write code that loops a specific number of times.


Example 2:

Compare the while and For Loops using below example


While Loop

x = 1;
System.out.println("Start");
while (x < 4) 
{
 System.out.println(x);
 x = x + 1;
}
System.out.println("End");

For Loop

System.out.println("Start");
for (x = 1; x < 4; x = x + 1) 
{
 System.out.println(x);
}
System.out.println("End");


 

Important Facts: Need to know when Learn about Loops


Infinite Loops #1

One easy mistake to make when working with loops is accidently creating an infinite loop. An infinite, or endless, loop is a loop that never exits and loops forever, or at least until the power goes out. There are two main types of infinite loops:




Always have an exit condition defined, either within the loop itself or with a break statement..


Break Statements #2

You can use a break to exit a loop early.

Example:

x = 1;
while (x < 5) 
{
 if (x == 3) 
 {
 break;
 }
 System.out.println("Looping");
 x = x + 1;
}
System.out.println("Done");


Java Assignment Help Services In Which You Can Get Help:

  • Java Basic to Advance Programming Help

  • Java Web Application Help

  • Java Mobile Application Help

  • Java AI Gamming Project Help

  • JavaFX Project and Homework help

  • Java Spring Boot Project Help

  • Java Servlet Project Help


For More details You can-

Contact us: +91 82 67 81 38 69

Comments


bottom of page