Skip to content

Instantly share code, notes, and snippets.

@VijayKrishna
Last active December 18, 2015 19:39
Show Gist options
  • Save VijayKrishna/5834992 to your computer and use it in GitHub Desktop.
Save VijayKrishna/5834992 to your computer and use it in GitHub Desktop.
Finding out the semantic differences between different parts of the code can be too easy. Check out the README.md for this Gist to find out the back story behind this Gist and "How are array object created when using a bracketed list" :)

In this gist I quickly showcase the differences between the following three code snippets:
int[] array = new int[] {10, 20, 30};
int[] array = {10, 20, 30};
int[] array = new int[3]; array[0] = 10; array[1] = 20; array[3] = 30;

I do this by disassembling the class files for those code snippets (which i obtain after compiling them). This arose due to a question that was asked on stackoverflow about their difference: http://stackoverflow.com/questions/17245450/how-are-array-object-created-when-using-a-bracketed-list

I also do this for:

String str = new String("Hello");```
public class ArrayTest extends java.lang.Object{
public ArrayTest();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."<init>":()V
4: return
public static void main1();
Code:
0: iconst_3
1: newarray int
3: astore_0
4: aload_0
5: iconst_0
6: bipush 10
8: iastore
9: aload_0
10: iconst_1
11: bipush 20
13: iastore
14: aload_0
15: iconst_3
16: bipush 30
18: iastore
19: return
public static void main2();
Code:
0: iconst_3
1: newarray int
3: dup
4: iconst_0
5: bipush 10
7: iastore
8: dup
9: iconst_1
10: bipush 20
12: iastore
13: dup
14: iconst_2
15: bipush 30
17: iastore
18: astore_0
19: return
public static void main3();
Code:
0: iconst_3
1: newarray int
3: dup
4: iconst_0
5: bipush 10
7: iastore
8: dup
9: iconst_1
10: bipush 20
12: iastore
13: dup
14: iconst_2
15: bipush 30
17: iastore
18: astore_0
19: return
}
public class ArrayTest {
public static void main1() {
int[] array = new int[3]; array[0] = 10; array[1] = 20; array[3] = 30;
}
public static void main2() {
int[] array = new int[] {10, 20, 30};
}
public static void main3() {
int[] array = {10, 20, 30};
}
}
public static void main4();
Code:
0: ldc #2; //String Hello
2: astore_0
3: return
public static void main5();
Code:
0: new #3; //class java/lang/String
3: dup
4: ldc #2; //String Hello
6: invokespecial #4; //Method java/lang/String."<init>":(Ljava/lang/String;)V
9: astore_0
10: return
class Test {
public static void main4() {
String str = "Hello"; // no 'new' statement here
}
public static void main5() {
String str = new String("Hello");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment