Mastering Iterative Statements in Java
Java, as a versatile and powerful programming language, provides several tools for developers to efficiently handle repetitive tasks. Iterative statements, also known as loops, are fundamental constructs that allow you to execute a block of code repeatedly. In this blog post, we will explore the three primary iterative statements in Java: for
, for each
, while
, and do-while
.
Iterative statements are statements or blocks of statements that are executed repeatedly as long as the given condition is true.
The While Loop: Condition-Driven Execution
The
while
loop continues to execute as long as a specified condition is true.It is often used when the number of iterations is unknown in advance.
The argument should be Boolean type only if you try to provide any other type then we will get compile time error.
Syntax for While loop:
while(condition){
//statement
}
Here's a basic illustration:
int count = 0;
while (count < 3) {
System.out.println("Count: " + count);
count++;
}
In this example, the loop will run until count
is no longer less than 3. It's crucial to ensure that the loop condition will eventually become false to avoid an infinite loop.
Points to remember -
Curtly braces are optional and without curly braces we can take only one statement under
while
which should not be declarative statement.//Valid while(condition) System.out.println("Hello"); //Valid while(condition) //Invalid while(condition) int i = 10; //Valid while(condition){ int i = 10; }
**If we have a statement both inside and outside our block but argument will be true inside while that is infinite loop. It will return error.
while(true){ System.out.println("Hello"); // Infinite loop } System.out.println("World"); // Never get chance to execute
if we have a statement both inside outside of while loop and the past argument is false then the wild bloc will be useless and raise error.
while(false){ System.out.println("Hello"); // Complie time error unreachable statement } System.out.println("World");
At compile time the compiler will check whether the argument is conditional or not and he will never check the values of A and B the values will be checked at runtime if constants are not fixed it will evaluate.
int a = 10, b = 20; while(a < b){ System.out.println("Hello"); // Infinite loop } System.out.println("World"); // Never get chance to execute
Here if the past variable values are fixed and cannot be changed then it will be the same as above******.
every time final variable will be replaced by the value at compile time only.
If every argument is a final variable (compile time constant) then that operation should be performed at compile time only.
The Do-While Loop: Guaranteeing at Least One Execution
The do-while
loop is similar to the while
loop, but it guarantees at least one execution of the loop body. The condition is checked after the loop body, ensuring that the code inside is executed before the condition is evaluated:
int attempts = 0;
do {
System.out.println("Attempt: " + attempts);
attempts++;
} while (attempts < 3);
This loop will execute the code block and then check if attempts
is less than 3. If true, it continues; otherwise, it exits.
Points to remember -
Curtly braces are optional and without curly braces we can take only one statement under
while
which should not be declarative statement.//Valid do System.out.println("Hello"); while(true); //Valid do; while; //Invalid do int i = 10; while(true); //Invalid do while(true); //Valid do{ int i = 10; }while(true);
Compiler at compilation will check if the loop goes infinite and there are other statements as well it will return compile time error. It will be same when we pass the expression with conditional operator and the values are fixed they will behave the same.
//Unreachable statement do System.out.println("Hello"); while(true); System.out.println("World"); //Unreachable statement final int a = 10, b = 20; do{ System.out.println("Hello"); }while(a < b) System.out.println("World"); //Infinie loop final int a = 10, b = 20; do{ System.out.println("Hello"); }while(a > b) System.out.println("World");
If the
do while
statement loop goes forfalse
then at once the statement will be printed and then it will check the Boolean as false and it will come out of the loop and print this next statement.do{ System.out.println("Hello"); }while(false) System.out.println("World");
If we are passing expression with conditional operator and the values are not fixed then the snippet of code will be valid. Add compile time JVM will never compare their values because it's not fixed
int a = 10, b = 20; do{ System.out.println("Hello"); }while(a < b) System.out.println("World");
The For Loop: Streamlining Repetition
The
for
loop is a concise and expressive way to iterate over a sequence of values.Most commonly used lupin Java.
If we know the number of Federators in advance then for rupees the best choice.
Its syntax consists of three parts: initialization, condition, and iteration expression. Let's break it down with a simple example:
for (int i = 0; i < 5; i++) { System.out.println("Iteration: " + i); }
In this example, int i = 0
initializes the loop variable, i < 5
is the loop condition, and i++
increments the loop variable after each iteration. The loop will execute as long as the condition is true.
Execution Cycle
It would start from initialization and then it'll check for the condition if the condition is true it would get inside the for loop. After first iteration it will never go for initialization so it will Iterate or increment as per our iteration expression and check the condition.
Curly braces are optional and without curly braces we can take single statement which should not be declarative statement.
//Valid
for (int i = 0; i < 5; i++)
System.out.println("Iteration: " + i);
//Valid
for (int i = 0; i < 5; i++);
//Invalid
for (int i = 0; i < 5; i++)
int i = 10;
Initialization section
This part will be executed only once in loop lifecycle.
Here we can declare and initialise local variable of
for
loop.We can declare any number of variable but should be of the same type.
By mistake, if we're trying to declare different data type compiler will return compile-time error.
for(int i = 0; j=0;) for(int i = 0; string s="Vikas";) for(int i = 0; int j=0;)
In this section we can take any Java statement including print.
int i = 0 for (System.out.println("Valid loop"); i < 5; i++) { System.out.println("Iteration: " + i); } //Output Valid loop Iteration 0 Iteration 1 Iteration 2 Iteration 3 Iteration 4
Conditional check
We can take any valid Java expression but should be of the boolean type.
This part is optional and if we are not taking anything that compiler will always place
true
.for (int i = 0;; i++) { //Valid System.out.println("Iteration: " + i); }
Increment/decrement section
It can be any valid Java statement including print statement.
for (int i = 0;i < 3; System.out.println("Valid loop")) { //Valid System.out.println("Iteration: " + i); } //Output will be infinite Iteration: 0 Valid loop
All three sections of for loop are independent of each other an optional.
for (;;) { //Valid
System.out.println("Hi"); //Infinite loop
}
Examples
Example 1 - In Java, when the loop condition is false
/true
from the beginning, the loop body will never be executed, and thus, any statements following the loop will be unreachable.
for (int i = 0; true; i++) {
System.out.println("Hi");
}
System.out.println("Hello"); //Unreachable statement
Example 2 - In this case, the loop condition is false, and the control goes directly to the statement after the loop. Therefore, the System.out.println("Hello");
statement is reachable, and there is no issue with unreachable code.
int a = 10, b = 20;
for (int i = 0; a > b; i++) {
System.out.println("Hi");
}
System.out.println("Hello");
for (int i = 0; a < b; i++) {
System.out.println("foo");
}
System.out.println("foofoo");
Example 3 - In this case, the compiler would be able to determine at compile-time that the loop condition is always false, given that a
and b
are constants with fixed values. Consequently, it might treat the entire loop (including its body) as unreachable, and you may get a compilation error for unreachable code.
final int a = 10, b = 20;
for (int i = 0; a > b; i++) {
System.out.println("Hi");
}
System.out.println("Hello");
For each loop: Enhanced for loop
Also known as enhanced for loop introducing version 1.5.
This is best for array and collection.
specially designed to retrieve elements of arrays and collection.
Syntax:
for (type variable: array)) {
//statement
}
Case 1: To find element in 1D array
int[] x = {10,20,30,40,50};
//For loop
for (int i = 0; i < x.length; i++) {
System.out.println(x[i]);
}
//For each
for (int y: x) {
System.out.println(y);
}
Case 2: To find element in 2D array
int[] x = {{10,20,30,40,50}, {60,70,80,90,100}};
//For loop
for (int i = 0; i < x.length; i++) {
for (int j = 0; j < x[i].length; j++) {
System.out.println(x[i][j]);
}
}
//For each
for (int[] y1: x) {
for (int y2: y1) {
System.out.println(y2);
}
}
Case 3: To find element in 3D array
//For loop
//For each
for (int[][] y1: x) {
for (int y2[]: y1) {
for (int y3: y2) {
System.out.println(y3);
}
}
}
For each
loop is best choice to retrieve elements of arrays and collections but its limitation is applicable only for arrays and collection and it's not a general purpose loop.
for (int i = 0; i < 5; i++) { //for each is not possible
System.out.println("Iteration: " + i);
}
By using normal for loop we can print array elements either in original order or reverse order.
But by using forge loop we can print array element only in original order not in reverse order.
Iterable Interface
for (type itemX: target)) {
//statement
}
the target element in fall each loop should be iterable object.
An object is set to beat rebel if and only if corresponding class implement
java.lang.iterable
interface.It is introduced in version 1.5 and it contains only one method that is iterator.
public iterator interator()
All array related classes and collection implemented classes already implemented iterable interface.
Being a programmer we are not required to do anything.
Iterable vs Iterator
Iterator(I) | Iterable(I) |
It is related to collection | It is related to for each loop |
We can use to retrieve element of collection one by one | The target element in for each loop should be iterable |
Present in java.util.package | Present in java.lang.package |
It contains three method - hasNext() , next() , remove() | It continually one method - interator() |
Choosing the Right Loop for the Job
When working with loops, it's essential to choose the right one for the specific task. for
loops are ideal for iterating a known number of times, while while
and do-while
loops are suitable for situations where the number of iterations is uncertain.
Mastering iterative statements is a key step towards becoming proficient in Java programming. By understanding the nuances of each loop type, you gain the flexibility to tackle a variety of programming challenges efficiently.
Happy coding!
Subscribe to my newsletter
Read articles from Xander Billa directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Xander Billa
Xander Billa
Myself Vikas Singh from Varanasi, Uttar Pradesh. Learning and exploring technical domains at Acharya Institute, Bangalore (IN) from the last two years. The main goal is to learn as much domains, tool