Explore Courses Blog Tutorials Interview Questions
0 votes
in Java by (10.2k points)

I want to declare and initialize an array in JAVA, how can I do that?

1 Answer

0 votes
by (46k points)

To declare your array either use this syntax:

<elementType>[] <arrayName>;

or use this one:

<elementType> <arrayName>[];


int intArray[];

//intArray will store some integer value

int []intArray;

To Initialize your array, use this for primitive types:

int[] myIntArray = new int[4];

int[] myIntArray = {2, 3, 4};

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

for strings replace int by a string in the above code:

String[] myStringArray = new String[4];

String[] myStringArray = {"q", "w", "e"};

String[] myStringArray = new String[]{"q", "w", "e"};

In case you want to declare the array first and then initialize it:

String[] myStringArray;

myStringArray = new String[]{"q", "w", "e"};

Related questions

0 votes
1 answer
asked Mar 11, 2021 in Java by Jake (7k points)
0 votes
1 answer
asked Oct 23, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer

Browse Categories