How do I declare an array in Java?
You can either use array declaration or array literal (but only when you declare and affect the variable right away, array literals can not be used for re-assigning an array).
For primitive types :
int[] myIntArray = new int[3];
int[] myIntArray = {1,2,3};
int[] myIntArray = new int[]{1,2,3};
For Objects, like Strings :
String[] myStringArray = new String[3];
String[] myStringArray = {"a","b","c"};
String[] myStringArray = new String[]{"a","b","c"};
Alternatively,
// Either method works
String arrayName[] = new String[10];
String[] arrayName = new String[10];
That declares an array called arrayName
of size 10 (you have elements 0 through 9 to use).
There are a various ways in which you can declare an array in Java:
float floatArray[]; //initialize later
int[] integerArray = new int[10];
String[] array = new String[] {"a", "b"};
You can find more information on the Sun Tutorial site and the JavaDoc.
Type[] variableName = new Type[capacity];
Type[] variableName = {comma-delimited values};
Type variableName[] = new Type[capacity];
is also valid, but I prefer the brackets after the type, because it's easier to see that the variable's type is actually an array.
I find its helpful if you understand each part:
Type[] name = new Type[5];
Type[] is the type of the variable called name. The keyword 'new' says to allocate memory for the new array. The number between the bracket says how large it will be and how much memory to allocate.
You can also create arrays with the values already there, such as
int[] name = {1, 2, 3, 4, 5};
which not only creates the empty space but fills it with those values.
Also, in case you want something more dynamic there is the List interface. This will not perform as well, but is more flexible:
List listOfString = new ArrayList();
listOfString.add("foo"); listOfString.add("bar");
String value = listOfString.get(0);
assertEquals( value, "foo" );