May 10, 2020
Estimated Post Reading Time ~

Initialize String[] Array in Java

How to initialize String[] in Java.
There are multiple ways to initialize a String Array in JAVA.

Some are illustrated below.

1.Inside Braces
String names[] = {"John","Smith","Doe"};

2.Post Declaration
String names[];
names = new String[] {"John","Smith","Doe"};

3.Using index numbers post declaration
String[] names= new String[3];
names[0] = "John";
names[1] = "Smith";
names[2] = "Doe";

Some Common Mistakes:
You should never try to initialize a String array in JAVA like this.

ISSUE 1:
String names[];
names ={"John","Smith","Doe"};
This results in an error because this is an initialization expression that can be used only to create new arrays and NOT for assigning values to an array. You should use method 2 in this case.

ISSUE 2:
String[] names;
names[0] = "John";
This results in an exception as we need to first allocate memory to the String[] so that it can have an actual memory location pointed by the index "0". Method 3 is the solution in this case.


By aem4beginner

No comments:

Post a Comment

If you have any doubts or questions, please let us know.