In this article, we will describe using statements with conditions and touch upon the types of loops in Java:
While
For
For Each
Do-While
The guide will be useful for beginner programmers who want to learn how the syntax is organized.
Let's start with an analogy. Our life consists entirely of a sequence of actions. They change depending on external and internal conditions. For example, the action "I will go to the gym today" contains conditions.
One person will not go to the gym if they have a sore throat, while the other will not skip a workout because of a slight cold or bad mood.
The same is true for apps. The code contains conditions. They customize the operation of the software, depending on the developer's idea.
Loop iteration in Java is a single execution of the loop body until the loop exit conditions are met. Such algorithms create the functionality of the program. They describe a pattern of repeated actions and contain information about the number of repetitions.
Let's look at a simple problem: writing the numbers from 1 to 150 by regular enumeration:
public class Main {
public static void main(String[] args) {
System.out.println(1);
System.out.println(2);
…(repetitions)
System.out.println(150);
}
}
We got the required result, the range of numbers. However, this approach is inconvenient as we have to manually describe each repeated action, although each repetition is connected to the previous one (except for the first one).
Describing an algorithm where we put two lines and get a similar result is easier. Let's complicate the task: numbers should be printed through a space:
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 150; i++) {
System.out.print(i + " ");
}
}
}
We printed out the numbers and separated them with spaces. Initially, we would describe each print statement. Tip: you can remove the curly braces of the loop body if the loop contains a single line.
How to create a Java loop:
Create (initialize) a variable. Define i
and assign it to 1, since we start counting from it.
Add an exit condition. We have indicated under what conditions the number is output after the code is run. The <=
symbol means "less than or equal to". According to the condition, we need to add all digits in the range, including 150. We can apply "less than" + 1, i.e. 151.
Increment condition. What happens when the number is less than or equal to 15. We will increment the number by 1 at each iteration of the loop. The algorithm is repeated as long as the value of the condition check is equal to the Boolean expression "True". When "False" appears at the next iteration, the loop body is not executed, the loop ends, and code execution moves on to the next part of the program.
This is how For loops work in Java. Let's analyze the peculiarities of different types of loops in Java.
Loop |
Purpose |
While |
Repeating the fragment an indefinite number of times, including 0. |
For |
Repetition of the code in a given number of iterations, including 0 |
For Each |
Array elements enumeration |
Do While |
Repeating a fragment with checking after iteration at least once |
The while
loop in Java is an operator with an unknown number of iterations. It executes a given pattern until the condition of the expression is false.
Another life analogy: studying at a university continues until a student goes through the whole course of study and passes all the intermediate and final exams. The algorithm of actions includes: attending lectures, preparing for the control stages of knowledge testing.
while (Conditions) {
// Algorithm body
}
The condition inside the while
statement takes a Boolean value. It is only true or false. The algorithm is triggered as long as the expression takes True.
In all other cases, the code fragment inside the loop body is not executed.
Let's apply while
and see how the loop body stops executing after five iterations.
Example of a Java while
loop with a parameter:
public class Main {
public static void main(String[] args) {
int count = 0;
while (count < 5) {
System.out.println("Number: " + count);
count++;
}
System.out.println("Completed. The check ignores the fragment and sequentially executes the rest of the program");
}
}
Java follows all the principles of object-oriented methodology and is based strictly on them. To successfully run the code, we declare the Main
class and the method of the same name after public static void main(String[] args)
. Before while, we initialize the variable necessary for the loop condition.
As long as the number is less than 5, the string and the current value of the count
variable are printed. Then count
is incremented by 1 (incremented). Result:
Number: 0
Number: 1
Number: 2
Number: 3
Number: 4
Completed. The check ignores the fragment and sequentially executes the rest of the program
While
is best used when the number of iterations is initially unknown. The situation is different with the for
loop in Java: it is used when the number of occurrences is known initially, for multiple repetitions of a code fragment.
With for
, you can create a variable and specify conditions at once. It is usually needed when there is no user input. But let's consider one interesting problem:
import java.math.BigInteger;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number to calculate its factorial: ");
int num = scanner.nextInt();
BigInteger factorial = BigInteger.ONE;
for (int i = 1; i <= num; i++) {
factorial = factorial.multiply(BigInteger.valueOf(i));
}
System.out.println("factorial " + num + " equals to " + factorial);
}
}
We find out the number of repetitions even before the loop. The number depends on a fixed user-defined number of multiplications from 0 to n (where n is any input using the formula 1*2*3..*n) via a math function.
BigInteger.valueOf(i)
creates a new BigInteger
object that represents i. factorial.multiply(BigInteger.valueOf(i))
multiplies the current value of factorial
(which is also a BigInteger
object) by the BigInteger
object. Assigning factorial = ...
sets the value of factorial
to a new BigInteger
object representing the product.
At each iteration of the loop, the current value of factorial
is multiplied by i
, and the result is stored back into factorial
. By the end of the loop, we output the factorial of the number.
Let's show the difference from While
:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int numberToGuess = 498;
int guess = 0;
while (guess != numberToGuess) {
System.out.print("Guess the number (from 1 to 1000): ");
guess = scanner.nextInt();
if (guess < numberToGuess) {
System.out.println("Lesser");
} else if (guess > numberToGuess) {
System.out.println("Greater");
}
}
System.out.println("You have won, this is the right answer: " + numberToGuess + "!");
}
}
Here, we apply while
because the repetitions depend entirely on how many times the user enters the value. But we must stop when he types 498. Only then we can exit the loop.
The for each
loop in Java is a variant of the for
loop adapted for convenient iteration over iterated objects (arrays and collections). It appeared in Java 5.0 in 2004 and simplifies code writing.
How the for
loop works in Java:
public class Main {
public static void main(String[] args) {
int[] numbers = {145, 342, 2343, 423, 23, 96, 11, 20, 590, 1457};
// Output only even numbers
for (int number : numbers) {
if (number % 3 == 0) {
System.out.print(number + " ");
}
}
}
}
Result:
342 2343 423 96
Apply the for each
loop to selectively output only certain elements from the array based on certain conditions.
We output numbers divisible by three. Here you can see how to use a for each
loop in Java to perform operations on collections. It can be used to loop through the elements of an array.
The main difference between while
and do-while
loops in Java is that do-while
executes the first iteration before the loop condition is checked. While may not execute a part of the program at all if the result of the check takes a false value.
Writing a loop in Java with do-while
looks like this:
do {
// Code fragment
} while (condition);
The condition is checked at the end of the iteration.
Here is an example illustrating the difference between do-while
and while
:
public class Main {
public static void main(String[] args) {
// do-while example
int count1 = 0;
do {
System.out.println(count1);
count1++;
} while (count1 < 5);
// while example
int count2 = 0;
while (count2 < 5) {
System.out.println(count2);
count2++;
}
}
}
We have applied do-while
. The algorithm will always execute the first occurrence and then check the condition (but only at the end of the iteration).
The code inside the do
statement is executed at least once. Even if we started with the number 5. The loop will end when the user executes our query. Do-while
literally means "Perform this action and later check if the given rule is applied".
In the second part of the example, nothing will happen if we assign count2
to 5. The code inside the while
statement is executed strictly when the condition we have written into the algorithm is met.
In general, do-while
is needed when executing a fragment at least once. While
is needed when it is better to apply a code block only when the boolean expression is "True".
Special constructs can be used to interfere with the operation of a loop. For example, you can interrupt them, return a value to a function, or exclude an undesired result.
Operator |
Used for |
What it does |
Break |
Interrupting loop execution |
Exits the code fragment. Continues from the statement that follows it |
Continue |
Skipping the specified iteration in the loop |
Ignores the entry and starts the next one |
Return |
Returning a function value |
Exits the entire function and returns the specified data within the statement, if specified by the developer |
This is the skip statement that ends the loop or switch. It terminates the iteration prematurely if the break
conditions are met. The result of calculations from the previous occurrence is stored in memory.
Example in Java with a loop:
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break;
}
System.out.println(i);
}
}
}
The code snippet uses a loop from 1 to 10. At each iteration, we check if the number is equal to 5.
If so, then the loop ends with a break statement, eliminating the remaining 5 iterations. Therefore, only numbers from 1 to 4 are output.
The final value is 4, the last result is ignored by the compiler. The principle works in all types of loops in Java. In practice, Break is used when you need to exclude a possible result or occurrence. It is also suitable for improving productivity.
This operator does not interrupt the loop, but selectively eliminates possible iterations. When the statement runs, the iteration ends, and the program begins rechecking the condition. The result of previous calculations is stored in memory.
Here is the implementation of the project using continue
:
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Map<String, Double> assortment = new HashMap<>();
assortment.put("Apples", 9.5);
assortment.put("Bananas", 15.5);
assortment.put("Oranges", 18.0);
assortment.put("Grapes", 40.0);
assortment.put("Pineapples", 89.0);
System.out.println("Welcome to our shop! Here’s our products:");
System.out.println(assortment);
double totalAmount = 0.0;
boolean moreItems = true;
while (moreItems) {
System.out.println("Enter the product name to buy (or 'exit'):");
String itemName = input.nextLine();
if (itemName.equals("exit")) {
moreItems = false;
continue;
}
if (!assortment.containsKey(itemName)) {
System.out.println("Sorry, we do not have this product.");
continue;
}
System.out.println("Enter the number of items, " + itemName + " you want to buy:");
int quantity = input.nextInt();
input.nextLine(); // clean the buffer
double itemPrice = assortment.get(itemName);
double itemTotal = itemPrice * quantity;
System.out.println("You added " + quantity + " " + itemName + " to basket. Price: " + itemTotal);
totalAmount += itemTotal;
}
System.out.println("Thanks for shopping with us! Your total: " + totalAmount);
}
}
This is a simplified Java program with a loop that is an online store. You can select a product from a certain range and calculate the total cost of the order.
At the beginning of the program, a HashMap
is created to store the items available in the store and their corresponding prices. The program then displays the assortment for the user.
The program then goes into a loop. The user is prompted to enter the name of the product he wants to buy. If the user enters exit
, the algorithm ends, and the program ends.
When entering the name of a product that is not in stock, we notify the user that the product is not available and continue processing.
If the customer enters the name of an available product, the program prompts you to enter the number of items he wants to buy. The app then calculates the cost of the order and adds the price.
At the end, the program calculates the cost of the order and exits. The application demonstrates continue
for implementing a simplified commercial project.
Return
is used to terminate the method and print the result of the calculation. It is also used in loops to exit and return a value.
The return
statement is written to exit a function and return a value to the caller. This is useful when you want to perform calculations or iterations until a certain condition occurs and return a result based on it.
Implementation of return
:
public class Main {
public static void main(String[] args) {
int[] arr = {17, 34, 45, 1, 8};
int num = 45;
int index = findIndex(arr, num);
System.out.println("Found " + num + " in set: " + index);
}
public static int findIndex(int[] arr, int num) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == num) {
return i; // Returning the result of calculations and exiting the loop
}
}
return -1; // Returning -1, if no required number
}
}
When iterating, the algorithm will stop and immediately return the index if it finds the right number. No additional code will be executed after return.
An infinite loop continues to execute indefinitely, its exit condition does not evaluate to False in at least one case, or its exit condition is undefined. The algorithm will run forever or until interrupted by an external event.
Here's an example:
while (true) {
// any code except break and return
}
Here the result of the condition value is always True, so the loop runs without stopping. To stop the loop, you must change the condition to False.
In most cases, an infinite loop in Java is a logical mistake on the part of the developer. If done incorrectly, it can cause the program to become unresponsive and crash.
However, sometimes an infinite loop is necessary. For example, in server processes, operating systems, or real-time applications. In these cases, it is usually combined with optimization. This is necessary to ensure that the program remains operational and does not consume a lot of system resources.
They mean using one or more loops inside another. They are typically used to work with two-dimensional arrays.
Let's draw a pattern in the shape of the letter X. You need to use a two-loop fragment in Java to include possible combinations of dashes and asterisks.
Implementation
public class Main {
public static void main(String[] args) {
int size = 7;
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if (i == j || i == size - j - 1) {
System.out.print("*");
} else {
System.out.print("-");
}
}
System.out.println();
}
}
}
Create a square pattern with alternating rows of stars and dashes, with the stars forming an "X" shape through the middle of the square. The square size is set to 7 which is the number of rows.
Result:
*-----*
-*---*-
--*-*--
---*---
--*-*--
-*---*-
*-----*
"X" will always be printed, regardless of the number of lines, thanks to the nested loop check. The if
statement checks whether the current position of the loop is on the main diagonal (where i == j
) or on the opposite diagonal (where i == size - j - 1
). When one of the conditions is true, a star is printed at the position. If false, dash.
In this guide, we have described Java loops, what they are and how to use them. With loops, developers can simplify their code and create efficient applications.