Java Tutorial

Java methods, java classes, java file handling, java how to's, java reference, java examples, java for loop.

When you know exactly how many times you want to loop through a block of code, use the for loop instead of a while loop:

Statement 1 is executed (one time) before the execution of the code block.

Statement 2 defines the condition for executing the code block.

Statement 3 is executed (every time) after the code block has been executed.

The example below will print the numbers 0 to 4:

Try it Yourself »

Example explained

Statement 1 sets a variable before the loop starts (int i = 0).

Statement 2 defines the condition for the loop to run (i must be less than 5). If the condition is true, the loop will start over again, if it is false, the loop will end.

Statement 3 increases a value (i++) each time the code block in the loop has been executed.

Another Example

This example will only print even values between 0 and 10:

Test Yourself With Exercises

Use a for loop to print "Yes" 5 times.

Start the Exercise

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

Javatpoint Logo

Java Tutorial

Control statements, java object class, java inheritance, java polymorphism, java abstraction, java encapsulation, java oops misc.

JavaTpoint

The Java is used to iterate a part of the program several times. If the number of iteration is , it is recommended to use for loop.

There are three types of for loops in Java.

or Enhanced for Loop

A simple for loop is the same as / . We can initialize the , check condition and increment/decrement value. It consists of four parts:

: It is the initial condition which is executed once when the loop starts. Here, we can initialize the variable, or we can use an already initialized variable. It is an optional condition. : It is the second condition which is executed each time to test the condition of the loop. It continues execution until the condition is false. It must return boolean value either true or false. It is an optional condition. : It increments or decrements the variable value. It is an optional condition. : The statement of the loop is executed each time until the second condition is false.

If we have a for loop inside the another loop, it is known as nested for loop. The inner loop executes completely whenever outer loop executes.

The for-each loop is used to traverse array or collection in Java. It is easier to use than simple for loop because we don't need to increment value and use subscript notation.

It works on the basis of elements and not the index. It returns element one by one in the defined variable.

We can have a name of each Java for loop. To do so, we use label before the for loop. It is useful while using the nested for loop as we can break/continue specific for loop.

If you use , it will break inner loop only which is the default behaviour of any loop.

If you use two semicolons ;; in the for loop, it will be infinitive for loop.

Now, you need to press ctrl+c to exit from the program.

Comparison for loop while loop do-while loop
Introduction The Java for loop is a control flow statement that iterates a part of the multiple times. The Java while loop is a control flow statement that executes a part of the programs repeatedly on the basis of given boolean condition. The Java do while loop is a control flow statement that executes a part of the programs at least once and the further execution depends upon the given boolean condition.
When to use If the number of iteration is fixed, it is recommended to use for loop. If the number of iteration is not fixed, it is recommended to use while loop. If the number of iteration is not fixed and you must have to execute the loop at least once, it is recommended to use the do-while loop.
Syntax for(init;condition;incr/decr){
// code to be executed
}
while(condition){
//code to be executed
}
do{
//code to be executed
}while(condition);
Example //for loop
for(int i=1;i<=10;i++){
System.out.println(i);
}
//while loop
int i=1;
while(i<=10){
System.out.println(i);
i++;
}
//do-while loop
int i=1;
do{
System.out.println(i);
i++;
}while(i<=10);
Syntax for infinitive loop for(;;){
//code to be executed
}
while(true){
//code to be executed
}
do{
//code to be executed
}while(true);

Youtube

  • Send your Feedback to [email protected]

Help Others, Please Share

facebook

Learn Latest Tutorials

Splunk tutorial

Transact-SQL

Tumblr tutorial

Reinforcement Learning

R Programming tutorial

R Programming

RxJS tutorial

React Native

Python Design Patterns

Python Design Patterns

Python Pillow tutorial

Python Pillow

Python Turtle tutorial

Python Turtle

Keras tutorial

Preparation

Aptitude

Verbal Ability

Interview Questions

Interview Questions

Company Interview Questions

Company Questions

Trending Technologies

Artificial Intelligence

Artificial Intelligence

AWS Tutorial

Cloud Computing

Hadoop tutorial

Data Science

Angular 7 Tutorial

Machine Learning

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures

DAA tutorial

Operating System

Computer Network tutorial

Computer Network

Compiler Design tutorial

Compiler Design

Computer Organization and Architecture

Computer Organization

Discrete Mathematics Tutorial

Discrete Mathematics

Ethical Hacking

Ethical Hacking

Computer Graphics Tutorial

Computer Graphics

Software Engineering

Software Engineering

html tutorial

Web Technology

Cyber Security tutorial

Cyber Security

Automata Tutorial

C Programming

C++ tutorial

Control System

Data Mining Tutorial

Data Mining

Data Warehouse Tutorial

Data Warehouse

RSS Feed

The Java Tutorials have been written for JDK 8. Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available. See Java Language Changes for a summary of updated language features in Java SE 9 and subsequent releases. See JDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases.

The for Statement

The for statement provides a compact way to iterate over a range of values. Programmers often refer to it as the "for loop" because of the way in which it repeatedly loops until a particular condition is satisfied. The general form of the for statement can be expressed as follows:

When using this version of the for statement, keep in mind that:

  • The initialization expression initializes the loop; it's executed once, as the loop begins.
  • When the termination expression evaluates to false , the loop terminates.
  • The increment expression is invoked after each iteration through the loop; it is perfectly acceptable for this expression to increment or decrement a value.

The following program, ForDemo , uses the general form of the for statement to print the numbers 1 through 10 to standard output:

The output of this program is:

Notice how the code declares a variable within the initialization expression. The scope of this variable extends from its declaration to the end of the block governed by the for statement, so it can be used in the termination and increment expressions as well. If the variable that controls a for statement is not needed outside of the loop, it's best to declare the variable in the initialization expression. The names i , j , and k are often used to control for loops; declaring them within the initialization expression limits their life span and reduces errors.

The three expressions of the for loop are optional; an infinite loop can be created as follows:

The for statement also has another form designed for iteration through Collections and arrays This form is sometimes referred to as the enhanced for statement, and can be used to make your loops more compact and easy to read. To demonstrate, consider the following array, which holds the numbers 1 through 10:

The following program, EnhancedForDemo , uses the enhanced for to loop through the array:

In this example, the variable item holds the current value from the numbers array. The output from this program is the same as before:

We recommend using this form of the for statement instead of the general form whenever possible.

About Oracle | Contact Us | Legal Notices | Terms of Use | Your Privacy Rights

Copyright © 1995, 2022 Oracle and/or its affiliates. All rights reserved.

HowToDoInJava

Java For Loop

Lokesh Gupta

November 20, 2023

The for-loop statement in Java provides a compact way to iterate over the arrays or collection types using a counter variable that is incremented or decremented after each iteration. Programmers often refer to it as the traditional “for loop” because of the way it repeatedly loops until a particular condition is satisfied.

Note that Java also provides a more concise way to iterate over arrays or collections using the enhanced for-each loop .

The general form of the for loop can be expressed as follows:

  • initialization expression initializes the loop; it is executed once when the loop begins.
  • termination expression provides the condition when evaluates to false , the loop terminates.
  • increment expression is invoked after each iteration; it is perfectly acceptable for this expression to increment or decrement a counter variable.
  • statements are instructions executed in each iteration of the loop. We can access the current value of the counter variable in this block.

Note that all expressions in the for-loop are optional. In case, we do not provide the termination expression, we must terminate the loop inside the statements else it can result in an infinite loop .

2. Java For-loop Example

In the following program, we are iterating over an array of int values. The array contains 5 elements so the loop will iterate 5 times, once for each value in the array.

Program output.

The execution of for-loop flows like this-

  • First, 'int i = 0' is executed, which declares an integer variable i and initializes it to 0 .
  • Then, condition-expression (i < array.length) is evaluated. The current value of I is 0 so the expression evaluates to true for the first time. Now, the statement associated with the for-loop statement is executed, which prints the output in the console.
  • Finally i++ is executed that increments the value of i by 1. At this point, the value of i becomes 1.
  • Again the conditional expression is evaluated as still true , and the print statement is executed.
  • This process continues until the value of i becomes 4, and the print statement is executed.
  • After that, i++ sets the value of num to 5 , and the expression i < array.length returns false and stops the execution and terminates the loop.

3. Initialization, Termination, and Increment Statements are Optional

As mentioned in syntax, the initialization, termination, and increment are optional parts , that can be controlled from other places. Or the for loop might not have all of them.

For example, we can rewrite the previous example as below. We have taken out the counter initialization before the loop. We have moved the counter increment and the termination statements inside the loop body. The statements are the same as the previous version.

The program output is the same as the previous version.

Moreover, it is also possible to write an infinite loop without these parts at all:

4. Nested Loops

It’s possible to nest one for-loop in another for-loop. This approach is used to process multidimensional structures like tables (matrices), data cubes, and so on.

As an example, the following code prints the multiplication table of numbers from 1 to 9 (inclusive).

Program output:

Happy Learning !!

Further reading:

  • Python Interview Questions and Answers
  • Java Concurrency Interview Questions
  • Java while Loop
  • Memory Access for Volatile Variables and Thread-Safety in Java
  • Java Flow Control Statements
  • Java Interview Puzzles and Coding Exercises

guest

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Tutorial Series

Privacy Policy

REST API Tutorial

  • C Program : Remove All Characters in String Except Alphabets
  • C Program : Sorting a String in Alphabetical Order – 2 Ways
  • C Program : Remove Vowels from A String | 2 Ways
  • C Program To Check Whether A Number Is Even Or Odd | C Programs
  • C Program To Check If Vowel Or Consonant | 4 Simple Ways
  • C Program To Count The Total Number Of Notes In A Amount | C Programs
  • C Program To Print Number Of Days In A Month | Java Tutoring
  • C Program To Input Any Alphabet And Check Whether It Is Vowel Or Consonant
  • C Program To Find Maximum Between Three Numbers | C Programs
  • C Program To Find Reverse Of An Array – C Programs
  • C Program To Check If Alphabet, Digit or Special Character | C Programs
  • C Program To Check Whether A Character Is Alphabet or Not
  • C Program To Check A Number Is Negative, Positive Or Zero | C Programs
  • C Program Inverted Pyramid Star Pattern | 4 Ways – C Programs
  • C Program To Check Character Is Uppercase or Lowercase | C Programs
  • C Program To Calculate Profit or Loss In 2 Ways | C Programs
  • C Program To Check Whether A Year Is Leap Year Or Not | C Programs
  • C Program Find Circumference Of A Circle | 3 Ways
  • C Program Area Of Triangle | C Programs
  • C Program To Check If Triangle Is Valid Or Not | C Programs
  • C Program To Check Number Is Divisible By 5 and 11 or Not | C Programs
  • C Program Hollow Diamond Star Pattern | C Programs
  • Mirrored Rhombus Star Pattern Program In c | Patterns
  • X Star Pattern C Program 3 Simple Ways | C Star Patterns
  • C Program Area Of Rectangle | C Programs
  • C Program To Find Area Of Semi Circle | C Programs
  • C Program Area Of Parallelogram | C Programs
  • C Program Area Of Rhombus – 4 Ways | C Programs
  • C Program Area Of Isosceles Triangle | C Programs
  • C Program Area Of Trapezium – 3 Ways | C Programs
  • C Program Area Of Square | C Programs
  • C Program To Find Volume of Sphere | C Programs
  • C Program Check A Character Is Upper Case Or Lower Case
  • C Program to find the Area Of a Circle
  • C Program Area Of Equilateral Triangle | C Programs
  • Hollow Rhombus Star Pattern Program In C | Patterns
  • C Program To Calculate Volume Of Cube | C Programs
  • C Program To Count Total Number Of Notes in Given Amount
  • C Program To Find Volume Of Cone | C Programs
  • C Program To Calculate Perimeter Of Rectangle | C Programs
  • C Program To Calculate Perimeter Of Rhombus | C Programs
  • C Program To Calculate Perimeter Of Square | C Programs
  • C Program Volume Of Cuboid | C Programs
  • C Program To Left Rotate An Array | C Programs
  • C Program Count Number Of Words In A String | 4 Ways
  • C Program To Search All Occurrences Of A Character In String | C Programs
  • C Program To Count Occurrences Of A Word In A Given String | C Programs
  • C Program To Remove First Occurrence Of A Character From String
  • C Program To Copy All Elements From An Array | C Programs
  • C Program To Delete Duplicate Elements From An Array | 4 Ways
  • C Program Volume Of Cylinder | C Programs
  • C Square Star Pattern Program – C Pattern Programs | C Programs
  • C Program To Delete An Element From An Array At Specified Position | C Programs
  • C Program To Compare Two Strings – 3 Easy Ways | C Programs
  • C Program To Toggle Case Of Character Of A String | C Programs
  • C Program To Find Reverse Of A string | 4 Ways
  • C Mirrored Right Triangle Star Pattern Program – Pattern Programs
  • C Program To Search All Occurrences Of A Word In String | C Programs
  • Hollow Square Pattern Program in C | C Programs
  • C Program To Trim Leading & Trailing White Space Characters From String
  • C Programs – 500+ Simple & Basic Programming Examples & Outputs
  • C Program To Reverse Words In A String | C Programs
  • C Program Inverted Right Triangle Star Pattern – Pattern Programs
  • C Plus Star Pattern Program – Pattern Programs | C
  • Rhombus Star Pattern Program In C | 4 Multiple Ways
  • C Program Replace All Occurrences Of A Character With Another In String
  • C Program To Find Maximum & Minimum Element In Array | C Prorams
  • C Pyramid Star Pattern Program – Pattern Programs | C
  • C Program To Remove Repeated Characters From String | 4 Ways
  • C Program To Count Frequency Of Each Character In String | C Programs
  • C Program To Remove Blank Spaces From String | C Programs
  • C Program To Remove Last Occurrence Of A Character From String
  • C Program Right Triangle Star Pattern | Pattern Programs
  • C Program To Find Last Occurrence Of A Word In A String | C Programs
  • C Program To Count Number Of Even & Odd Elements In Array | C Programs
  • C Program To Copy One String To Another String | 4 Simple Ways
  • C Program To Find Last Occurrence Of A Character In A Given String
  • C Program Replace First Occurrence Of A Character With Another String
  • C Program Number Of Alphabets, Digits & Special Character In String | Programs
  • C Program To Search An Element In An Array | C Programs
  • C Program To Check A String Is Palindrome Or Not | C Programs
  • Merge Two Arrays To Third Array C Program | 4 Ways
  • C Program To Trim White Space Characters From String | C Programs
  • C Program To Print Number Of Days In A Month | 5 Ways
  • C Program To Concatenate Two Strings | 4 Simple Ways
  • C Program To Find First Occurrence Of A Word In String | C Programs
  • C Program To Sort Even And Odd Elements Of Array | C Programs
  • C Program Count Number Of Vowels & Consonants In A String | 4 Ways
  • C Program To Sort Array Elements In Ascending Order | 4 Ways
  • C Program To Remove First Occurrence Of A Word From String | 4 Ways
  • Highest Frequency Character In A String C Program | 4 Ways
  • C Program To Trim Trailing White Space Characters From String | C Programs
  • C Program To Count Frequency Of Each Element In Array | C Programs
  • C Program To Count Occurrences Of A Character In String | C Programs
  • C Program To Convert Uppercase String To Lowercase | 4 Ways
  • C Program To Convert Lowercase String To Uppercase | 4 Ways
  • C Program To Put Even And Odd Elements Of Array Into Two Separate Arrays
  • C Program To Print All Unique Elements In The Array | C Programs
  • C Program Find Maximum Between Two Numbers | C Programs
  • C Program Hollow Inverted Mirrored Right Triangle
  • C Program Hollow Inverted Right Triangle Star Pattern
  • Diamond Star Pattern C Program – 4 Ways | C Patterns
  • C Program To Sort Array Elements In Descending Order | 3 Ways
  • C Program Count Number of Duplicate Elements in An Array | C Programs
  • C Program To Find Sum Of All Array Elements | 4 Simple Ways
  • C Program To Replace Last Occurrence Of A Character In String | C Programs
  • C Program To Remove All Occurrences Of A Character From String | C Programs
  • C Program To Insert Element In An Array At Specified Position
  • C Program To Input Week Number And Print Week Day | 2 Ways
  • C Program Hollow Mirrored Rhombus Star Pattern | C Programs
  • C Program To Find Lowest Frequency Character In A String | C Programs
  • C Program Hollow Mirrored Right Triangle Star Pattern
  • C Program To Read & Print Elements Of Array | C Programs
  • C Program To Count Number Of Negative Elements In Array
  • C Program To Right Rotate An Array | 4 Ways
  • C Program To Find First Occurrence Of A Character In A String
  • C Program Half Diamond Star Pattern | C Pattern Programs
  • 8 Star Pattern – C Program | 4 Multiple Ways
  • Hollow Inverted Pyramid Star Pattern Program in C
  • Right Arrow Star Pattern Program In C | 4 Ways
  • C Program To Print All Negative Elements In An Array
  • C Program To Find Length Of A String | 4 Simple Ways
  • C Program : Capitalize First & Last Letter of A String | C Programs
  • C Program : Check if Two Strings Are Anagram or Not
  • C Program : Check if Two Arrays Are the Same or Not | C Programs
  • C Program Hollow Right Triangle Star Pattern
  • Left Arrow Star Pattern Program in C | C Programs
  • C Program Inverted Mirrored Right Triangle Star Pattern
  • Hollow Pyramid Star Pattern Program in C
  • C Program Mirrored Half Diamond Star Pattern | C Patterns
  • C Program : Non – Repeating Characters in A String | C Programs
  • C Program : Sum of Positive Square Elements in An Array | C Programs
  • C Program : Find Longest Palindrome in An Array | C Programs
  • C Program Lower Triangular Matrix or Not | C Programs
  • C Program : To Reverse the Elements of An Array | C Programs
  • C Program Merge Two Sorted Arrays – 3 Ways | C Programs
  • C Program : Convert An Array Into a Zig-Zag Fashion
  • C Program : Maximum Scalar Product of Two Vectors
  • C Program : Check If Arrays are Disjoint or Not | C Programs
  • C Program : Minimum Scalar Product of Two Vectors | C Programs
  • C Program : Find Missing Elements of a Range – 2 Ways | C Programs
  • C Program Transpose of a Matrix 2 Ways | C Programs
  • C program : Find Median of Two Sorted Arrays | C Programs
  • C Program : To Find Maximum Element in A Row | C Programs
  • C Program : Rotate the Matrix by K Times | C Porgrams
  • C Program Patterns of 0(1+)0 in The Given String | C Programs
  • C Program : Check if An Array Is a Subset of Another Array
  • C Program : To Find the Maximum Element in a Column
  • C Program To Check Upper Triangular Matrix or Not | C Programs
  • C Program : Rotate a Given Matrix by 90 Degrees Anticlockwise
  • C Program : Non-Repeating Elements of An Array | C Programs
  • C Program Sum of Each Row and Column of A Matrix | C Programs

Learn Java Java Tutoring is a resource blog on java focused mostly on beginners to learn Java in the simplest way without much effort you can access unlimited programs, interview questions, examples

Java for loop – tutorial with examples | loops.

in Java Tutorials , Loops July 20, 2024 Comments Off on Java For Loop – Tutorial With Examples | Loops

Java for loop tutorial with examples and complete guide for beginners. The below article on Java for loop will cover most of the information, covering all the different methods, syntax, examples that we used in for loops.

What Are Java Loops – Definition & Explanation

Executing a set of statements repeatedly is known as looping. We have 3 types of looping constructs in Java. These looping statements are also known as iterative statements.

  • The above three different java loops are used primarily with same purpose and the difference is in their syntax.
  • Because of the syntactical differences, their behavior may differ a little bit. We will see the differences soon.

For Loop In Java & Different Types

Java For Loop, is probably the most used one out of the three loops. Whatever we can do for a while we can do it with a Java for loop too (and of course with a do-while too).

There are two kinds of for loops

1. Normal for loop

2. For each style of for loop

For Loop In Java Different Types And Explanation:

1.Normal for loop

(initialization; condition; incr/decr) --- ---
  • When control comes to a Java for loop, it executes the initialization part first. This part is executed only once.
  • The one-time activities associated with the loop (that too at the beginning) are done here.
  • Then control moves to condition part. If the condition results in true, the control enters the body.

If it results in false the control comes out of the java for loop and executes the statement immediately following the loop.

When the condition is true, the loop body is executed. This is where the actual logic is executed. Then control comes to incr/decr part. Here, generally, the control variables are incremented/decremented.

After executing the incr/decr part, the control comes to condition part. If it results true, the body is executed, then comes to incr/decr and then to condition part. This process is repeated as long as condition results in true.

(int a=1; a<=3; a++) .out.println(drink more water);

In the above example, in the initialization part, the variable a is initialized with 1.

This activity takes place only once. Then it moves to condition a<=3 which results in true.

So it comes to loop body to print “ drink more water ” and then it moves to increment a value by 1 so that a becomes 2. Then it comes to condition part, results in true, print the message and comes back to increment to make a value 3. Once again the condition is true, so prints the message in the body and then comes to make a value 4.

Then the condition results in false (as 4<=3 is false) and comes out to execute the statement after the loop.

  • In a Java for loop, initialization is executed only once irrespective of a number of times the loop is executed.
  • The condition is checked N+1 times where N is the number of times the body is executed.
  • Incr/decr part is executed N times (same as the number of times the body is executed).

Example Program:

example public static void main(String arg[]) { int i; for(i=1;i<=3;i++) { System.out.print("hello world"); } }
world world world

When we create a variable at initialization part of the for loop that variable is automatically dead when the loop ends (in C, we cannot create a variable at initialization part of the for loop).

Such variable cannot be used outside the loop. If we want we can create a variable a fresh with the same name outside.

(int len=1;len<=max; len++) statements;

int x=len;             is not valid as len is dead.

int len=p;             is valid, as len is treated as a fresh variable

ForLoopBasics4 public static void main(String args[]) { for(int i=1;i<=5;i++) { System.out.println(i); } }
ForLoopBasics5 public static void main(String args[]) { for(int i=1;i<=5;i++) { System.out.println(i);  //1 2 3 4 5 } System.out.println(i);//error for unknown variable i
: cannot find symbol                                                                                                                                   System.out.print(i);                                                                                                                                                       ^

description:

the above program error occurs due to variable 'i' is dead the for loop ends
ForLoopBasics6 public static void main(String args[]) { int i; for( i=1;i<=5;i++) { System.out.println(i);  //1 2 3 4 5 } System.out.println(i);  //6
the above program, we don't get an error because here variable 'i' not declared in the for loop
  • We can have any number of statements in a for loop body.
  • All of them should be enclosed within curly braces.
  • If we have only one statement, then the curly braces are optional.
(double b=2.3; b<=10; b+=1.2) .out.print(b); .out.print(10-b);
(int c=A; c<=Z; c++) .out.print( +(char)c);

The initialization part can have any number of statements, but all of them should be separated by a comma.

When initialization ends, then that part should end with a semi-colon. In the following example, three statements (a=10), (b=20) and (c=30) are placed in the initialization part separated by commas.

(a=10, b=20, c=30;  a+b <= c ;  a++) ;
ForLoopBasics9 public static void main(String args[]) { int a,b,c; for(a=10, b=20, c=33;  a+b <= c ;  a++) { System.out.println(true); } }
  • Similar to initialization part, the incr/decr part can also have multiple statements separated by commas.
(a=1,b=5; a<=b; a+=2, b++) ;
ForLoopBasics10 public static void main(String args[]) { int a,b,c; for(a=1,b=5; a<=b; a+=2, b++) { System.out.println(a +"<="+ b); } } }
<= 5                                                                                                                                                                           <= 6                                                                                                                                                                           <= 7                                                                                                                                                                           <= 8                                                                                                                                                                           <= 9

But the condition part should not be separated by commas.

All supposed conditions should be combined using AND or OR operators to make it a single condition (in C, we can have multiple conditions separated by commas and truth value of the last condition is considered as truth value of condition part).

for(a=2; a<=b && a<=c; a++)       is valid

for(a=3; a<=b, a<=c; a++)             is not valid

for(a=4; a>=b || a>=0; a–)            is valid

The condition should always result in a boolean value. Other types of values are not allowed.

for(int a=5,b=6; a<=b ; a++)        is valid

for(int a=7,b=8; a+b; a++)            is not valid

Generally, the header part of the for loop decides (with initialization, condition, and incrementation) how many times the loop will be executed and the actual logic is placed in the body.

In case the header part itself has the actual logic implicitly then the body may not be required. In that case, we can have a dummy body. We have two examples below, the first one has a set of curly braces without any code inside. In the second example, just a semi-colon is the body of the loop.

(int a=9; a<=b; a++)
ForLoopBasics11 public static void main(String args[]) { int a,b,c,n=10;     //n=10 mean first 10 fibonacci numbers a=0; b=1; System.out.print(a+" "+b+" "); for(int i=2;i<n;i++) { c=a+b; a=b; b=c; System.out.print(c+" "); } } }
1 1 2 3 5 8 13 21 34

2. Nesting for loop

  • We can have a for loop inside another for loop. This is known as nesting.
(int a=11; a<=b; a++) ; (int x=12; x<=y; x++) ; ;

In this example, first control comes to initiation part of outer for loop.

The explanation for the Above Example:

Their value of a becomes 11.

Then it comes to its condition part.

If the condition is true, it enters the loop body and executes statementA.

Then control comes to initialization part of inner loop and then to condition part.

If the condition part is true, it enters the body of loop body and executes statementB.

And then it goes to incrementation part of inner for loop and then to condition part of the same (inner) loop.

This (inner loop) is repeated as long as the inner condition is true.

NestedForLoop public static void main(String args[]) { int i,j; for(i=1;i<=3;i++) { System.out.println(i+"iteration"); for(j=1;j<=3;j++) { System.out.println(j); } } }
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            

We can place any construct inside another a for loop. There is no limit on the number of constructs we can place in.

To come out of a for loop from the middle of the body, we can use a break . The break will take the control out of the loop without regard to a condition in the header.

(a=16; a<=i; a+=3) ---- (condition) ; ----

If we want to go the next iteration of a loop from the middle of the body (by skipping the remaining statements of current iteration) then we can use continue.

(a=17; a<=j; a*=2) ---- (condition) ; ----

Even though it is named to be initialization, condition and incrementation parts, we can write any statement in that part. The condition part should result in a boolean value. At initialization, we can create variables but not at incrementation part. The following code is valid.

Sometimes the initialization takes place by the time control comes to the for loop, in that case, we can write a dummy statement (just a semi-colon) at initialization part. Similarly, we can skip the incrementation part. If we use a dummy condition (just a; ) then it is treated as true. So all the following usages are valid.

a=1; ( ; a<=3; a++) ;
(int a=1; a<=3; ) ; ++;
(int a=1; ; a++) (a>3) ; ;

If we write a for loop like for(;;) and there is no break or return kind of statements then that loop becomes an infinite loop. The following are infinites.

Eg1:        for( ; ; )

Eg2:        for(init; true; incr)

2.Foreach style of for loop

(variable : collection) --- ---

Definition:

These kinds of loops are used to travel through a set of elements strictly in an order (from beginning to ending). The Set of elements can be an array, an ArrayList, a LinkedList or any other collection.

Suppose we have an array and wanted to print each element of the array we can write a normal loop like the following.

a[]={10,20,30,40}; (int i=0; i<a.length; i++) .out.println(a[i]);

In this example, the loop is repeated for 4 times (number of elements in the array) and each time i th element (from 0 th to 3 rd ) is printed.

To get the same result, we can use the following notation (for each style).

int a[]={10,20,30,40};

for(int x : a)

System.out.println(x);

In this case, the variable x gets each value of the array (one value per iteration) and it is printed. Relatively this approach (foreach) is comfortable to visit all elements of the list. If we want parts of the list then we can use the normal for loop.

The following example gives another example of using for each notation to travel through an ArrayList.

<Integer> al=new ArrayList<Integer>(); .add(10); al.add(20); al.add(30); al.add(40); (int x : al) .out.println(x);

Similar to normal loop, we can come out of this loop also using a statement like break ;

To travel through a two dimensional array we can write a code like the following.

a[][]={{1,2,3,4},{5,6,7,8},{9,8,7,6}}; (int curArr[] : a) (int curEle : curArr) .out.print(curEle+" ");

In the above example, the outer loop travels through an array of references (where each reference will refer an array) and the inner loop travels through each element (of the current array).

Related Posts !

Remove an element from collection using iterator object in java.

July 20, 2024

How to Read All Elements In Vector By Using Iterator

assignment for for loop in java

30+ Number & Star Pattern Programs In Java – Patterns

Java thread by extending thread class – java tutorials, copying character array to string in java – tutorial, what is recursion in java programming – javatutoring, java if else – tutorial with examples | learn java.

If else Java – statement complete tutorial. Here we cover in-depth information with examples on ...

Table of Contents

The difference between for loop - while loop - do-while loop, types of for loops in java, pitfalls of loops, choosing the right loop, understanding for loop in java with examples and syntax.

Understanding For Loop In Java With Examples

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

While all three types’ basic functionality remains the same, there’s a vast difference in the syntax and how they operate.

For loop in Java iterates over code based on a condition, commonly used for arrays or calculations. Mastering it is crucial for efficient iteration and data processing. Enroll in a Java Course to explore for loops and more programming constructs.

In this article, you will focus on for loop in Java. But before delving deep into for loop and how to use it, let’s understand the difference between the three types of loops.

There are several differences among the three types of loops in Java, such as the syntax, optimal time to use, condition checking, and so on. The table below represents some of the primary dissimilarities between all the loops in Java.

Introduction

For loop in Java iterates a given set of statements multiple times.

The Java while loop executes a set of instructions until a boolean condition is met.

The do-while loop executes a set of statements at least once, even if the condition is not met. After the first execution, it repeats the iteration until the boolean condition is met.

Best time to use

Use it when you know the exact number of times to execute the part of the program.

Use it when you don’t know how many times you want the iteration to repeat.

Use it when you don’t know how many times you want the iteration to repeat, but it should execute at least one time.

Syntax

for(init; condition; icr/dcr){

//statements to be repeated

}

while(condition){

//statements to be repeated

}

do{

//statements to be repeated

}while(condition);

Example

for(int x=0; x<=5; x++){

System.out.println(x);

}

int x=0;

while(x<=5){

System.out.println(x);

x++;

}

int x=0;

do{

System.out.println(x);

x++;

}while(x<=5);

Master Core Java 8 Concepts, Java Servlet & More!

Master Core Java 8 Concepts, Java Servlet & More!

For Loop in Java

As mentioned, Java for loop helps execute a set of code repeatedly, and it is recommended when the number of iterations is fixed. You have seen the syntax of for loop, now try to understand it.

for(init; condition, incr/decr){

//statements to be executed or body

In the above syntax:

  • init: The init expression is used for initializing a variable, and it is executed only once.
  • condition: It executes the condition statement for every iteration. If it evaluates the condition to be true, it executes the body of the loop. The loop will continue to run until the condition becomes false.
  • incr/decr: It is the increment or decrement statement applied to the variable to update the initial expression.

Thus, the Flow of for Loop in Java Is:

/flowofforloop

Let’s look at a simple for loop example to understand the syntax and how it operates.

public class forExample{

public static void main(String args[]) {

for(int x=0; x<=5; x++){

             System.out.println(x);   

ForLoop_1.

There are three types of for loops in Java:

  • For-each or enhanced

You will go through each type of Java for loops with examples.

Simple For Loop in Java

A simple for loop is what you have seen until now, including the flow and syntax. Here’s an example where you must print the values from 1 to 10.

Example of simple for loop:

for(int x=1; x<=10; x++){

TypeForLoop

For-each Loop in Java

The Java for-each loop is used on an array or a collection type. It works as an iterator and helps traverse through an array or collection elements, and returns them. While declaring a for-each loop, you don’t have to provide the increment or decrement statement as the loop will, by default, traverse through each element. Here’s the syntax:

for(Type var:array){  

//loop body

Example of for-each loop:

public class ForEach{  

    public static void main(String[] args){  

        //Array declaration  

        int ar[]={1,2,3,5,7,11,13,17,19};  

        //Using for-each loop to print the array  

        for(int x:ar){

            System.out.println(x);  

        }  

ForEachLoop

Labeled For Loop in Java

With the labeled for loop in Java, you can label the loops. It is useful when you have a nested loop (more about it later) and want to use the break or continue keyword for the outer loop instead of the inner one. Usually, the break and continue keyword works on the innermost loop by default. The syntax of Java labeled for loop is:

labelname:  

for(initialization;condition;incr/decr){  

Example of labeled for loop

public class LabeledForLoop{  

        //Using Labels 

        Label1:  

            for(int x=1;x<=5;x++){  

                Label2:  

                    for(int y=1;y<=4;y++){  

                        if(x==3&&y==2){  

                            break Label1;  

                        }  

                        System.out.println(x+" "+y);  

                    }  

            }  

LabeledForLoop

As you can see in the above example, this demo has used the label name to break the outer loop, which is the opposite of a loop’s default behavior.

Nested For Loop in Java

Java nested for loop is not a separate type of loop. It is just using one or multiple for loops inside another. Whenever the outer loop meets the condition, the inner loop is executed completely. It is usually used for pattern programs to print distinct patterns in the output. The example below uses the nested for loop in Java to print a pyramid.

public class NestedForExample{  

        for(int x=1;x<=7;x++){

            for(int y=1;y<=x;y++){  

                System.out.print("* ");  

            //new line when the inner loop is executed completely

            System.out.println();

NestedForLoop

Infinite For Loop in Java

The Java infinite for loop is used if you want to keep running a certain set of code. Syntax of infinite for loop in Java is:

Example of infinite for loop

public class InfiniteFor{  

    public static void main(String[] args) {  

        //Declaring the infinite for loop  

        for(;;){  

            System.out.println("Simplilearn");  

infiniteForLoop.

You can use ctrl + c to exit the infinite loop.

Skyrocket Your Career: Earn Top Salaries!

Skyrocket Your Career: Earn Top Salaries!

Here are some common pitfalls associated with loops in Java:

  • Infinite Loops:
  • An infinite loop occurs when the loop condition never becomes false, causing the loop to continue indefinitely.
  • Example: Forgetting to update the loop control variable in a while or for a loop can lead to an infinite loop.
  • Solution: Always ensure the loop condition is properly defined and updated within the loop body to avoid infinite looping.
  • Off-by-One Errors:
  • Off-by-one errors occur when loop iterations are either too many or too few.
  • Example: Using <= instead of < or forgetting to subtract one from the loop termination condition in a loop that iterates over an array.
  • Solution: Double-check loop conditions to ensure they are inclusive or exclusive as needed, and verify that loop indexes are within the correct range.
  • Incorrect Loop Control:
  • Incorrect loop control can result in unexpected behavior, such as skipping iterations or executing the loop body when it should not.
  • Example: Misplacing or incorrectly using loop control statements like break and continue.
  • Solution: Review loop control statements to ensure they are placed and used correctly within the loop structure.
  • Mutable Loop Variables:
  • Modifying loop control variables within the loop body can lead to unintended behavior and make the code difficult to understand.
  • Example: Modifying the loop index or condition variable inside a loop can result in unexpected loop termination or iteration behavior.
  • Solution: Avoid modifying loop control variables within the loop body unless necessary. If needed, document such modifications clearly to enhance code readability.
  • Inefficient Looping Constructs:
  • Using inefficient looping constructs, such as nested loops or unnecessary iterations, can degrade performance and increase execution time.
  • Example: Using nested loops when a single loop suffices or iterating over the entire collection when only a subset of elements is needed.
  • Solution: Optimize looping constructs by reducing unnecessary iterations, minimizing nested loops, and choosing the most efficient loop type for the task.

Developers can write more robust and efficient code by being aware of these pitfalls and adopting best practices, such as carefully designing loop conditions, verifying loop control statements, and optimizing loop constructs.

Choosing the right loop construct is crucial in Java programming as it can significantly impact code readability, efficiency, and maintainability. Here's an elaboration on the considerations when choosing the appropriate loop:

  • The for loop is ideal when the number of iterations is known or when iterating over a range of values.
  • It provides a compact syntax for initializing loop variables, specifying loop conditions, and updating loop counters in a single line.
  • Use cases include iterating over arrays, processing elements of collections, and implementing iterative algorithms.
  • while Loop:
  • The while loop is suitable when the number of iterations is uncertain or looping based on a condition that may change during execution.
  • It continues iterating as long as the loop condition is evaluated as true.
  • Use cases include implementing interactive input loops, processing data until a specific condition is met, and performing conditional iteration.
  • do-while Loop:
  • The do-while loop is useful when you want to execute the loop body at least once before checking the loop condition.
  • It guarantees that the loop body executes at least once, regardless of the initial condition.
  • Use cases include menu-driven programs, input validation loops, and iterative tasks that require initialization before condition evaluation.
  • Choosing Based on Clarity and Readability:
  • Prioritize code clarity and readability when selecting a loop construct.
  • Consider the loop structure that best conveys the code's intention and makes it easier for other developers to understand.
  • Choose a loop type that aligns with the problem domain and promotes maintainability over time.
  • Performance Considerations:
  • Evaluate the performance implications of different loop constructs, especially in performance-critical sections of code.
  • Measure the overhead associated with loop initialization, condition evaluation, and loop variable updates.
  • Optimize loops for performance by minimizing unnecessary iterations, reducing loop complexity, and using appropriate loop types.

By carefully considering factors such as the nature of the iteration, loop conditions, code clarity, and performance requirements, developers can choose the right loop construct to solve the problem while maintaining code readability and efficiency.

Get a firm foundation in Java, the most commonly used programming language in software development with the  Java Certification Training Course .

In this for loop in Java article, you learned what loops are, and what are for loops in specific. You also looked at the types of loops, the difference between them, and the types of for loops with examples. 

If you want to learn about the other two types of loops: while and do-while, you can refer to Simplilearn’s Java Tutorial for Beginners: A Step-By-Step Guide . You can also opt for the Free Java Course for Beginners that includes around 9 hours of self-paced video lessons. But if you want to go a step further and excel in Java programming, go for our Java Certification Training Course . It offers you applied learning and hands-on experience with some of the most-popular Java environment frameworks, including Hibernate and Spring.

1. What are loops in Java, and why are they important?

Loops in Java are programming constructs used to repeatedly execute a block of code until a specified condition is met. They are essential for automating repetitive tasks, iterating over arrays or collections, and implementing various algorithms efficiently.

2. How many types of loops are there in Java?

Java provides three main types of loops: the for loop, the while loop, and the do-while loop. Each type has its syntax and use cases, allowing developers to choose the most appropriate loop for a given scenario.

3. What is the difference between a while loop and a do-while loop in Java?

The main difference between a while loop and a do-while loop is that a while loop tests the loop condition before executing the loop body, while a do-while loop executes the loop body at least once and then tests the loop condition.

4. How do I prevent an infinite loop in Java?

To prevent an infinite loop in Java, ensure the loop condition is properly defined and updated within the loop body. Use loop control statements like break or return to exit the loop when a specific condition is met. Additionally, carefully review the loop logic to avoid unintentional infinite looping.

5. When should I use a for loop versus a while loop in Java?

Use a for loop when the number of iterations is known or when iterating over a range of values. On the other hand, use a while loop when the number of iterations is uncertain or when looping based on a condition that may change during execution. Choose the loop type that best fits your program's specific requirements.

Our Software Development Courses Duration And Fees

Software Development Course typically range from a few weeks to several months, with fees varying based on program and institution.

Program NameDurationFees

Cohort Starts:

4 Months€ 2,499

Cohort Starts:

11 Months€ 1,099

Cohort Starts:

6 Months€ 1,500

Cohort Starts:

6 Months€ 1,500

Recommended Reads

Free eBook: Pocket Guide to the Microsoft Certifications

Understanding the While Loop in C++

The Best Guide to C++ For Loop : For Loops Made Easy

Free eBook: Enterprise Architecture Salary Report

The Basics of Python Loops

Get Affiliated Certifications with Live Class programs

Java certification training.

  • 24x7 learner assistance and support

Full Stack Java Developer Masters Program

  • Kickstart Full Stack Java Developer career with industry-aligned curriculum by experts
  • Hands-on practice through 20+ projects, assessments, and tests
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.

TopJavaTutorial

For loop in java 8.

For loop in Java has changed a lot from the way it first appeared in jdk 1.

Here is an example of the classical for loop :

                   // Classic for loop         for(int i=0;i<5;i++){     System.out.println(i);   }  

Java 5 added the forEach loop that made looping with collections easier as it removed declaration of the looping variable and checking length of the collection.

Here is an example of the forEach loop :

                   List categories = Arrays.asList("Java","Dot Net","Oracle","Excel");        // For Each loop   for(String category: categories){     System.out.println(category);   }  

Java 8 added lambda expressions and Stream api.

The Stream api java.util.Stream provides a forEach that can be used to loop over collection as shown below :

                   // Java 8 Lambda For loop   categories.stream().forEach(category-> System.out.println(category));  

Here is the complete example that loops over a list using different for loops :

  package com.topjavatutorial.java8examples; import java.util.Arrays; import java.util.List; public class ForLoopExample {   public static void main(String[] args) {          List categories = Arrays.asList("Java","Dot Net","Oracle","Excel");          // Classic for loop          for(int i=0;i<categories.size();i++){ System.out.println(categories.get(i)); }                 // For Each loop                 for(String category: categories){ System.out.println(category); }                 // Java 8 Lambda For loop                 categories.stream().forEach(category-> System.out.println(category));        } }  

You may like the following articles on Java 8:

  • Introduction to Java 8 Lambda expressions
  • Java 8 Interface new features

© 2015 – 2016, https: . All rights reserved. On republishing this post, you must provide link to original post

Share this article :

  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Facebook (Opens in new window)
  • Click to share on Twitter (Opens in new window)
  • Click to share on Pinterest (Opens in new window)
  • Click to share on Flipboard (Opens in new window)
  • Click to share on Tumblr (Opens in new window)
  • Click to share on Reddit (Opens in new window)
  • Click to share on Pocket (Opens in new window)

Popular Articles you may like :

  • Java 8 Interview Questions
  • RESTful CRUD operations using Jersey and Hibernate
  • Frequently asked Java Programming Interview questions on Strings

assignment for for loop in java

int n=10; int i; int j; int k; for(i=1;i<=n;i++){ k=i; for(j=1;j<=i;j++){ System.out.printf("%2d",k); k=k+(n-j); } System.out.print("/n"); } } }

assignment for for loop in java

Please help me out in this 1 2 6 3 7 10 4 8 11 13 5 9 12 14 15

Leave a Reply.. code can be added in <code> </code> tags Cancel reply

Learn Java practically and Get Certified .

Popular Tutorials

Popular examples, reference materials, learn java interactively, java introduction.

  • Get Started With Java
  • Your First Java Program
  • Java Comments

Java Fundamentals

  • Java Variables and Literals
  • Java Data Types (Primitive)
  • Java Operators
  • Java Basic Input and Output
  • Java Expressions, Statements and Blocks

Java Flow Control

  • Java if...else Statement
  • Java Ternary Operator

Java for Loop

  • Java for-each Loop

Java while and do...while Loop

Java break Statement

Java continue Statement

  • Java switch Statement
  • Java Arrays
  • Java Multidimensional Arrays
  • Java Copy Arrays

Java OOP(I)

  • Java Class and Objects
  • Java Methods
  • Java Method Overloading
  • Java Constructors
  • Java Static Keyword
  • Java Strings
  • Java Access Modifiers
  • Java this Keyword
  • Java final keyword
  • Java Recursion
  • Java instanceof Operator

Java OOP(II)

  • Java Inheritance
  • Java Method Overriding
  • Java Abstract Class and Abstract Methods
  • Java Interface
  • Java Polymorphism
  • Java Encapsulation

Java OOP(III)

  • Java Nested and Inner Class
  • Java Nested Static Class
  • Java Anonymous Class
  • Java Singleton Class
  • Java enum Constructor
  • Java enum Strings
  • Java Reflection
  • Java Package
  • Java Exception Handling
  • Java Exceptions
  • Java try...catch
  • Java throw and throws
  • Java catch Multiple Exceptions
  • Java try-with-resources
  • Java Annotations
  • Java Annotation Types
  • Java Logging
  • Java Assertions
  • Java Collections Framework
  • Java Collection Interface
  • Java ArrayList
  • Java Vector
  • Java Stack Class
  • Java Queue Interface
  • Java PriorityQueue
  • Java Deque Interface
  • Java LinkedList
  • Java ArrayDeque
  • Java BlockingQueue
  • Java ArrayBlockingQueue
  • Java LinkedBlockingQueue
  • Java Map Interface
  • Java HashMap
  • Java LinkedHashMap
  • Java WeakHashMap
  • Java EnumMap
  • Java SortedMap Interface
  • Java NavigableMap Interface
  • Java TreeMap
  • Java ConcurrentMap Interface
  • Java ConcurrentHashMap
  • Java Set Interface
  • Java HashSet Class
  • Java EnumSet
  • Java LinkedHashSet
  • Java SortedSet Interface
  • Java NavigableSet Interface
  • Java TreeSet
  • Java Algorithms
  • Java Iterator Interface
  • Java ListIterator Interface

Java I/o Streams

  • Java I/O Streams
  • Java InputStream Class
  • Java OutputStream Class
  • Java FileInputStream Class
  • Java FileOutputStream Class
  • Java ByteArrayInputStream Class
  • Java ByteArrayOutputStream Class
  • Java ObjectInputStream Class
  • Java ObjectOutputStream Class
  • Java BufferedInputStream Class
  • Java BufferedOutputStream Class
  • Java PrintStream Class

Java Reader/Writer

  • Java File Class
  • Java Reader Class
  • Java Writer Class
  • Java InputStreamReader Class
  • Java OutputStreamWriter Class
  • Java FileReader Class
  • Java FileWriter Class
  • Java BufferedReader
  • Java BufferedWriter Class
  • Java StringReader Class
  • Java StringWriter Class
  • Java PrintWriter Class

Additional Topics

  • Java Keywords and Identifiers
  • Java Operator Precedence
  • Java Bitwise and Shift Operators
  • Java Scanner Class
  • Java Type Casting
  • Java Wrapper Class
  • Java autoboxing and unboxing
  • Java Lambda Expressions
  • Java Generics

Nested Loop in Java

  • Java Command-Line Arguments

Java Tutorials

If a loop exists inside the body of another loop, it's called a nested loop. Here's an example of the nested for loop.

Here, we are using a for loop inside another for loop.

We can use the nested loop to iterate through each day of a week for 3 weeks.

In this case, we can create a loop to iterate three times (3 weeks). And, inside the loop, we can create another loop to iterate 7 times (7 days).

Example 1: Java Nested for Loop

In the above example, the outer loop iterates 3 times and prints 3 weeks. And, the inner loop iterates 7 times and prints the 7 days.

We can also create nested loops with while and do...while in a similar way.

Note : It is possible to use one type of loop inside the body of another loop. For example, we can put a for loop inside the while loop.

Example 2: Java for loop inside the while loop

Here you can see that the output of both Example 1 and Example 2 is the same.

Example 3: Java nested loops to create a pattern

We can use the nested loop in Java to create patterns like full pyramid, half pyramid, inverted pyramid, and so on.

Here is a program to create a half pyramid pattern using nested loops.

To learn more, visit the Java program to print pyramid and patterns .

  • break and continue Inside Nested Loops

When we use a break statement inside the inner loop, it terminates the inner loop but not the outer loop. For example,

In the above example, we have used the break statement inside the inner for loop. Here, the program skips the loop when i is 2 .

Hence, days for week 2 are not printed. However, the outer loop that prints week is unaffected.

Similarly, when we use a continue statement inside the inner loop, it skips the current iteration of the inner loop only. The outer loop is unaffected. For example,

In the above example, we have used the continue statement inside the inner for loop. Notice the code,

Here, the continue statement is executed when the value of j is odd. Hence, the program only prints those days that are even.

We can see the continue statement has affected only the inner loop. The outer loop is working without any problem.

Table of Contents

  • Java nested loop
  • Example: Nested for Loop
  • Example: for loop inside while loop
  • Java nested loop to create a pattern

Sorry about that.

Related Tutorials

Java Tutorial

Enhanced For Loops in Java – How to Use ForEach Loops on Arrays

Ihechikara Abba

You can use enhanced loops in Java to achieve the same results as a for loop . An enhanced loop is also known as a for-each loop in Java.

Enhanced loops simplify the way you create for loops. They are mostly used to iterate through an array or collection of variables.

In this tutorial, you'll learn the syntax and how to use the for-each loop (enhanced loop) in Java.

Java For-Each Loop Syntax

Here's what the syntax of a for-each loop in Java looks like:

In the syntax above:

  • dataType denotes the data type of the array .
  • variable denotes a variable assigned to each element in the array during the iteration (you'll understand this through the examples that follow).
  • array denotes the array to be looped through.

Java For-Each Loop Example

Let's take a look at some examples to help you understand how a for-each loop works.

Java For-Each Loop Example #1

In the code above, we created an array called even_numbers .

To loop through and print all the numbers in the array, we made use of a for-each loop: for(int number : even_numbers){...} .

In the parenthesis for the loop, we created an integer variable called number which would be used to loop through the even_numbers array.

Iteration #1

number = first element in the array (2). This gets printed out.

Iteration #2

number = second element in the array (4). This current value gets printed out.

Iteration #3

number = third element in the array (6). This current value gets printed out.

Iteration #4

number = fourth element in the array (8). This current value gets printed out.

The value of number keeps changing to the current index during the iteration process until it gets to the end of the array. After each index is printed out, it moves to the next index.

You can also see it this way: "For every number in the even_numbers array, print number )".

Java For-Each Loop Example #2

In the code above, we're multiplying the value of each element by two using the number variable: number = number*2; .

The process here is the same with the last example. When number becomes an element in the array, it doubles the element's value and prints it to the console.

You can use for-each loops in Java to iterate through elements of an array or collection.

They simplify how you create for loops. For instance, the syntax of a for loop requires that you create a variable, a condition that specifies when the loop should terminate, and an increment/decrement value.

With for-each loops, all you need is a variable and the array to be looped through.

But this doesn't mean that you should always go for for-each loops.

for loops give you more control over what happens during the iteration process – controlling and tracking what happens at every index or some indexes.

On the other hand, for-each loops can be used when you have no use for tracking each index. The code just runs through for every element in the array.

You can learn more about for loops in Java by reading this article .

Happy coding!

ihechikara[dot]com

If you read this far, thank the author to show them you care. Say Thanks

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

for-each loop in java can't be used for assignments

Why for-each loop in java can't be used for assignments? For eg I am trying the below example and not getting the expected result but compiles successfully:

Scary Wombat's user avatar

  • 1 Strings are immutable –  Scary Wombat Commented Feb 12, 2016 at 1:33
  • We need to assign the value for obj in each iteration: obj[count] = ob; count++; –  Swaroop Nagendra Commented Feb 12, 2016 at 1:43

3 Answers 3

ob is a local variable which is a copy of the reference in the array. You can alter it but it doesn't alter the array or collection it comes from.

Peter Lawrey's user avatar

Essentially, that is correct. The for-each loop is not usable for loops where you need to replace elements in a list or array as you traverse it

Elliott Frisch's user avatar

As you've noted, you can't use the variable in an array iteration to set the values of the array. In fact your code, while legal, is unusual in iterating through the elements of an array in order to initialise them. As other answers have noted, you are better off using the index of the array.

Even better is to create the array in the process of initialisation. For example, in Java 8 you could use:

This seems to me to capture your intent of creating strings and then turning them into a new array rather than create an array and then iterate through it changing each element.

sprinter's user avatar

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged java or ask your own question .

  • The Overflow Blog
  • Scaling systems to manage all the metadata ABOUT the data
  • Navigating cities of code with Norris Numbers
  • Featured on Meta
  • We've made changes to our Terms of Service & Privacy Policy - July 2024
  • Bringing clarity to status tag usage on meta sites
  • Tag hover experiment wrap-up and next steps

Hot Network Questions

  • Suitable tool bag for vintage centre pull rim brake bike
  • Short story about a committee planning to eliminate 1 in 10 people
  • How to interpret coefficients of logistic regression using natural cubic splines?
  • A study on the speed of gravity
  • Meaning of 折れ込む here
  • Union of lists with original order
  • Returning to France with a Récépissé de Demande de Carte de Séjour stopping at Zurich first
  • How many advancements can a Root RPG character get before running out of options to choose from in the advancement list?
  • Ai-Voice cloning Scam?
  • Can a Statute of Limitations claim be rejected by the court?
  • What are those bars in subway train or bus called?
  • What's the polarity of this electrolytic capacitor symbol?
  • Do space stations have anything that big spacecraft (such as the Space Shuttle and SpaceX Starship) don't have?
  • Does the US Congress have to authorize non-combat deployments (e.g. of advisers and trainers) from the US armed forces to a foreign country?
  • The minimal Anti-Sudoku
  • When would it be legal to ask back (parts of) the salary?
  • Package with environment that changes according to option
  • A post-apocalyptic short story where very sick people from our future save people in our timeline that would be killed in plane crashes
  • Isn't an appeal to emotions in fact necessary to validate our ethical decisions?
  • Erase the loops
  • Unstable output C++: running the same thing twice gives different output
  • Did the Space Shuttle weigh itself before deorbit?
  • Is an invalid date considered the same as a NULL value?
  • How can I obscure branding on the side of a pure white ceramic sink?

assignment for for loop in java

  • DSA with JS - Self Paced
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Operator
  • JS Projects
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter

How to fix SyntaxError – ‘invalid assignment left-hand side in JavaScript’?

In JavaScript, a SyntaxError : Invalid Assignment Left-Hand Side occurs when the interpreter encounters an invalid expression or structure on the left side of an assignment operator ( = ).

This error typically arises when trying to assign a value to something that cannot be assigned, such as literals, expressions, or the result of function calls. Let’s explore this error in more detail and see how to resolve it with some examples.

Understanding an error

An invalid assignment left-hand side error occurs when the syntax of the assignment statement violates JavaScript’s rules for valid left-hand side expressions. The left-hand side should be a target that can receive an assignment like a variable, object property or any array element, let’s see some cases where this error can occur and also how to resolve this error.

Case 1: Error Cause: Assigning to Literals

When you attempt to assign a value to a literal like a number, string or boolean it will result in SyntaxError: Invalid Assignment Left-Hand Side .

Resolution of error

In this case values should be assigned to variables or expressions which will be on the left side of an equation and avoid assigning values directly to literals.

Case 2: Error Cause: Assigning to Function Calls

Assigning a value directly to the result of function call will give an invalid assignment left-hand side error.

Explanation : In this example, getX() returns a value but is not a valid target for assignment. Assignments should be made to variables, object properties, or array elements, not to the result of a function call.

Therefore, store it into a variable or at least place it on the left-hand side that is valid for assignment.

author

Please Login to comment...

Similar reads.

  • Web Technologies

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

IMAGES

  1. Java For Loop with Examples

    assignment for for loop in java

  2. Java For Loop with Examples

    assignment for for loop in java

  3. Bucle Java For con ejemplos

    assignment for for loop in java

  4. Java For Loop Syntax and Example

    assignment for for loop in java

  5. For Loop in Java

    assignment for for loop in java

  6. The For Loop in Java

    assignment for for loop in java

COMMENTS

  1. Java for Loop (With Examples)

    Java for Loop. Java for loop is used to run a block of code for a certain number of times. The syntax of for loop is:. for (initialExpression; testExpression; updateExpression) { // body of the loop } Here, The initialExpression initializes and/or declares variables and executes only once.; The condition is evaluated. If the condition is true, the body of the for loop is executed.

  2. For Loop in Java

    Java for loop provides a concise way of writing the loop structure. The for statement consumes the initialization, condition, and increment/decrement in one line thereby providing a shorter, easy-to-debug structure of looping. Let us understand Java for loop with Examples. Syntax: for (initialization expr; test expr; update exp) {.

  3. Java For Loop

    Example explained. Statement 1 sets a variable before the loop starts (int i = 0). Statement 2 defines the condition for the loop to run (i must be less than 5). If the condition is true, the loop will start over again, if it is false, the loop will end. Statement 3 increases a value (i++) each time the code block in the loop has been executed.

  4. Questions and Exercises in Loops

    Programming Questions and Exercises : Loops. Question 1. Write a program to print numbers from 1 to 10. Show the answer. Question 2. Write a program to calculate the sum of first 10 natural number. Show the answer. Question 3. Write a program that prompts the user to input a positive integer.

  5. Loops in Java

    Comparison for loop while loop do-while loop; Introduction: The Java for loop is a control flow statement that iterates a part of the programs multiple times.: The Java while loop is a control flow statement that executes a part of the programs repeatedly on the basis of given boolean condition.

  6. The for Statement (The Java™ Tutorials > Learning the Java Language

    The for statement provides a compact way to iterate over a range of values. Programmers often refer to it as the "for loop" because of the way in which it repeatedly loops until a particular condition is satisfied. The general form of the for statement can be expressed as follows: for ( initialization; termination ; increment) {.

  7. Java For Loop (with Examples)

    The execution of for-loop flows like this-. First, 'int i = 0' is executed, which declares an integer variable i and initializes it to 0. Then, condition-expression (i < array.length) is evaluated. The current value of I is 0 so the expression evaluates to true for the first time. Now, the statement associated with the for-loop statement is executed, which prints the output in the console.

  8. Loops in Java

    Loops in Java. Looping in programming languages is a feature which facilitates the execution of a set of instructions/functions repeatedly while some condition evaluates to true. Java provides three ways for executing the loops. While all the ways provide similar basic functionality, they differ in their syntax and condition checking time.

  9. For loop in Java with example

    For loop is used to execute a set of statements repeatedly until a particular condition returns false. In Java we have three types of basic loops: for, while and do-while. In this tutorial you will learn about for loop in Java. You will also learn nested for loop, enhanced for loop and infinite for loop with examples. Syntax of for loop:

  10. Java For Loop

    Executing a set of statements repeatedly is known as looping. We have 3 types of looping constructs in Java. These looping statements are also known as iterative statements. 1.while. 2.for. 3.do while. The above three different java loops are used primarily with same purpose and the difference is in their syntax.

  11. Understanding For Loop in Java With Examples and Syntax

    For Loop in Java. As mentioned, Java for loop helps execute a set of code repeatedly, and it is recommended when the number of iterations is fixed. You have seen the syntax of for loop, now try to understand it. Syntax: for (init; condition, incr/decr) {. //statements to be executed or body. }

  12. For Loop in Java

    Usecase 1: Providing expression in for loop is a must. For loop must consist of a valid expression in the loop statement failing which can lead to an infinite loop. The statement. is similar to. Note: This above said is crux of advanced programming as it is origin of logic building in programming. Example.

  13. For Loop in Java + forEach Loop Syntax Example

    A loop in programming is a sequence of instructions that run continuously until a certain condition is met. In this article, we will learn about the for and forEach loops in Java.. Syntax for a for loop in Java. Here is the syntax for creating a for loop:. for (initialization; condition; increment/decrement) { // code to be executed} . Let's break down some of the keywords above.

  14. PDF for-loop

    for-loop. We don't describe the complete for-statement, or for-loop, as it is defined in Java, but just its most used form. The syntax of the for-loop is: for (<initialization> ; <condition> ; <increment> ) <repetend>. where. The <initialization> is an assignment, like k= 0. It is executed at the beginning of the for-statement.

  15. Can we assign a variable for looping to a value inside the loop in Java

    I would like to assign a certain value to an iteration variable inside a for loop in Java. List<Integer> values = Arrays.asList(1,2,4,16,32,64,128); for (Integer value: values) { value = value / 2; // local value } Is this assignment working in java? java; loops; variable-assignment; Share. Improve this question. Follow edited Feb 17, 2020 at 6 ...

  16. For loop in Java 8

    Java 8 added lambda expressions and Stream api. The Stream api java.util.Stream provides a forEach that can be used to loop over collection as shown below : // Java 8 Lambda For loop categories.stream().forEach(category-> System.out.println(category)); Here is the complete example that loops over a list using different for loops :

  17. Nested Loop in Java (With Examples)

    In the above example, the outer loop iterates 3 times and prints 3 weeks. And, the inner loop iterates 7 times and prints the 7 days. We can also create nested loops with while and do...while in a similar way. Note: It is possible to use one type of loop inside the body of another loop. For example, we can put a for loop inside the while loop.

  18. Enhanced For Loops in Java

    Java For-Each Loop Example #1. In the code above, we created an array called even_numbers. To loop through and print all the numbers in the array, we made use of a for-each loop: for(int number : even_numbers){...}. In the parenthesis for the loop, we created an integer variable called number which would be used to loop through the even_numbers ...

  19. Java Assignment Operators with Examples

    Note: The compound assignment operator in Java performs implicit type casting. Let's consider a scenario where x is an int variable with a value of 5. int x = 5; If you want to add the double value 4.5 to the integer variable x and print its value, there are two methods to achieve this: Method 1: x = x + 4.5. Method 2: x += 4.5.

  20. for-each loop in java can't be used for assignments

    For example, in Java 8 you could use: String[] obj = IntStream.range(0, 4).mapToObj(n -> "obj" + n).toArray(); This seems to me to capture your intent of creating strings and then turning them into a new array rather than create an array and then iterate through it changing each element.

  21. For-each loop in Java

    Prerequisite: Decision making in Java For-each is another array traversing technique like for loop, while loop, do-while loop introduced in Java5. It starts with the keyword for like a normal for-loop.; Instead of declaring and initializing a loop counter variable, you declare a variable that is the same type as the base type of the array, followed by a colon, which is then followed by the ...

  22. 7 Best Java Homework Help Websites: How to Choose Your Perfect Match?

    Nowadays, Java assignment help companies provide several ways of communication. In most cases, you can contact your expert via live chat on a company's website, via email, or a messenger. To see ...

  23. How to fix SyntaxError

    This JavaScript exception invalid assignment to const occurs if a user tries to change a constant value. Const declarations in JavaScript can not be re-assigned or re-declared. Message: TypeError: invalid assignment to const "x" (Firefox) TypeError: Assignment to constant variable. (Chrome) TypeError: Assignment to const (Edge) TypeError: Redeclara