Skip to content

Instantly share code, notes, and snippets.

@v6ak
Last active November 23, 2022 14:39
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 v6ak/43361894260f784a31958a3bc63324a6 to your computer and use it in GitHub Desktop.
Save v6ak/43361894260f784a31958a3bc63324a6 to your computer and use it in GitHub Desktop.
Proof that var in Java infers compile-time; backslashes in filenames are a workaround for Gist subdirectory limitations
% find -type f -name '*.class' | xargs sha256sum | sort
688244b446cd64a016c33ff7178e939ccd1455fd55d0896175b1ded6aab4cc39 ./String/Main.class
688244b446cd64a016c33ff7178e939ccd1455fd55d0896175b1ded6aab4cc39 ./var/Main.class
74ff1fd1fcb36ca7db9882de59cee2dd69f104c42f21d1790fd10abe3839822b ./Object/Main.class
public class Main{
public static void main(String...args) {
final Object x = "hello world";
System.out.println(x);
}
}
# comments are mine
~/exp% /usr/lib/jvm/java-19/bin/javap -cp var -c Main
Compiled from "Main.java"
public class Main {
public Main();
Code:
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String...);
Code:
# load System.out
0: getstatic #7 // Field java/lang/System.out:Ljava/io/PrintStream;
# put String constant “hello world" to operand stack (don't use any variable slot)
3: ldc #13 // String hello world
# call println(String)
5: invokevirtual #15 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
8: return
}
public class Main{
public static void main(String...args) {
final String x = "hello world";
System.out.println(x);
}
}
# comments are mine
~/exp% /usr/lib/jvm/java-19/bin/javap -cp Object -c Main # It would be the same for exp, as the class files are exactly the same
Compiled from "Main.java"
public class Main {
public Main();
Code:
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String...);
Code:
# put String constant “hello world" to variable slot #1
0: ldc #7 // String hello world
2: astore_1
# load System.out
3: getstatic #9 // Field java/lang/System.out:Ljava/io/PrintStream;
# load variable slot #1
6: aload_1
# call println(Object) (not println(String) like with String or var
7: invokevirtual #15 // Method java/io/PrintStream.println:(Ljava/lang/Object;)V
10: return
}
public class Main{
public static void main(String...args) {
final var x = "hello world";
System.out.println(x);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment