This article describes several related aspects of the Java array, describing the declaration, creation, and initialization of the Java array, and giving its corresponding code.
the declaration mode of one-dimensional array : type var[]; or type[] var;
You cannot specify its length (the number of elements in an array) when declaring an array.
In Java, use the keyword new to create an array object in the form of: Array name = new array element type [number of array elements]
Example: Testnew.java:
Program code:
public class Testnew
{public
static void Main (String args[]) {
int[] s;
int i;
s = new int[5];
for (i = 0; i < 5; i++) {
s[i] = i;
}
for (i = 4; I >= 0; i--) {
System.out.println ("" + s[i]);
}
Class
1. Dynamic initialization: The array definition is separated from the operation of the Arrays allocation space and assignment;
2. Static initialization: Assigning space and assigning values to array elements while defining numbers;
3. Default initialization: An array is a reference type and its elements are equivalent to a class's member variable, so after the array allocates space, each element is also initialized by the hermit according to the rule of the member variable.
Instance:
Testd.java (Dynamic):
Program code:
public class TESTD
{public
static void Main (String args[]) {
int a[];
A = new int[3];
A[0] = 0;
A[1] = 1;
A[2] = 2;
Date days[];
days = new Date[3];
Days[0] = new Date (2008,4,5);
DAYS[1] = new Date (2008,2,31);
DAYS[2] = new Date (2008,4,4);
}
Class Date
{
int year,month,day;
Date (int year, int month, int day) {
this.year = year;
This.month = month;
This.day = day;
}
Tests.java (Static):
Program code:
public class TestS
{public
static void Main (String args[]) {
int a[] = {0,1,2};
Time times [] = {new Time (19,42,42), New Time (1,23,54), New Time (5,3,2)}}
Class time
{
int hour,min,sec;
Time (int hour, int min, int sec) {
this.hour = hour;
this.min = min;
This.sec = sec;
}
}
Testdefault.java (default):
Program code:
public class Testdefault
{public
static void Main (String args[]) {
int a [] = new int [5];
System.out.println ("" + a[3]);
}
The above is on the Java array declaration, create, initialize the example explanation, hope everybody can understand, to everybody's study to be helpful.