Array declaration and initialization (test1.java)

  Today, I learned one-bit array and two-dimensional array. First, I learned the application of array, initialization of array, copy of array, etc. I don't think there is much difference between arrays and arrays in C\C++, but in JAVA, everyone knows that JAVA is an object-oriented programming language, each object has its own attributes, and an array is an object , so he also has many attributes, such as length, etc. In this way, the loop can be controlled by the method of [object.length], which is more convenient than C\C++.

 

  Without further ado, let's look at the code.

 

1  // Array declaration
 2  // Array initialization and assignment 
3  
4  public  class test1
 5  {
 6      public  static  void main (String [] args)
 7      {
 8          // Declare an array 
9          int [] arr;
 10  
11          // Apply for space in the heap for the array. When applying for space, you must specify the size of the array 
12          arr = new  int [20 ];
 13  
14          // At this time, the elements in the array are all default values ​​0
 15  
16          // for( int i=0 ; i<arr.length ; i++)
 17          //Each array has a length attribute, which is used to obtain the length of the array
 18          // The above loop is not recommended, because the length of the array will be repeatedly obtained, and the time efficiency is low 
19  
20          for ( int i=0,len=arr.length ; i <len ; i++ )
 21          {
 22              // Access each element in the array through the array subscript 
23              System.out.print(arr[i]+"\t" );
 24          }
 25  
26          System.out.println( );
 27  
28          // Assign 29 to each element of the array 
for ( int i=0,len=arr.length ; i<len ; i++ )
 30         {
 31              arr[i] = i+1 ;
 32                   }

 

  From this, it can be seen that the array is indeed an object, which is stored by applying for space in the heap, and the method can be called by ".". I also learned that when declaring an array, you must specify the size of the space requested, that is, the number of elements. If no initialization is performed, all elements will be the default value, which is 0, instead of a random value like C\C++.

 

  To summarize, the declaration of the array is int[] arr = new int[array length] , the initialization of the array is int[] arr = {1,2,3,4,5}, not int[] arr = new int { 1,2,3,4,5} .

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324712781&siteId=291194637