Java String array example

Java String array example shows how to define and initialize Java String array. Example also shows how to add elements and access elements from String array using for loop.

How to define Java String array?

Java String array is a collection of fixed number of Java String objects. You can define String array in below given two methods.

1

String[]strArrayNames=newString[3];

This will define String array of size 3. That means we can add 3 String objects to an array using the index as given below.

1

2

3

strArrayNames[0]="Jay";

strArrayNames[1]="Kumar";

strArrayNames[2]="Roy";

If you have String variable, you can also directly assign it to the array using its index like given below.

1

2

StringstrName="Mike";

strArrayNames[0]=strName;

Important Note: Java array starts from index 0. Since we defined our array’s size as 3, array will have three elements at 0, 1 and 2 index. Accessing index 3 will throw ArrayIndexOutOfBoundsException as given below.

1

2

//This will throw ArrayIndexOutOfBoudsException

strArrayNames[3]="Raj";

If you know the String objects array is going to have at time of array definition, you can directly assign them while defining the String array as given below.

1

String[]strArrayNames=newString[]{"Jay","Kumar","Roy"};

In this case, you do not have to define the size of an array. If you do so, there will be a compilation error.

About the author

rahimv

rahimv has over 15 years of experience in designing and developing Java applications. His areas of expertise are J2EE and eCommerce. If you like the website, follow him on Facebook, Twitter or Google Plus.