- For Loop in Java
- Basics of For Loop in Java
- The flow of a program
- Sequential:
- Iterative:
- For Loop
- Description:
- Syntax:
- Flowchart:
- Advanced looping technique
- Syntax:
- Examples:
- Print numbers in a single line:
- Count backward from a given number:
- Iterate through a collection:
- Java For Loop
- 1. Overview
- 2. Simple for Loop
- 2.1. Labeled for Loops
- 3. Enhanced for Loop
- 3.1. Iterable.forEach()
- 4. Conclusion
For Loop in Java
This tutorial will guide you on how to use for loop in Java programs, perform repetitive tasks, and iterate through the elements of a collection or array. It is a core Java programming construct used to perform repetitive tasks.
Basics of For Loop in Java
The tutorial has the following sections to help you learn quickly.
The flow of a program
The workflow of an application represents how the compiler executes the lines of your code. There are three basic types of flow in a Java program:
Sequential:
Sequential flow is the normal flow of execution. It means the very first instruction that will execute is line 1, then 2, and so on until the control reaches the end of your code.
Conditional flow occurs when the execution reaches a specific part in your code which has multiple branches. Here, the result of the condition decides the course of the program.
Java supports two conditional statements: if-else and Switch-Case.
Iterative:
Iterative flow comes in the light when the control enters in a block which repeats itself for specified no. of cycles.
Must Read – Variable in Java
For Loop
Description:
For loop provides the most straightforward way to create an iterative block. It has a three instruction template where first is to initialize the loop counter, second is the condition to break, and third increments the counter.
Syntax:
It has a cleaner and informative structure:
for (init counter; check condition ; move counter)
As we said that there are three statements in the for-loop. The first instruction tells when to start the loop; you initialize a variable here with some value.
In the next statement, you can move the counter both ways, i.e., increment or decrement its value.
Flowchart:
Check below is the for-loop flow diagram.
Also, Read – Data types in Java
Advanced looping technique
Java has one more style of “for” loop first included in Java 5. It lays down an easy way to traverse through the items of a collection or array. You should use it only for sequentially iterating an array without using indexes.
In this type, the object/variable doesn’t change, i.e., the array doesn’t change, so you can also call it as a read-only loop.
Syntax:
for (T item:Collection obj/array)
Examples:
Print numbers in a single line:
Instead of writing the print statement for n times, we made the for loop resolve it. Here ‘iter’ is the loop control variable.
Count backward from a given number:
public class MyClass < public static void main(String args[]) < int N = 5; for ( int iter = N; iter >0; iter-- ) < System.out.print(iter + " "); >> >
You can see that the “for” loop is letting us manipulate the test condition and update statement to yield different outputs.
Iterate through a collection:
public class MyClass < public static void main(String args[]) < String array[] = ; // Advanced for loop for (String item:array) < System.out.print(item + " "); >System.out.println(" "); // Standard for loop for (int iter = 0; iter < array.length; iter++) < System.out.print(array[iter] + " "); >> >
After execution, the following values will print:
Python Java CSharp Python Java CSharp
Java For Loop
The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.
To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.
Connect your cluster and start monitoring your K8s costs right away:
We rely on other people’s code in our own work. Every day.
It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.
The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.
Lightrun is a new kind of debugger.
It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.
Learn more in this quick, 5-minute Lightrun tutorial:
Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.
The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.
Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.
Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:
DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.
The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.
And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.
The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.
To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.
Connect your cluster and start monitoring your K8s costs right away:
We’re looking for a new Java technical editor to help review new articles for the site.
1. Overview
In this article, we’ll look at a core aspect of the Java language – executing a statement or a group of statements repeatedly using a for loop.
2. Simple for Loop
A for loop is a control structure that allows us to repeat certain operations by incrementing and evaluating a loop counter.
Before the first iteration, the loop counter gets initialized, then the condition evaluation is performed followed by the step definition (usually a simple incrementation).
The syntax of the for loop is:
for (initialization; Boolean-expression; step) statement;
Let’s see it in a simple example:
The initialization, Boolean-expression, and step used in for statements are optional. Here’s an example of an infinite for loop:
2.1. Labeled for Loops
We can also have labeled for loops. It’s useful if we’ve got nested for loops so that we can break/continue from aspecific for loop:
aa: for (int i = 1; i System.out.println(i + " " + j); > >
3. Enhanced for Loop
Since Java 5, we have a second kind of for loop called the enhanced for which makes it easier to iterate over all elements in an array or a collection.
The syntax of the enhanced for loop is:
for(Type item : items) statement;
Since this loop is simplified in comparison to the standard for loop, we need to declare only two things when initializing a loop:
- The handle for an element we’re currently iterating over
- The source array/collection we’re iterating
Therefore, we can say that: For each element in items, assign the element to the item variable and run the body of the loop.
Let’s have a look at the simple example:
int[] intArr = < 0,1,2,3,4 >; for (int num : intArr)
We can use it to iterate over various Java data structures:
Given a List list object – we can iterate it:
We can similarly iterate over a Set set:
And, given a Map map we can iterate over it as well:
for (Entry entry : map.entrySet())
3.1. Iterable.forEach()
Since Java 8, we can leverage for-each loops in a slightly different way. We now have a dedicated forEach() method in the Iterable interface that accepts a lambda expression representing an action we want to perform.
Internally, it simply delegates the job to the standard loop:
default void forEach(Consumer action) < Objects.requireNonNull(action); for (T t : this) < action.accept(t); >>
Let’s have a look at the example:
List names = new ArrayList<>(); names.add("Larry"); names.add("Steve"); names.add("James"); names.add("Conan"); names.add("Ellen"); names.forEach(name -> System.out.println(name));
4. Conclusion
In this quick tutorial, we explored Java’s for loop.
As always, examples can be found over on GitHub.
Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.
The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.
Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.
Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes: