Coding Raptor

Programmers' Nest

You are here: Home / java / core-java / Looping Construct: for Loop

March 15, 2016

Looping Construct: for Loop

The for statement, popularly called for loop is the most often used looping construct in Java. A for loop is used to iterate over a range of values.

Structure of for Loop

The general structure of for statement is as follows –


for (initializationExpression, 
terminationExpression, 
modificationExpression) {

// code block of the loop

}

As seen above, the constituents of a for statement are –
1. initializationExpression – this expression is evaluated exactly once. It typically initializes any variable that controls the execution of the loop.
2. terminationExpression – the loop is executed as long as this expression evaluates to true. This expression is evaluated at the beginning of each iteration.
3. modificationExpression – this expression is evaluated at the end of each iteration. This expression typically modifies the value of variable that controls execution of loop.
4. Loop’s code block – the set of statements that are executed in an iteration.

All three expressions of the for loop are optional. You can omit one or more of these expressions without causing syntax errors. For example, the code below demonstrates an infinite loop – again using our favorite example of class Politician.

Infinite loop
Java
1
2
3
4
5
6
7
8
9
10
public class Politician {
 
  public void rob() {
    // an infinite loop
    // no initialization, modification or termination conditions
    for ( ; ; ) {
      depositInSwissAcounts();
    } // end of for loop's code block
  }
}

 

Enhanced for Loop

  1. The enhanced for loop was introduced in Java 5.
  2. This is used for iterating over Arrays and Collections. Any class that implements Iterable can be used in an enhanced for loop.
  3. This is a readonly loop. You can not modify the  variable that has been read.
  4. Wherever possible prefer enhanced for loop over traditional for loop

The enhanced for loop is a convenience feature to read (and only read) elements of an array or a collection. The general form of the enanced for loop is –


for ( Type anElement : collectionOfElements) {

// anElement is available for reading

// can use anElement to change contents of object referenced to

// but the collection itself cannot be changed

}

And here is a small demo of our Politician reading all his bank accounts –

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// an array of all bank accounts of a politician
BankAccount[] politiciansAccounts;
 
// assume the Interpol has filled the above array for us
 
for (BankAccount anAccount : politiciansAccounts) {
  // one by one all accounts appear as anAccount
  // each iteration has different account in anAccount
 
  // can read anAccount
  // can change the properties of object referenced by anAccount
  // even assign null to it
  // but cannot make anAccount disappear from the array
 
  // do something about the account
}
....

 

We are social

Spread the word
Facebooktwittergoogle_plusredditpinterestlinkedintumblrmailFacebooktwittergoogle_plusredditpinterestlinkedintumblrmail

Follow CodingRaptor
Facebooktwittergoogle_plusrssFacebooktwittergoogle_plusrss
Post Views: 57

Share with your friends on other avenues:

  • Twitter
  • Facebook
  • Google
  • Reddit
  • Pinterest
  • Tumblr
  • Print
  • LinkedIn
  • Email
  • More
  • Pocket
  • Skype

Related

Article by P T / core-java, java Leave a Comment

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Also Check These Out!

  • Factors in R
  • Basic Data Structures V: Arrays in R
  • Basic Data Structures IV: Lists in R
  • Basic Data Structures III: Data Frames in R
  • Basic Data Structures II: Matrices in R
  • Basic Data Structures I: Vectors in R
  • Atomic or Basic Data Types and Scalars in R
  • Getting Started with R: Packages, Help & Workspace (Part 2)
  • Getting Started with R: Installing and Running R (Part 1)
  • Floating-Point in Java: Representation, Comparison, Equality & A Few Shockers
  • Java Ternary Operator a.k.a Conditional Operator
  • Arrays In JavaScript
  • Coding Raptor Turns 1
  • Java EnumMap with Example
  • LinkedHashMap Example: LRU Cache Implementation
  • LinkedHashMap with Example
  • Java TreeMap with Example
  • Java Collections: Java HashMap Internals
  • Java HashMap with Example
  • Java Map
  • Java Collections: EnumSet with Example
  • Java Collections: Problem Solving with Java Sets
  • Java Collections: Differences between TreeSet, LinkedHashSet and HashSet
  • Java Collections: Sets
  • Using Lists in Java
  • Java Collections: Using Lists
  • Java Collections: Interfaces
  • Java Collections: General Overview
  • Debugging in Netbeans
  • Learn Basics of Core Java in 49 Lessons
  • Varargs in Java
  • Exceptions in Java VIII: Creating Custom Exceptions
  • Exceptions in Java VII: throw and throws in Java
  • Exceptions in Java VI: Types and Hierarchy
  • Exceptions in Java V: try with Resources
  • Exceptions in Java IV: Summary of Rules for try-catch-finally
  • Exceptions in Java iii: Control Flow and Multiple try, catch, finally
  • Exceptions in Java II: try, catch, finally
  • Exceptions in Java I: Introduction
  • Strings in Java VI: More String Methods
  • String in Java V: The intern Method
  • String in Java IV: Important String Methods
  • Strings in Java III: StringBuilder and StringBuffer
  • Strings in Java II: Immutability
  • Strings in Java I: What is a String?
  • Arrays in Java V: Iteration
  • Arrays in Java IV: Manipulating Individual Elements
  • Arrays in Java III: Multidimensional Arrays
  • Arrays in Java II: Declaring, Initializing, Instantiating Arrays
  • Arrays in Java I: What is an Array?
  • Using Environment Variables as Inputs
  • Command Line Arguments in Java
  • static import in Java
  • The import Statement in Java
  • Packages in Java
  • Non Access Modifiers in Java III: abstract, transient, volatile, native
  • Non Access Modifiers in Java II: final, synchronized
  • Non Access Modifiers in Java I: static and strictfp
  • Access Modifiers in Java
  • Looping Construct: for Loop
  • Looping Construct: while and do-while
  • Statements, Expressions and Code Blocks
  • Operators in Java
  • Conditional Statements in Java
  • Reference Data Types
  • Literals in Java
  • Primitive Data Types in Java
  • Variables in Java
  • Compiling and Running Java from Command Line
  • First Java Program: Hello World!
  • Java IDEs and Editors III: Sublime Text and Editplus
  • Java IDEs and Editors II: Eclipse IDE
  • Java IDEs and Editors I: Netbeans
  • Setting up Java Development Environment
  • Java’s Program Execution Model and WORA: Compilation & Interpretation
  • Inside JVM 101: What does JVM do and Memory Areas
  • JVM, JRE, JDK and JIT explained
  • Features of Java and White Paper Buzzwords
  • Beginning Java: History in Brief
Facebooktwittergoogle_plusrssFacebooktwittergoogle_plusrss

Copyright © 2017 · Coding Raptor

loading Cancel
Post was not sent - check your email addresses!
Email check failed, please try again
Sorry, your blog cannot share posts by email.