Core JAVA || Loops
2 min readJul 30, 2023
There are three types of Loops in JAVA
- For Loop
- While Loop
- Do While Loop
There are two keywords to control the flow in Loop
- Continue
- Break
Which loop?
For Loop:- If you know How many times loop runs?
While/ Do While: -Until Something happen (specific condition met), you don’t know how many times loop will execute, then while/ do while loop is used
- While Loop: If condition is not met then it will not execute
- Do While Loop: Even if condition is not met, you want to execute the code at least once.
For Loop
The for
loop is the most commonly used loop in Java and is suitable when you know the number of iterations in advance. It consists of three parts: initialization, condition, and update.
Here’s how the for
loop works:
- The initialization is executed before the loop starts and is usually used to set a loop control variable.
- The condition is evaluated before each iteration. If it is true, the loop body is executed; otherwise, the loop terminates.
- The update statement is executed after each iteration and is used to modify the loop control variable.
public boolean isPrime(int number){
boolean isPrime = true;
// gaurd condition
if(number < 2) return false;
for(int i = 2; i< number; i++){
if (number % i == 0) {
isPrime = false;
break;
}
}
return isPrime;
}
While Loop & Do While
When While Loop?
- You want to execute the loop body zero or more times based on a condition.
- The loop condition might be false from the beginning, and you want to avoid executing the loop body in such cases.
int count = 1;
while (count <= 5) {
System.out.println("while loop: " + count);
count++;
}
When Do While Loop?
- You want to ensure that the loop body executes at least once, irrespective of the condition.
- You have a task that needs to be performed first, and then you check whether to repeat it.
Scanner scanner = new Scanner(System.in);
int number;
do {
System.out.print("Enter a positive number: ");
number = scanner.nextInt();
} while (number <= 0);
System.out.println("You entered a valid positive number: " + number);
scanner.close();
Break
- It is used to break the loop execution if specified condition is met
- It will stop executing the loop further if the condition is met
for (int i = 0; i < 10; i++) {
if (i == 4) {
break;
}
System.out.println(i);
}
Continue
- It is used to continue the loop execution if specified condition is met
- It will execute the code till the condition of continue, but if the condition is met then it will skip the loop execution further for the current iterator.
public static void main( String[] args ){
printOddNumbers(10);
}
public static void printOddNumbers(int number){
for(int i=0; i<= number; i++){
if(i%2 == 0)
continue;
System.out.print(i+ " ");
}
}