How do I declare and initialize an array in Java?

Spread the love

Question Description

How do I declare and initialize an array in Java?

Practice As Follows

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 initialising is useful when you declare the array first and then initialise it. Cast is necessary here.

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

For more examples, see the documentation page.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.