Wednesday, November 14, 2012

Declaring a Variable to Refer to an Array

Like declarations for variables of other types, an array declaration has two components: the array's type and the array's name. An array's type is written as type[], where type is the data type of the contained elements; the square brackets are special symbols indicating that this variable holds an array. The size of the array is not part of its type (which is why the brackets are empty). An array's name can be anything you want, provided that it follows the rules and conventions as previously discussed in the naming section. As with variables of other types, the declaration does not actually create an array — it simply tells the compiler that this variable will hold an array of the specified type.
Similarly, you can declare arrays of other types:
byte[] anArrayOfBytes;
short[] anArrayOfShorts;
long[] anArrayOfLongs;
float[] anArrayOfFloats;
double[] anArrayOfDoubles;
boolean[] anArrayOfBooleans;
char[] anArrayOfChars;
String[] anArrayOfStrings;
You can also place the square brackets after the array's name:
// this form is discouraged
float anArrayOfFloats[];
However, convention discourages this form; the brackets identify the array type and should appear with the type designation. Below is an example of converting a date string into Integer Array.
string date_str = "2012/11/06";
String str_arr[] = date_str.split("/");
int[] int_arr = new int[4];
int_arr[0] = Integer.valueOf(str_arr[0]);
System.out.println(int_arr[0]);

No comments:

Post a Comment