How to declare a dimension array:
Type var[]; or type[] var;
When declaring an array, you cannot specify its length (the number of elements in the array).
In Java, you use the keyword new to create an array object in the following 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 performed separately from the assignment of the space and assignment to a set of values;
2. Static initialization: Allocates space and assigns values to the array elements while defining the numbers;
3. Default initialization: An array is a reference type and its elements are equivalent to the member variables of the class, so after the array allocates space, each element is also initialized by the hermit according to the rules 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 (4,5);
- days[1] = new Date (2,31);
- days[2] = new Date (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 (1, +), 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]);
- }
- }
Java Array Declaration, initialization