Compiled Counting Examples
Simple Counting
class CountingSimple { public static void count(int from, int to, int step) { int counter = from; while (counter < to) { counter = counter + step; } } }
Bytecode:
public static void count(int, int, int); Code: 0: iload_0 1: istore_3 2: iload_3 3: iload_1 4: if_icmpge 14 7: iload_3 8: iload_2 9: iadd 10: istore_3 11: goto 2 14: return LineNumberTable: line 3: 0 line 4: 2 line 5: 7 line 7: 14 LocalVariableTable: Start Length Slot Name Signature 0 15 0 from I 0 15 1 to I 0 15 2 step I 2 13 3 counter I }
Counting with Printing
class Counting { public static void count(int from, int to, int step) { int counter = from; while (counter < to) { counter = counter + step; System.out.println("counter = " + counter); } } }
Bytecode:
public static void count(int, int, int); Code: 0: iload_0 1: istore_3 2: iload_3 3: iload_1 4: if_icmpge 39 7: iload_3 8: iload_2 9: iadd 10: istore_3 11: getstatic #2; //Field java/lang/System.out:Ljava/io/PrintStream; 14: new #3; //class java/lang/StringBuilder 17: dup 18: invokespecial #4; //Method java/lang/StringBuilder."<init>":()V 21: ldc #5; //String counter = 23: invokevirtual #6; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder; 26: iload_3 27: invokevirtual #7; //Method java/lang/StringBuilder.append:(I)Ljava/lang/StringBuilder; 30: invokevirtual #8; //Method java/lang/StringBuilder.toString:()Ljava/lang/String; 33: invokevirtual #9; //Method java/io/PrintStream.println:(Ljava/lang/String;)V 36: goto 2 39: return LineNumberTable: line 3: 0 line 4: 2 line 5: 7 line 6: 11 line 8: 39 LocalVariableTable: Start Length Slot Name Signature 0 40 0 from I 0 40 1 to I 0 40 2 step I 2 38 3 counter I }