Grails Cookbook - A collection of tutorials and examples

Java String Array Initialization

It is a common scenario that we need to manipulate multiple String values. String Array is always a good choice because it is very simple to work with. The first thing we wish to do when working with arrays is to initialize it with values. We will share below some code examples on how to initialize a String Array in Java.

Initialize During Declaration

If we do not initialize, the contents of a String Array are all null values. There are two ways to initialize the values, that is before or after declaring the array. We would typically declare a String Array like this:
String[] testArray = new String[5];
So all the values from testArray[0] to testArray[4] are null. But we can initialize the values during declaration. Below is a code example on how to do this:
String[] testArray = {"Daddy", "Mommy", "Brother", "Sister", "Dog"};
So this declares an array with size 5 and each item has an initial value. That is, if we run this code:
String[] testArray = {"Daddy", "Mommy", "Brother", "Sister", "Dog"};
System.out.println(testArray [0]);
System.out.println(testArray [1]);
System.out.println(testArray [2]);
System.out.println(testArray [3]);
System.out.println(testArray [4]);

Will output:

Daddy
Mommy
Brother
Sister
Dog

Initialize After Declaration

Sometimes it is impossible to initialize the values during declaration. For example, if the values will come externally, like a file. We can initialize a String Array in Java like this:
String[] testArray = new String[5];
testArray[0] = "Daddy";
testArray[1] = "Mommy";
testArray[2] = "Brother";
testArray[3] = "Sister";
testArray[4] = "Dog";
Or if the values are coming from a file, below is an example:
BufferedReader bf = new BufferedReader(new FileReader(new File("testfile.txt")));
String[] testArray = new String[5];
testArray[0] = bf..readLine();
testArray[1] = bf..readLine();
testArray[2] = bf..readLine();
testArray[3] = bf..readLine();
testArray[4] = bf..readLine();