One-dimensional array declaration method:
Type var []; or type [] var;
When declaring an array, you cannot specify its length (number of elements in the array ),
In Java, use the keyword new to create an array object in the format:
Array name = new array element type [number of array elements]
Instance:
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]);
- }
- }
- }
Initialization:
1. Dynamic initialization: the array definition is separated from the operations for allocating space and assigning values to arrays;
2. Static initialization: when defining numbers, allocate space for array elements and assign values;
3. Default initialization: The array is a reference type, and its elements are equivalent to member variables of the class. Therefore, after the array is allocated space, each element is also initialized by the hermit according to the rules of the member variables.
Instance:
Testd. Java (dynamic ):
Program code:
- Public ClassTestd
- {
- Public Static VoidMain (string ARGs []) {
- IntA [];
- A =New Int[3];
- A [0] = 0;
- A [1] = 1;
- A [2] = 2;
- Date days [];
- Days =NewDate [3];
- Days [0] =NewDate (, 5 );
- Days [1] =NewDate (, 31 );
- Days [2] =NewDate (, 4 );
- }
- }
-
- ClassDate
- {
- IntYear, month, day;
- Date (IntYear,IntMonth,IntDay ){
- 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 (, 42), new time (, 54), new time (, 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 ClassTestdefault
- {
- Public Static VoidMain (string ARGs []) {
- IntA [] =New Int[5];
- System. Out. println ("" + A [3]);
- }
- }