Three ways to initialize Java arrays

Source: Internet
Author: User

April 3, 2018

Arrays in the Java language must be initialized before they can be used. Initialization is allocating memory space for array elements of arrays and attaching an initial value to each array element.

Note: After the array is initialized, there is a default value for each element in the memory space for that array:

The default value for the integer type of the base data type (byte, short, int, long) is 0;

The default value for floating-point types (float, double) of the base data type is 0.0;

The default value for the character type (char) of the base data type is ' \u0000 ';

The Boolean type (Boolean) default value for the base data type is false;

The default value of a type's reference type (class, array, interface, String) is null.

=====================================================================

Initialization mode:

Static initialization: The programmer explicitly specifies the initial value of each array element when initializing, and the system determines the length of the array;

1.arrayName = new Type[]{element1,element2,element3 ...}

Example:

Int[] intarr;
Intarr = new int[]{1,2,3,4,5,9};

2. Simplified static initialization mode type[] Arrayname = {element1,element2,element3 ...};

Example:

String[] Strarr = {"John", "Dick", "Wang Er Ma"};

Two. Dynamic initialization: The length of the array is specified by the programmer when initialized, and the default value of each array element is initialized by the system.

Arrayname = new Type[length];

Example:

int[] Price = new INT[4];

Note: Do not use static initialization and dynamic initialization at the same time, that is, do not specify both the length of the array and the initial value for each array element when the array is initialized.

Once the array completes initialization, the space occupied by the array in memory is fixed, so the length of the array is immutable.

            

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.