Java Array Initialization

Source: Internet
Author: User

There are two ways to initialize a 1.Java array :

Static initialization: the programmer assigns values to each element of an array when initializing it;

Dynamic initialization: when an array is initialized, the programmer only specifies the length of the array, and the system assigns an initial value to each element.

 public static void main (String[] args) {
     //static Initialization array: Method one
   String cats[] = new string[] {"Tom", "Sam", "Mimi"  };
       //Static Initialization array: Method two
  string dogs[] = {"Jimmy", "Gougou", "Doggy"};      
  //dynamic initialization of data
   String books[] = new string[2];
  books[0] = "thinking in Java";
  books[1] = "effective Java";      
  
  system.out.println (cats.length);
  system.out.println (dogs.length);
  system.out.println (books.length);
 } The
Java array is a reference data type. An array variable is not an array itself, but a pointer to an array object stored in the heap memory. Therefore, you can change the array referenced by an array variable. Look at the following code:

public static void Main (string[] args) {
Static initialization array: Method one
String cats[] = new string[] {"Tom", "Sam", "Mimi"};
Static initialization array: Method two
String dogs[] = {"Jimmy", "Gougou", "Doggy"};
Dynamic initialization of data
String books[] = new STRING[2];
Books[0] = "thinking in Java";
BOOKS[1] = "effective Java";
Cats = dogs;
Books = dogs;
}
2. Whether an array must be initialized

The key to this problem is to figure out the difference between array variables and arrays of objects. The array variable is stored in the stack memory, and the array object is stored in the heap memory. An array variable is simply a reference variable that can point to the actual array object.

The so-called array initialization is not the initialization of a logarithmic set of variables, but the initialization of arrays of objects.

Java Array Initialization

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.