Thursday, 28 January 2016

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.


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.


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.

No comments:

Post a Comment

Coder Magnet
CoderMagnet is full of resources from our daily development activities. It has solutions for common problematic scenarios in technologies like Java 8, AEM, JCR and also occasionally gives you tips on Blogger as well.