Java loop structure - for, while and do...while
The program statements of the sequence structure can only be executed once. If you want to perform the same operation multiple times, you need to use a loop structure.
There are three main loop structures in Java:
while loop
do...while loop
for loop
in Java5 Introduced an enhanced for loop primarily for arrays.
while loop
while is the most basic loop. Its structure is:
while( 布尔表达式 ) { //循环内容 }
As long as the Boolean expression is true, the loop body will continue to execute.
Example
public class Test { public static void main(String args[]) { int x = 10; while( x < 20 ) { System.out.print("value of x : " + x ); x++; System.out.print("\n"); } } }
The compilation and running results of the above example are as follows:
value of x : 10 value of x : 11 value of x : 12 value of x : 13 value of x : 14 value of x : 15 value of x : 16 value of x : 17 value of x : 18 value of x : 19
do...while loop
For the while statement, if the condition is not met, then Cannot enter the loop. But sometimes we need to execute it at least once even if the conditions are not met.
do…while loop is similar to while loop. The difference is that do…while loop will be executed at least once.
do { //代码语句 }while(布尔表达式);
Note: The Boolean expression is after the loop body, so the statement block has been executed before detecting the Boolean expression. If the Boolean expression evaluates to true, the statement block is executed until the Boolean expression evaluates to false.
Example
public class Test { public static void main(String args[]){ int x = 10; do{ System.out.print("value of x : " + x ); x++; System.out.print("\n"); }while( x < 20 ); } }
The compilation and running results of the above example are as follows:
value of x : 10 value of x : 11 value of x : 12 value of x : 13 value of x : 14 value of x : 15 value of x : 16 value of x : 17 value of x : 18 value of x : 19
for loop
Although all loop structures can use while or do...while means, but Java provides another statement-the for loop, which makes some loop structures simpler.
The number of times the for loop is executed is determined before execution. The syntax format is as follows
for(初始化; 布尔表达式; 更新) { //代码语句 }
There are several instructions for the for loop:
The initialization step is executed first. One or more loop control variables can be declared and initialized, or it can be an empty statement.
Then, detect the value of the Boolean expression. If true, the loop body is executed. If it is false, the loop terminates and execution of the statements following the loop body begins.
After executing the loop once, update the loop control variable.
Detect Boolean expression again. Perform the above process in a loop.
Example
public class Test { public static void main(String args[]) { for(int x = 10; x < 20; x = x+1) { System.out.print("value of x : " + x ); System.out.print("\n"); } } }
The compilation and running results of the above example are as follows:
value of x : 10 value of x : 11 value of x : 12 value of x : 13 value of x : 14 value of x : 15 value of x : 16 value of x : 17 value of x : 18 value of x : 19
Java enhanced for loop
Java5 introduces an enhanced type mainly used for arrays for loop.
Java enhanced for loop syntax format is as follows:
for(声明语句 : 表达式) { //代码句子 }
Declaration statement: declare a new local variable. The type of the variable must match the type of the array element. Its scope is limited to the loop statement block, and its value is equal to the value of the array element at this time.
Expression: The expression is the name of the array to be accessed, or a method that returns an array.
Example
public class Test { public static void main(String args[]){ int [] numbers = {10, 20, 30, 40, 50}; for(int x : numbers ){ System.out.print( x ); System.out.print(","); } System.out.print("\n"); String [] names ={"James", "Larry", "Tom", "Lacy"}; for( String name : names ) { System.out.print( name ); System.out.print(","); } } }
The compilation and running results of the above example are as follows:
10,20,30,40,50, James,Larry,Tom,Lacy,
break keyword
break is mainly used in loop statements or switch statements. Jump out of the entire statement block.
break jumps out of the innermost loop and continues to execute the statements below the loop.
语法
break的用法很简单,就是循环结构中的一条语句:
break;
实例
public class Test { public static void main(String args[]) { int [] numbers = {10, 20, 30, 40, 50}; for(int x : numbers ) { if( x == 30 ) { break; } System.out.print( x ); System.out.print("\n"); } } }
以上实例编译运行结果如下:
10 20
continue关键字
continue适用于任何循环控制结构中。作用是让程序立刻跳转到下一次循环的迭代。
在for循环中,continue语句使程序立即跳转到更新语句。
在while或者do…while循环中,程序立即跳转到布尔表达式的判断语句。
语法
continue就是循环体中一条简单的语句:
continue;
实例
public class Test { public static void main(String args[]) { int [] numbers = {10, 20, 30, 40, 50}; for(int x : numbers ) { if( x == 30 ) { continue; } System.out.print( x ); System.out.print("\n"); } }
以上实例编译运行结果如下:
10 20 40 50
以上就是【java教程】Java循环结构 - for, while 及 do...while的内容,更多相关内容请关注PHP中文网(www.php.cn)!

This article analyzes the top four JavaScript frameworks (React, Angular, Vue, Svelte) in 2025, comparing their performance, scalability, and future prospects. While all remain dominant due to strong communities and ecosystems, their relative popul

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

Node.js 20 significantly enhances performance via V8 engine improvements, notably faster garbage collection and I/O. New features include better WebAssembly support and refined debugging tools, boosting developer productivity and application speed.

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

Iceberg, an open table format for large analytical datasets, improves data lake performance and scalability. It addresses limitations of Parquet/ORC through internal metadata management, enabling efficient schema evolution, time travel, concurrent w

This article addresses the CVE-2022-1471 vulnerability in SnakeYAML, a critical flaw allowing remote code execution. It details how upgrading Spring Boot applications to SnakeYAML 1.33 or later mitigates this risk, emphasizing that dependency updat

This article explores integrating functional programming into Java using lambda expressions, Streams API, method references, and Optional. It highlights benefits like improved code readability and maintainability through conciseness and immutability

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Atom editor mac version download
The most popular open source editor
