while_Keyword

Java while Loop with Examples

In this quick article, we will learn how to use while loop with examples. The while loop is Java’s most fundamental loop statement. It repeats a statement or block while its controlling expression is true.

Table of contents

  • How while Loop Works?
  • Simple while Loop Example
  • The while Loop with No Body
  • Infinite while Loop
    Syntex
while(condition) {
// body of a loop
}

The condition can be any Boolean expression. The body of the loop will be executed as long as the conditional expression is true. When the condition becomes false, control passes to the next line of code immediately following the loop. The curly braces are unnecessary if only a single statement is being repeated.

1. How while Loop works?

In while loop, a condition is evaluated first and if it returns true then the statements inside while loop execute. When condition returns false, the control comes out of a loop and jumps to the next statement after while loop.

2. Simple while Loop Example

Here is a while loop that counts down from 10, printing exactly ten lines of “tick”:

package net.javaguides.corejava.controlstatements.loops;

public class WhileLoopExample {
    public static void main(String args[]) {
        int n = 10;
        while (n > 0) {
            System.out.println("tick " + n);
            n--;
        }
    }
}

Output:

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

3. The while Loop with No Body

The body of the while (or any other of Java’s loops) can be empty. This is because a null statement (one that consists only of a semicolon) is syntactically valid in Java. For example, consider the following program:

package net.javaguides.corejava.controlstatements.loops;

public class WhileLoopNoBody {
    public static void main(String args[]) {
        int i, j;
        i = 100;
        j = 200;
        // find midpoint between i and j
        while (++i < --j)
        ; // no body in this loop
        System.out.println("Midpoint is " + i);
    }
}

Output:

Midpoint is 150

4. Infinite while Loop

If you pass true in the while loop, it will be an infinite while loop.
Syntax:

while(true){  
//code to be executed  
} 

Example:

public class WhileExample {
    public static void main(String[] args) {
        while (true) {
            System.out.println("infinitive while loop");
        }
    }
}

Output:

infinitive while loop
infinitive while loop
infinitive while loop
infinitive while loop
infinitive while loop

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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值