String[] thisIsAStringArray;Another way of declaring a String Array is to put the square brackers after the name of the variable. For example:
String thisIsAStringArray[];Both statements will declare the variable "thisIsAStringArray" to be a String Array. Note that this is just a declaration, the variable "thisIsAStringArray" will have the value null. And since there is only one square brackets, this means that the variable is only a one-dimensional String Array. Examples will be shown later on how to declare multi-dimensional String Arrays.
String[] thisIsAStringArray = new String[5];This will declare a String Array with 5 elements. Each element can be accessed using index that starts with 0. The fist element is "thisIsAStringArray[0]", the second element is "thisIsAStringArray[1]", and so on. Here is an example of declaring a String Array with size 5 and assigning values to each element:
String[] thisIsAStringArray = new String[5]; thisIsAStringArray[0] = "AAA"; thisIsAStringArray[1] = "BBB"; thisIsAStringArray[2] = "CCC"; thisIsAStringArray[3] = "DDD"; thisIsAStringArray[4] = "EEE";Note, since there are only 5 elements and index started from 0, the last index will be 4. Or we could use the formula ( array length - 1). This means if we access the index greater than 4, an Exception will be raised. Example:
String[] thisIsAStringArray = new String[5]; thisIsAStringArray[5] = "FFF";The code will throw a java.lang.ArrayIndexOutOfBoundsException.
String[] thisIsAStringArray = {"AAA", "BBB", "CCC", "DDD", "EEE"};This will create a String Array of length 5. Element at index 0 will have the value "AAA", element at index 1 will have the value "BBB", and so on. Hence, when we run this code:
String[] thisIsAStringArray = {"AAA", "BBB", "CCC", "DDD", "EEE"}; System.out.println( thisIsAStringArray[0] ); System.out.println( thisIsAStringArray[1] ); System.out.println( thisIsAStringArray[2] ); System.out.println( thisIsAStringArray[3] ); System.out.println( thisIsAStringArray[4] );
It will produce this output:
AAA BBB CCC DDD EEE
Another syntax to declare and initialize a String array together is by using the new operator. Here is an example:
String[] thisIsAStringArray = new String[]{"AAA", "BBB", "CCC", "DDD", "EEE"};The behaviour is the same as the example above: "String[] thisIsAStringArray = {"AAA", "BBB", "CCC", "DDD", "EEE"};"
String[] thisIsAStringArray; if (fruits) { thisIsAStringArray = new String[] {"Apple", "Banana", "Orange"}; } else { thisIsAStringArray = new String[] {"Asparagus", "Carrot", "Tomato"}; }
Note that the value of the array depends on the value of fruits variable. The array can have the values {"Apple", "Banana", "Orange"} if fruits is true, or {"Asparagus", "Carrot", "Tomato"} if fruits is false.
Note that initializing an array will override the old contents of the array. For example
String[] thisIsAStringArray = {"Apple", "Banana", "Orange"}; thisIsAStringArray = new String[] {"Asparagus", "Carrot", "Tomato"}; System.out.println( thisIsAStringArray[0] ); System.out.println( thisIsAStringArray[1] ); System.out.println( thisIsAStringArray[2] );
The code will have the output below. This is because the old contents {"Apple", "Banana", "Orange"}, will be discarded and replaced with the new contents.
Asparagus Carrot TomatoAlso note that even the size of array will be changed if re-initialized. For example:
String[] thisIsAStringArray = {"Apple", "Banana", "Orange"}; thisIsAStringArray = new String[] {"Asparagus", "Carrot"}; System.out.println( thisIsAStringArray[0] ); System.out.println( thisIsAStringArray[1] ); System.out.println( thisIsAStringArray[2] );
Will have the following output:
Asparagus Carrot Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2 at ArrayTest.main(ArrayTest.java:10)The exception is because the thisIsAStringArray variable will only have 2 elements after the second initialization.
String[] thisIsAStringArray = {"Apple", "Banana", "Orange"}; System.out.println( thisIsAStringArray.length );This will have the output:
3Because there are 3 elements in the declared array.
Since the size and contents of a String Array can vary, it is useful to iterate through all the values. Here is an example code using style that can run prior to Java 5.
String[] thisIsAStringArray = {"Apple", "Banana", "Orange"}; for( int i = 0; i < thisIsAStringArray.length; i++) { String element = thisIsAStringArray[i]; System.out.println( element ); }
The code will start from index 0, and continue upto length - 1, which is the last element of the array. This code will run on any version of Java, before of after Java 5
The code will have the output:
Apple Banana Orange
Another way is to use the enhanced for loop of Java 5. For example:
String[] thisIsAStringArray = {"Apple", "Banana", "Orange"}; for( String element:thisIsAStringArray) { System.out.println( element ); }The code will have the same output as the previous example:
String[] thisIsAStringArray = {"Apple", "Banana", "Orange"}; String stringToSearch = "Banana"; boolean found = false; for (String element:thisIsAStringArray) { if ( element.equals( stringToSearch )) { found = true; } } if (found) { System.out.println( "The array contains the string: " + stringToSearch ); } else { System.out.println( "The array does not contains the string: " + stringToSearch ); }
This code will loop through the array and check one by one if an element is equal to the item being searched for. The output of the code will be:
The array contains the string: Banana
We can place a break when we found the item, to make it run faster.
String[] thisIsAStringArray = {"Apple", "Banana", "Orange"}; String stringToSearch = "Banana"; boolean found = false; for (String element:thisIsAStringArray) { if ( element.equals( stringToSearch )) { found = true; break; } } if (found) { System.out.println( "The array contains the string: " + stringToSearch ); } else { System.out.println( "The array does not contains the string: " + stringToSearch ); }
The break will stop the loop when we found an element match. We can also factor this out as a separate method, if this will be a commonly used routine:
public static boolean contains(String[] stringArray, String stringToSearch) { boolean result = false; for (String element:stringArray) { if ( element.equals( stringToSearch )) { result = true; break; } } return result; } public static void main( String[] args ) { String[] thisIsAStringArray = {"Apple", "Banana", "Orange"}; System.out.println( "The array contains the string Apple: " + contains(thisIsAStringArray, "Apple") ); System.out.println( "The array contains the string Carrots: " + contains(thisIsAStringArray, "Carrots") ); }
As shown, the function can be called multiple times because it is re-factored as a utility method. Here is the output of the code:
The array contains the string Apple: true The array contains the string Carrots: false
String[] thisIsAStringArray = {"Apple", "Banana", "Orange"}; String[] tempArray = new String[ thisIsAStringArray.length + 1 ]; for (int i=0; i<thisIsAStringArray.length; i++) { tempArray[i] = thisIsAStringArray[i]; } tempArray[thisIsAStringArray.length] = "Carrots"; thisIsAStringArray = tempArray; for (String element:thisIsAStringArray) { System.out.println( element ); }The example code above started with a String Array of size 3. Another array was created with size larger than 1. The 3 elements were then copied and the new value is added on the last index. The code will print the following result:
Apple Banana Orange Carrots
We can refactor the logic to a separate function. For example:
public static String[] add(String[] stringArray, String newValue) { String[] tempArray = new String[ stringArray.length + 1 ]; for (int i=0; i<stringArray.length; i++) { tempArray[i] = stringArray[i]; } tempArray[stringArray.length] = newValue; return tempArray; } public static void main( String[] args ) { String[] thisIsAStringArray = {"Apple", "Banana", "Orange"}; thisIsAStringArray = add(thisIsAStringArray, "Carrots"); for (String element:thisIsAStringArray) { System.out.println( element ); } }This will have the same output as the previous example.
public static void bubbleSort( String[] arr ) { int j = 0; String tmp; boolean sorted = false; while ( !sorted ) { sorted = true; j++; for ( int i = 0; i < arr.length - j; i++ ) { if (arr[i].compareTo( arr[i + 1] ) > 0) { tmp = arr[i]; arr[i] = arr[i + 1]; arr[i + 1] = tmp; sorted = false; } } } } public static void main( String[] args ) { String[] thisIsAStringArray = { "Banana", "Orange", "Cherry", "Apple", "Pineapple", "Melon", "Plum" }; bubbleSort( thisIsAStringArray ); for ( String element : thisIsAStringArray ) { System.out.println( element ); } }
The code will output the Strings in the array in order alphabetically.
Apple Banana Cherry Melon Orange Pineapple PlumBut since sorting is a common programming problem, Java has a built-in solution for this. We can use the sort method in java.util.Arrays class. Here is a shortened example of our code above using Arrays.sort() method:
public static void main( String[] args ) { String[] thisIsAStringArray = { "Banana", "Orange", "Cherry", "Apple", "Pineapple", "Melon", "Plum" }; Arrays.sort(thisIsAStringArray ); for ( String element : thisIsAStringArray ) { System.out.println( element ); } }And the output will be the same, the alphabetically sorted strings in the array.
String[] thisIsAStringArray = { "Apple", "Banana", "Orange" }; String theString = Arrays.toString( thisIsAStringArray ); System.out.println( theString );
And this will be the output:
[Apple, Banana, Orange]
The elements are separated by comma in the converted String, and enclosed in square brackets. To implement a custom behaviour, we may implement our own code for that:
We may implement our own that uses a custom delimiter without the square brackets. Here is an example of converting String Array to String with custom delimiter:
String[] thisIsAStringArray = { "Apple", "Banana", "Orange" }; String delimiter = "-"; StringBuilder sb = new StringBuilder(); for ( String element : thisIsAStringArray ) { if (sb.length() > 0) { sb.append( delimiter ); } sb.append( element ); } String theString = sb.toString(); System.out.println( theString );
The output will use the delimiter dash without square brackets:
Apple-Banana-OrangeWe can refactor the logic to a separate method. Here is an example of converting a String Array to String using comma delimiter or any other delimiter:
public static String stringArrayToString( String[] stringArray, String delimiter ) { StringBuilder sb = new StringBuilder(); for ( String element : stringArray ) { if (sb.length() > 0) { sb.append( delimiter ); } sb.append( element ); } return sb.toString(); } public static void main( String[] args ) { String[] thisIsAStringArray = { "Apple", "Banana", "Orange" }; String theString = stringArrayToString(thisIsAStringArray, ","); System.out.println( theString ); String theString2 = stringArrayToString(thisIsAStringArray, "="); System.out.println( theString2 ); }
The output will be:
Apple,Banana,Orange Apple=Banana=Orange
One dis-advantage of arrays is that the size is fixed. If we need the size of the array to grow, it is better to use List. Fortunately, this is simple - again by using java.util.Arrays. Here is an example code:
String[] thisIsAStringArray = { "Apple", "Banana", "Orange" }; List<String> stringList = Arrays.asList( thisIsAStringArray );
Note that reading the Javadoc of asList says:
Returns a fixed-size list backed by the specified array. (Changes to the returned list "write through" to the array.) This method acts as bridge between array-based and collection-based APIs, in combination with Collection.toArray. The returned list is serializable and implements RandomAccess.
This means that you can not add items to the List returned by Arrays.asList method. Hence, this code will raise an Exception:
String[] thisIsAStringArray = { "Apple", "Banana", "Orange" }; List<String> stringList = Arrays.asList( thisIsAStringArray ); stringList.add( "WaterMelon" );
When you run this, you will encounter a java.lang.UnsupportedOperationException on the line where "WaterMelon" was being added to the list.
To avoid this problem, we can specifically convert the String Array to an ArrayList. Here is a sample code on how to do that:
String[] thisIsAStringArray = { "Apple", "Banana", "Orange" }; List<String> fixedList = Arrays.asList( thisIsAStringArray ); List<String> stringList = new ArrayList<String>( fixedList ); stringList.add( "WaterMelon" );The code will construct a new ArrayList based on the returned value of Arrays.asList. All items from fixedList will be added to the stringList. And the ArrayList instance has no limitation of being fixed size. Hence, the code that adds "WaterMelon" will not throw any exception.
The difference between a Set and a list is that a Set cannot contain duplicate elements while a List can. So if we only want elements of a collection without duplicates, Set is a more appropriate data structure. Here is a sample code on how to convert a String Array to a Set:
String[] thisIsAStringArray = { "Apple", "Banana", "Orange", "Banana" }; List<String> stringList = Arrays.asList( thisIsAStringArray ); Set<String> stringSet = new HashSet<String>( stringList ); System.out.println( "Size of the list is: " + stringList.size() ); System.out.println( "Size of the set is: " + stringSet.size() );The output will be:
Size of the list is: 4 Size of the set is: 3The list will have four items, as enumerated in declaration. But since there are two Banana's, the set will only have 3 elements.
If we want the opposite behavior of the sample above, it is also possible to convert a List back to String Array. Here is a sample code that converts a List to String Array:
List<String> stringList = new ArrayList<String>(); stringList.add( "Apple" ); stringList.add( "Banana" ); stringList.add( "Orange" ); String[] stringArr = stringList.toArray( new String[] {} ); for ( String element : stringArr ) { System.out.println( element ); }Note that we need to pass an instance of array to the toArray method. This is to tell the list what type of array it should return.
String[][] coupleArray = new String[4][]; coupleArray[0] = new String[] {"John", "Rose"}; coupleArray[1] = new String[] {"Peter", "Abigail"}; coupleArray[2] = new String[] {"Robert", "Josephine"}; coupleArray[3] = new String[] {"Timothy", "Angelina"};
Here, we declared an array of arrays with size 4. We initialize each element with a String Array that represents a pair of husband and wife names.
To access a specific item, we need two index values. For example, to output "Robert", the code should be:
System.out.println( coupleArray[2][0] );
And to access "Josephine", the code should be:
System.out.println( coupleArray[2][1] );Here is an alternative way of creating a two-dimensional String array and initializing it's values:
String[][] coupleArray = new String[4][2]; coupleArray[0][0] = "John"; coupleArray[0][1] = "Rose"; coupleArray[1][0] = "Peter"; coupleArray[1][1] = "Abigail"; coupleArray[2][0] = "Robert"; coupleArray[2][1] = "Josephine"; coupleArray[3][0] = "Timothy"; coupleArray[3][1] = "Angelina";
Here, we can think of it as creating a multi-dimensional array where the first dimension is of size 4, and the second dimension is of size 2. The effect is the same as the first example. Which means accessing elements is also the same.
Here is an even shorter example where we declare and initialize a two-dimensional string array in a single statement:
String[][] coupleArray = { { "John", "Rose" }, { "Peter", "Abigail" }, { "Robert", "Josephine" }, { "Timothy", "Angelina" } };