0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Java の for 文が JVM でどう動くか

Posted at

解説

0をスタックに積み、取り出して変数1(sum)へ格納

0: iconst_0
1: istore_1

0をスタックに積み、取り出して変数2(i)へ格納

2: iconst_0
3: istore_2

変数2(i)と5をスタックへ積む
if_icmpge 19 → i >= 5 なら 19 番命令へ跳ぶ

4: iload_2
5: iconst_5
6: if_icmpge     19

変数2(i)を1増やす
4へ跳ぶ

13: iinc          2, 1
16: goto          4

変数1(sum)、変数2(i)をスタックへ積み、足し合わせる
結果を変数1(sum)へ格納

9: iload_1
10: iload_2
11: iadd
12: istore_1

ソース

ForTest.java
public class ForTest {
    public static void main(String[] args) {
        int sum = 0;
        for (int i = 0; i < 5; i++) {
            sum += i;
        }
        System.out.println(sum);
    }
}
testuser@CasaOS:~/jtest$ javac ForTest.java 
testuser@CasaOS:~/jtest$ javap -c ForTest
Compiled from "ForTest.java"
public class ForTest {
  public ForTest();
    Code:
       0: aload_0
       1: invokespecial #1                  // Method java/lang/Object."<init>":()V
       4: return

  public static void main(java.lang.String[]);
    Code:
       0: iconst_0
       1: istore_1
       2: iconst_0
       3: istore_2
       4: iload_2
       5: iconst_5
       6: if_icmpge     19
       9: iload_1
      10: iload_2
      11: iadd
      12: istore_1
      13: iinc          2, 1
      16: goto          4
      19: getstatic     #7                  // Field java/lang/System.out:Ljava/io/PrintStream;
      22: iload_1
      23: invokevirtual #13                 // Method java/io/PrintStream.println:(I)V
      26: return
}

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?