Skip to content

Instantly share code, notes, and snippets.

@prathik
Last active November 16, 2018 19:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save prathik/7cf16d8da3e59b1fed5c0cd5085c0ef3 to your computer and use it in GitHub Desktop.
Save prathik/7cf16d8da3e59b1fed5c0cd5085c0ef3 to your computer and use it in GitHub Desktop.
class Test {
    static boolean val = false;

    public static void main() {
        if (!val) {
            System.out.println("Test");
        }
    }
}

Generates

class test.Test {
  static boolean val;

  test.Test();
    Code:
       0: aload_0
       1: invokespecial #1                  // Method java/lang/Object."<init>":()V
       4: return

  public static void main();
    Code:
       0: getstatic     #2                  // Field val:Z
       3: ifne          14
       6: getstatic     #3                  // Field java/lang/System.out:Ljava/io/PrintStream;
       9: ldc           #4                  // String Test
      11: invokevirtual #5                  // Method java/io/PrintStream.println:(Ljava/lang/String;)V
      14: return

  static {};
    Code:
       0: iconst_0
       1: putstatic     #2                  // Field val:Z
       4: return
}

And declaring val as final

class Test1 {
    static final boolean val = false;

    public static void main() {
        if (!val) {
            System.out.println("Test");
        }
    }
}
```java

Generates

```Compiled from "Test1.java"
class test.Test1 {
  static final boolean val;

  test.Test1();
    Code:
       0: aload_0
       1: invokespecial #2                  // Method java/lang/Object."<init>":()V
       4: return

  public static void main();
    Code:
       0: getstatic     #3                  // Field java/lang/System.out:Ljava/io/PrintStream;
       3: ldc           #4                  // String Test
       5: invokevirtual #5                  // Method java/io/PrintStream.println:(Ljava/lang/String;)V
       8: return
}

The extra ifne check is not done in the latter byte code as the compiler knows val is always false.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment