---
title: "JAVA中： for(;;) 与 while(true) 的 区别"
author: "fuliguo"
date: "2015-07-21T14:10:15Z"
tags: []
categories: ["编程语言"]
slug: "java-for-while-true"
draft: false
lastmod: "2015-07-21T14:09:17Z"
id: 2229044
url: "https://fuliguo.iteye.com/blog/2229044"
---

结论：从编译后的字节码文件看，for(;;) 和 while(true) 在底层用的相同的实现，两种写法没有区别。

**1、for(;;)**


```java

@Test
public void test(){


    for(;;){
        System.out.println("for"+"+++");
    }


}
```


编译后的字节码
 
```java
public void test();
   flags: ACC_PUBLIC
   Code:
     stack=2, locals=1, args_size=1
        0: getstatic     #2                  // Field java/lang/System.out:Ljava/io/PrintStream;
        3: ldc           #3                  // String for+++
        5: invokevirtual #4                  // Method java/io/PrintStream.println:(Ljava/lang/String;)V
        8: goto          0
     LineNumberTable:
       line 18: 0
     LocalVariableTable:
       Start  Length  Slot  Name   Signature
              0      11     0  this   Lcom/jj/jingcai/MyTest;
     StackMapTable: number_of_entries = 1
          frame_type = 0 /* same */
   RuntimeVisibleAnnotations:
     0: #17()
```


**2、while(true)**


```java
@Test
public void test(){


    while (true){
        System.out.println("while"+"---");
    }


}
```



编译后的字节码

```java
public void test();
  flags: ACC_PUBLIC
  Code:
    stack=2, locals=1, args_size=1
       0: getstatic     #2                  // Field java/lang/System.out:Ljava/io/PrintStream;
       3: ldc           #3                  // String while---
       5: invokevirtual #4                  // Method java/io/PrintStream.println:(Ljava/lang/String;)V
       8: goto          0
    LineNumberTable:
      line 18: 0
    LocalVariableTable:
      Start  Length  Slot  Name   Signature
             0      11     0  this   Lcom/jj/jingcai/MyTest;
    StackMapTable: number_of_entries = 1
         frame_type = 0 /* same */
  RuntimeVisibleAnnotations:
    0: #17()
```