Friday, 30 June 2017

How do I declare and initialize an array in Java?



How do I declare and initialize an array in Java?


Answer



You can either use array declaration or array literal (but only when you declare and affect the variable right away, array literals cannot be used for re-assigning an array).



For primitive types:




int[] myIntArray = new int[3];
int[] myIntArray = {1, 2, 3};
int[] myIntArray = new int[]{1, 2, 3};


For classes, for example String, it's the same:



String[] myStringArray = new String[3];
String[] myStringArray = {"a", "b", "c"};

String[] myStringArray = new String[]{"a", "b", "c"};


The third way of initializing is useful when you declare the array first and then initialize it. The cast is necessary here.



String[] myStringArray;
myStringArray = new String[]{"a", "b", "c"};

No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...