Square brackets is used to declare an Array in Java. We can use it two ways, one is after the data type keyword, and the other is after the variable name. Here is an example on how to declare an int array in Java:
int[] thisIsAnIntArray1; int thisIsAnIntArray2[];both declaration is valid. Below is the counterpart if we wish to declare an array of Integer:
Integer[] thisIsAnIntegerArray1; Integer thisIsAnIntegerArray2[];All the statements above will have the variables contain null value. No array object is created, the variables are just simply declared without values assigned to them.
int[] thisIsAnIntArray = new int[5]; Integer[] thisIsAnIntegerArray = new Integer[5];
Note that the int array above will not only create the array, but each item will have the value 0. This is because int is a primitive type. The array of Integer however, will have null values for each element, unless initialized later.
We can explicitly initialize the contents of the array:// int int[] thisIsAnIntrray = new int[5]; thisIsAnIntrray[0] = 5; thisIsAnIntrray[1] = 15; thisIsAnIntrray[2] = 25; thisIsAnIntrray[3] = 35; thisIsAnIntrray[4] = 45; // Integer Integer[] thisIsAnIntegerArray = new Integer[5]; thisIsAnIntegerArray[0] = Integer.valueOf(5); thisIsAnIntegerArray[1] = Integer.valueOf(15); thisIsAnIntegerArray[2] = Integer.valueOf(25); thisIsAnIntegerArray[3] = Integer.valueOf(35); thisIsAnIntegerArray[4] = Integer.valueOf(45);
int[] thisIsAnIntArray = {5, 12, 13, 17, 22, 39};
And an example for Java Integer Array:
Integer[] thisIsAnIntegerArray1 = {5, 12, 13}; Integer[] thisIsAnIntegerArray2 = {Integer.valueOf(5), Integer.valueOf(12), Integer.valueOf(13)};
Notice that the first statement uses plain ints. This is because the autoboxing feature of Java will convert an int to Integer automatically.
Another syntax to declare and initialize an Integer array together is by using the new operator. Here is an example:
int[] thisIsAnIntArray = new int[] {5, 12, 13, 17, 22, 39}; Integer[] thisIsAnIntegerArray1 = new Integer[] {5, 12, 13}; Integer[] thisIsAnIntegerArray2 = new Integer[] {Integer.valueOf(5), Integer.valueOf(12), Integer.valueOf(13)};
int[] thisIsAnIntArray; if (isOdd) { thisIsAnIntArray = new int[] {1, 3, 5, 7, 9}; } else { thisIsAnIntArray = new int[] {2, 4, 6, 8, 10}; }
Note that the value of the array depends on the value of isOdd variable.
Note that initializing an array will override the old contents of the array. For example
int[] thisIsAnIntArray = new int[] {1, 3, 5}; thisIsAnIntArray = new int[] {2, 4, 6}; System.out.println( thisIsAnIntArray[0] ); System.out.println( thisIsAnIntArray[1] ); System.out.println( thisIsAnIntArray[2] );
The code will have the output below.
2 4 6
This is because the old contents {1, 3, 5}, will be discarded and replaced with the new contents {2, 4, 6}.
Also note that even the size of array will be changed if re-initialized. For example:
int[] thisIsAnIntArray = new int[] {1, 3, 5}; thisIsAnIntArray = new int[] {2, 4}; System.out.println( thisIsAnIntArray[0] ); System.out.println( thisIsAnIntArray[1] ); System.out.println( thisIsAnIntArray[2] );
Will have the following output:
2 4 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2 at ArrayTest.main(ArrayTest.java:10)The exception is because the thisIsAnIntArray variable will only have 2 elements after the second initialization.
int[] thisIsAnIntArray = new int[] {1, 3, 5}; System.out.println( thisIsAnIntArray.length );This will have the output:
3Because there are 3 elements in the declared int array.
Since the size and contents of an Integer 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.
int[] thisIsAnIntArray = new int[] {1, 3, 5}; for( int i = 0; i < thisIsAnIntArray.length; i++) { int element = thisIsAnIntArray[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:
1 3 5
Another way is to use the enhanced for loop of Java 5. For example:
int[] thisIsAnIntArray = new int[] {1, 3, 5}; for( int element:thisIsAnIntArray) { System.out.println( element ); }The code will have the same output as the previous example:
int[] thisIsAnIntArray = new int[] {1, 3, 5}; int intToSearch = 3; boolean found = false; for (int element:thisIsAnIntArray) { if ( element == intToSearch ) { found = true; } } if (found) { System.out.println( "The array contains the integer: " + intToSearch ); } else { System.out.println( "The array does not contains the integer: " + intToSearch ); }
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 integer: 3
import java.util.Arrays; /** * A Simple Program That Sorts An Integer Array In Java. */ public class SortIntArrayInJava { public static void bubbleSort(int[] arr) { int j = 0; int tmp; boolean sorted = false; while (!sorted) { sorted = true; j++; for (int i = 0; i < arr.length - j; i++) { if (arr[i] > arr[i + 1]) { tmp = arr[i]; arr[i] = arr[i + 1]; arr[i + 1] = tmp; sorted = false; } } } } public static void main(String[] args) { int[] thisIsAnIntArray = { 5, 1, 100, 50, 75, 12, 89, 51, 11, 28, 99 }; bubbleSort(thisIsAnIntArray); System.out.println(Arrays.toString(thisIsAnIntArray)); } }
The code will output the Integers in the array in order ascendingly.
[1, 5, 11, 12, 28, 50, 51, 75, 89, 99, 100]Java has a built-in solution for this common programming problem. We can use the sort method in java.util.Arrays utility class. Here is a shortened example of our code above using Arrays.sort() method:
import java.util.Arrays; /** * A Simple Program That Sorts An Integer Array In Java. */ public class SortIntArrayInJava { public static void main(String[] args) { int[] thisIsAnIntArray = { 5, 1, 100, 50, 75, 12, 89, 51, 11, 28, 99 }; Arrays.sort(thisIsAnIntArray); System.out.println(Arrays.toString(thisIsAnIntArray)); } }And the output will be the same.
import java.util.Arrays; /** * A Simple Program That Converts an Integer Array To String. */ public class ConvertArrayInJava { public static void main(String[] args) { int[] thisIsAnIntArray = { 5, 6, 7, 8 }; String theString = Arrays.toString(thisIsAnIntArray); System.out.println(theString); } }
And this will be the output:
[5, 6, 7, 8]
The elements are separated by comma in the converted String, and enclosed in square brackets.
If you like customized behavior, we can implement the conversion ourselves
/** * A Simple Program That Converts an Integer Array To String With Custom Behavior. */ public class SortIntArrayInJava { public static void main(String[] args) { int[] thisIsAnIntArray = { 5, 6, 7, 8 }; String delimiter = "-"; StringBuilder sb = new StringBuilder(); for ( int element : thisIsAnIntArray ) { 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:
5-6-7-8
Arrays are fixed sized. Hence, working with List is more convenient. Here is an example of how to Convert an int Array to List in Java.
Integer[] thisIsAnIntArray = { 5, 6, 7, 8 }; List<Integer> intList = Arrays.asList( thisIsAnIntArray );
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 adding items to the returned List will raise an exception:
Integer[] thisIsAnIntArray = { 5, 6, 7, 8 }; List<Integer> intList = Arrays.asList( thisIsAnIntArray ); intList.add( Integer.valueOf(10) );
When you run this, you will encounter a java.lang.UnsupportedOperationException.
To avoid this problem, we can specifically convert the Integer Array to an ArrayList. Here is a sample code on how to do that:
Integer[] thisIsAnIntArray = { 5, 6, 7, 8 }; List<Integer> fixedList = Arrays.asList( thisIsAnIntArray ); List<Integer> intList = new ArrayList<Integer>(fixedList); intList.add( Integer.valueOf(10) );The code now will not throw an Exception.
The difference between a Set and a list is that a Set only contains unique values. So if we only want elements of a collection without duplicates (unique), Set is a more appropriate data structure. Here is a sample code on how to convert a Integer Array to a Set:
Integer[] thisIsAnIntArray = { 5, 6, 5, 8 }; List<Integer> intList = Arrays.asList( thisIsAnIntArray ); Set<Integer> intSet = new HashSet<Integer>( intList ); System.out.println( "Size of the list is: " + intList.size() ); System.out.println( "Size of the set is: " + intSet.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 5'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 an Integer Array. Here is a sample code that converts a List to int Array:
List<Integer> intList = new ArrayList<Integer>(); intList.add( 5 ); intList.add( 10 ); intList.add( 15 ); Integer[] intArr = intList.toArray( new Integer[] {} ); for ( Integer element : intArr ) { System.out.println( element ); }