博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
for_Keyword
阅读量:3925 次
发布时间:2019-05-23

本文共 9622 字,大约阅读时间需要 32 分钟。

Java for Loop with Examples

In this quick article, we will discuss for loop with examples. 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.

Table of contents

  • Java for Loop Syntax
  • How for Loop Works
  • Simple for Loop Example
  • Using the Comma
  • The For-Each Version of the for Loop
  • for-each Loop with Break
  • for-each Loop is Essentially Read-Only
  • for-each - Iterating Over Multidimensional Arrays
  • Search an Array Using for-each Style Example
  • Nested for Loops

Java for Loop Syntax

for (initialization; termination;     increment) {    statement(s)}

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.

How for Loop Works (Flow of Execution of the for Loop)

  • First step: In for loop, initialization happens first and only one time, which means that the initialization part of for loop only executes once.

  • Second step: Condition in for loop is evaluated on each iteration, if the condition is true then the statements inside for loop body gets executed. Once the condition returns false, the statements in for loop does not execute and the control gets transferred to the next statement in the program after for loop.

  • Third step: After every execution of for loop’s body, the increment/decrement part of for loop executes that updates the loop counter.

  • Fourth step: After the third step, the control jumps to the second step and condition is re-evaluated.

Simple for Loop Example
package net.javaguides.corejava.controlstatements.loops;public class ForLoopExample {    public static void main(String args[]) {        // here, n is declared inside of the for loop        for (int n = 10; n > 0; n--)            System.out.println("tick " + n);    }}

Output:

tick 10tick 9tick 8tick 7tick 6tick 5tick 4tick 3tick 2tick 1

Note that we have declared a loop control variable inside the a for loop. When you declare a variable inside a for loop, there is one important point to remember: the scope of that variable ends when the for statement does.

When the loop control variable will not be needed elsewhere, most Java programmers declare it inside the for. For example, here is a simple program that tests for prime numbers. Notice that the loop control variable, i , is declared inside the for since it is not needed elsewhere.

package net.javaguides.corejava.controlstatements.loops;public class ForLoopFindPrime {    public static void main(String args[]) {        int num;        boolean isPrime;        num = 14;        if (num < 2)            isPrime = false;        else            isPrime = true;        for (int i = 2; i <= num / i; i++) {            if ((num % i) == 0) {                isPrime = false;                break;            }        }        if (isPrime)            System.out.println("Prime");        else            System.out.println("Not Prime");    }}

Output:

Not PrimeUsing the Comma

There will be times when we will want to include more than one statement in the initialization and iteration portions of the for loop. For example, consider the loop in the following program:

package net.javaguides.corejava.controlstatements.loops;public class ForLoopComma {    public static void main(String args[]) {        int a, b;        for (a = 1, b = 4; a < b; a++, b--) {            System.out.println("a = " + a);            System.out.println("b = " + b);        }    }}

Output:

a = 1b = 4a = 2b = 3

In this example, the initialization portion sets the values of both a and b. The two commas separated statements in the iteration portion are executed each time the loop repeats.

The For-Each Version of the for Loop

Beginning with JDK 5, the second form of for was defined that implements a “for-each” style loop. Enhanced for loop is useful when you want to iterate Array/Collections, it is easy to write and understand.

Syntex

for(type itr-var : collection) statement-block

Here, type specifies the type and itr-var specifies the name of an iteration variable that will receive the elements from a collection, one at a time, from beginning to end.

Here is an entire program that demonstrates the for-each version:

package net.javaguides.corejava.controlstatements.loops;public class ForEachExample {    public static void main(String args[]) {        int nums[] = {            1,            2,            3,            4,            5,            6,            7,            8,            9,            10        };        int sum = 0;        // use for-each style for to display and sum the values        for (int x: nums) {            System.out.println("Value is: " + x);            sum += x;        }        System.out.println("Summation: " + sum);    }}

Output:

Value is: 1Value is: 2Value is: 3Value is: 4Value is: 5Value is: 6Value is: 7Value is: 8Value is: 9Value is: 10Summation: 55

for-each Loop with Break

It is possible to terminate the loop early by using a break statement. For example, this program sums only the first five elements of nums:

package net.javaguides.corejava.controlstatements.loops;public class ForEachWithBreak {    public static void main(String args[]) {        int sum = 0;        int nums[] = {            1,            2,            3,            4,            5,            6,            7,            8,            9,            10        };        // use for to display and sum the values        for (int x: nums) {            System.out.println("Value is: " + x);            sum += x;            if (x == 5)                break; // stop the loop when 5 is obtained        }        System.out.println("Summation of first 5 elements: " + sum);    }}

Output:

Value is: 1Value is: 2Value is: 3Value is: 4Value is: 5Summation of first 5 elements: 15

for-each Loop is Essentially Read-Only

There is one important point to understand about the for-each style loop. Its iteration variable is “read-only” as it relates to the underlying array. An assignment to the iteration variable has no effect on the underlying array. In other words, we can’t change the contents of the array by assigning the iteration variable a new value.

For example, consider this program:

package net.javaguides.corejava.controlstatements.loops;public class ForEachNoChange {    public static void main(String args[]) {        int nums[] = {            1,            2,            3,            4,            5,            6,            7,            8,            9,            10        };        for (int x: nums) {            System.out.print(x + " ");            x = x * 10; // no effect on nums        }        System.out.println();        for (int x: nums)            System.out.print(x + " ");        System.out.println();    }}

Note that the first for loop increases the value of the iteration variable by a factor of 10. However, this assignment has no effect on the underlying array nums, as the second for loop illustrates.

for-each - Iterating Over Multidimensional Arrays

The enhanced version of the for also works on multidimensional arrays. The following program uses the for-each style for a two-dimensional array:

package net.javaguides.corejava.controlstatements.loops;public class ForEachMultidimensionalArrays {    public static void main(String args[]) {        int sum = 0;        int nums[][] = new int[3][5];        // give nums some values        for (int i = 0; i < 3; i++)            for (int j = 0; j < 5; j++)                nums[i][j] = (i + 1) * (j + 1);        // use for-each for to display and sum the values        for (int x[]: nums) {            for (int y: x) {                System.out.println("Value is: " + y);                sum += y;            }        }        System.out.println("Summation: " + sum);    }}

Output:

Value is: 1Value is: 2Value is: 3Value is: 4Value is: 5Value is: 2Value is: 4Value is: 6Value is: 8Value is: 10Value is: 3Value is: 6Value is: 9Value is: 12Value is: 15Summation: 90

Search an Array Using for-each Style Example

The following program uses a for each loop to search an unsorted array for a value. It stops if the value is found.

package net.javaguides.corejava.controlstatements.loops;public class ForEachSearchArray {    public static void main(String args[]) {        int nums[] = {            6,            8,            3,            7,            5,            6,            1,            4        };        int val = 5;        boolean found = false;        // use for-each style for to search nums for val        for (int x: nums) {            if (x == val) {                found = true;                break;            }        }        if (found)            System.out.println("Value found!");    }}

Output:

Value found!

The for-each style for is an excellent choice in this application because searching an unsorted array involves examining each element in a sequence.

Nested for Loops

Java allows loops to be nested. That is, one loop may be inside another. For example, here is a program that nests for loops:

package net.javaguides.corejava.controlstatements.loops;public class NestedForLoops {    public static void main(String args[]) {        int i, j;        for (i = 0; i < 10; i++) {            for (j = i; j < 10; j++)                System.out.print(".");            System.out.println();        }    }}

Output:

.......................................................

转载地址:http://ibgrn.baihongyu.com/

你可能感兴趣的文章
HashMap的负载因子初始值为什么是0.75?这篇文章以最通俗的方式告诉你答案
查看>>
详解java中一个面试常问的知识点-阻塞队列
查看>>
除了Thread和Runnable,你还知道第三种创建线程的方式Callable吗
查看>>
java线程面试题集锦(第一版本)
查看>>
记一次java中三元表达式的坑(避免踩坑)
查看>>
面试官:如何实现一个乐观锁(小白都能看得懂的代码)
查看>>
CopyOnWriteArrayList,一个面试中经常问到的冷门容器
查看>>
设计模式之桥接模式
查看>>
设计模式之组合模式
查看>>
java网络编程(1)基础知识点总结
查看>>
java网络编程(2)Socket编程案例(TCP和UDP两种)
查看>>
设计模式之享元模式
查看>>
深入分析java中的多态原理(jvm角度分析)
查看>>
SpringBoot系列(1)基础入门和案例
查看>>
设计模式之命令模式
查看>>
springBoot系列(2)整合MongoDB实现增删改查(完整版)
查看>>
java关键字(6)void
查看>>
面试必问:java中String对象为什么要设计成不可变的呢?
查看>>
深入分析java中的反射机制
查看>>
java集合类(7)Stack
查看>>