search
HomeJavajavaTutorialJAVA Tutorial | Chapter 6 Loop Structure

Java Loop Structure

The code in the program is executed sequentially, which means it can only be executed once. If you want to perform the same operation multiple times, the headquarters may copy the code several times! Therefore, a loop structure needs to be used here.

There are three main loop structures in Java:

  • ##while loop

  • do…while loop

  • for loop



##while loop

while is the most basic loop. As long as the condition inside while is true, the while loop will continue. The syntax is as follows
while(true){
        //...
}

Example

public class Test {
   public static void main(String args[]) {
      int x = 15;
      while( x < 20 ) {
         System.out.print("X is : " + x );
         x++;
         System.out.println("");
      }
   }
}
The above example compilation and running results are as follows:

X is  : 15 
X is  : 16 
X is  : 17 
X is  : 18
X is  : 19



do...while loop

do...while loop is the same as while loop. The difference is that the do operation will be executed first, and then it will be judged whether the while condition is true. If it is true, it will continue to execute the do statement. If it is not true, it will exit the loop body. .

Even if the conditions are not met, the execution statement will be executed 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 block of statements executes until the Boolean expression evaluates to false.

Example

public class Test {
   public static void main(String args[]){
      int x = 10;
 
      do{
         System.out.print("值为 : " + x );
         x++;
         System.out.println("");
      }while( x < 20 );
   }
}
The above example compilation and running results are as follows:
值为 : 10
值为 : 11
值为 : 12
值为 : 13
值为 : 14
值为 : 15
值为 : 16
值为 : 17
值为 : 18
值为 : 19



for Loop

Although the loop structure can use while or do...while, Java provides another statement-the for loop, which makes the loop structure 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 about the for loop:

      The initialization step is executed first. A type can be declared, but one or more loop control variables can be 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 a loop, update the loop control variables.
    • 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");
      }
   }
}

以上实例编译运行结果如下: 

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 增强 for 循环

Java5 引入了一种主要用于数组的增强型 for 循环。其实学过C#的同学应该知道,这个和foreach循环是一样的。

Java 增强 for 循环语法格式如下: 

for(声明语句 : 表达式){
   //代码句子
}
声明语句:声明新的局部变量,该变量的类型必须和数组元素的类型匹配。其作用域限定在循环语句块,其值与此时数组元素的值相等。

表达式:表达式是要访问的数组名,或者是返回值为数组的方法。

这个方法一般会用在对象输出的方式上。

实例 


public class Test {
   public static void main(String args[]){
      int [] numbers = {1, 2, 3, 4, 5};
 
      for(int x : numbers ){
         System.out.print( x );
         System.out.print(",");
      }
      System.out.println("");
      String [] names ={"Karl", "DuJinYang", "JiMi", "Lucy"};
      for( String name : names ) {
         System.out.print( name );
         System.out.print(",");
      }
   }
}


以上实例编译运行结果如下: 


10,20,30,40,50,
Karl,DuJinYang,JiMi,Lucy,


break 关键字

break 主要用在循环语句或者 switch 语句中,用来跳出整个语句块。 

break 中文就是结束的意思,顾名思义,就是跳出最里层(当前涵盖)的循环,并且继续执行该循环下面的语句。

语法

break 的用法很简单,就是循环结构中的一条语句: 

break;

实例 


public class Test {
   public static void main(String args[]) {
      int [] numbers = {10, 20, 30, 40, 50};
 
      for(int x : numbers ) {
         // x 等于 30 时跳出循环
         if( x == 30 ) {
            break;
         }
         System.out.print( x );
         System.out.print("\n");
      }
   }
}
以上实例编译运行结果如下:
10
20

continue 关键字

continue ,继续的意思,适用于任何循环控制结构中。作用是让程序立刻跳转到下一次循环的迭代。

在 for 循环中,continue 语句使程序立即跳转到更新语句。

在 while 或者 do…while 循环中,程序立即跳转到布尔表达式的判断语句。

语法

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

嵌套循环

do...while、while、for 循环都是可以相互嵌套的,这里不做过多的演示,大家可以自己去试验一下。

 以上就是JAVA 入坑教程 | 章节六  循环结构体的内容,更多相关内容请关注PHP中文网(www.php.cn)!


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What are the advantages of using bytecode over native code for platform independence?What are the advantages of using bytecode over native code for platform independence?Apr 30, 2025 am 12:24 AM

Bytecodeachievesplatformindependencebybeingexecutedbyavirtualmachine(VM),allowingcodetorunonanyplatformwiththeappropriateVM.Forexample,JavabytecodecanrunonanydevicewithaJVM,enabling"writeonce,runanywhere"functionality.Whilebytecodeoffersenh

Is Java truly 100% platform-independent? Why or why not?Is Java truly 100% platform-independent? Why or why not?Apr 30, 2025 am 12:18 AM

Java cannot achieve 100% platform independence, but its platform independence is implemented through JVM and bytecode to ensure that the code runs on different platforms. Specific implementations include: 1. Compilation into bytecode; 2. Interpretation and execution of JVM; 3. Consistency of the standard library. However, JVM implementation differences, operating system and hardware differences, and compatibility of third-party libraries may affect its platform independence.

How does Java's platform independence support code maintainability?How does Java's platform independence support code maintainability?Apr 30, 2025 am 12:15 AM

Java realizes platform independence through "write once, run everywhere" and improves code maintainability: 1. High code reuse and reduces duplicate development; 2. Low maintenance cost, only one modification is required; 3. High team collaboration efficiency is high, convenient for knowledge sharing.

What are the challenges in creating a JVM for a new platform?What are the challenges in creating a JVM for a new platform?Apr 30, 2025 am 12:15 AM

The main challenges facing creating a JVM on a new platform include hardware compatibility, operating system compatibility, and performance optimization. 1. Hardware compatibility: It is necessary to ensure that the JVM can correctly use the processor instruction set of the new platform, such as RISC-V. 2. Operating system compatibility: The JVM needs to correctly call the system API of the new platform, such as Linux. 3. Performance optimization: Performance testing and tuning are required, and the garbage collection strategy is adjusted to adapt to the memory characteristics of the new platform.

How does the JavaFX library attempt to address platform inconsistencies in GUI development?How does the JavaFX library attempt to address platform inconsistencies in GUI development?Apr 30, 2025 am 12:01 AM

JavaFXeffectivelyaddressesplatforminconsistenciesinGUIdevelopmentbyusingaplatform-agnosticscenegraphandCSSstyling.1)Itabstractsplatformspecificsthroughascenegraph,ensuringconsistentrenderingacrossWindows,macOS,andLinux.2)CSSstylingallowsforfine-tunin

Explain how the JVM acts as an intermediary between the Java code and the underlying operating system.Explain how the JVM acts as an intermediary between the Java code and the underlying operating system.Apr 29, 2025 am 12:23 AM

JVM works by converting Java code into machine code and managing resources. 1) Class loading: Load the .class file into memory. 2) Runtime data area: manage memory area. 3) Execution engine: interpret or compile execution bytecode. 4) Local method interface: interact with the operating system through JNI.

Explain the role of the Java Virtual Machine (JVM) in Java's platform independence.Explain the role of the Java Virtual Machine (JVM) in Java's platform independence.Apr 29, 2025 am 12:21 AM

JVM enables Java to run across platforms. 1) JVM loads, validates and executes bytecode. 2) JVM's work includes class loading, bytecode verification, interpretation execution and memory management. 3) JVM supports advanced features such as dynamic class loading and reflection.

What steps would you take to ensure a Java application runs correctly on different operating systems?What steps would you take to ensure a Java application runs correctly on different operating systems?Apr 29, 2025 am 12:11 AM

Java applications can run on different operating systems through the following steps: 1) Use File or Paths class to process file paths; 2) Set and obtain environment variables through System.getenv(); 3) Use Maven or Gradle to manage dependencies and test. Java's cross-platform capabilities rely on the JVM's abstraction layer, but still require manual handling of certain operating system-specific features.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.