Java Learning Journey Basics: Arrays and reference types memory allocations

Source: Internet
Author: User

In the previous article, we have learned about arrays, which are reference types, and this article details the memory allocation of arrays and other knowledge points. arrays are used to store data of the same data type, and once the initialization is complete, the occupied space is fixed, even if an element is emptied, but its space remains, so the length of the array cannot be changed . When you define only one array variable (int[] numbers), the variable does not point to any valid memory, so you cannot specify the length of the array, only the arrays are initialized (the array element allocates memory space) before it can be used. array initialization is divided into static initialization (The value of the array element is specified at the time of definition and the array length cannot be specified) and dynamic initialization (Specify only the array length, the system assigns the initial value).

Static initialization int[] numbers = new int[] {3, 5, 12, 8, 7}; String[] names = {"Miracle", "Miracle He"};//using a simplified form of static initialization
Dynamic initialization int[] numbers = new INT[5]; string[] names = new string[2];

It is recommended that you do not mix static initialization with dynamic initialization, that is, do not specify both the length of the array and the value of each element. When the initialization is complete, the array elements can be accessed by index location (0~array.length-1). When dynamic initialization is used, if no value is specified at the corresponding index bit, the system specifies the default value corresponding to the corresponding data type (integer 0, floating point number 0.0, character ' \u0000 ', Boolean type false, reference type is null).

public class Testarray {public    static void Main (string[] args) {        string[] names = new string[3];        Names[0] = "Miracle";        NAMES[1] = "Miracle He";        The following code outputs Miracle Miracle He null        /* for        (int i = 0; i < names.length;i++) {            System.out.print (Names[i] + "") ;        }        *        ///You can also use foreach to traverse for        (String name:names) {            System.out.print (name + "");    }}}

Note:There is no foreach keyword in Java and its syntax is for a for (type Item:items), but foreach can only be used to traverse the value of an element and cannot be changed , and must be implemented using for.

public class Testforeach {public    static void Main (string[] args) {        int[] numbers = {3, 5, 8, 7};        for (int number:numbers) {            int num = number *;            System.out.print (num + ",");        }        System.out.println ("");        The numbers is still unchanged (if the for is changed)        for (int i = 0;i < numbers.length;i++) {            System.out.print (Numbers[i] + ",");        }    }}

The above is a simple introduction to the initialization and application of the array, followed by a detailed description of the array (array references and arrays of elements) in memory in the form of storage. First , it is concluded that the array reference variable is stored in the stack memory (stack), the array element is stored in the heap memory (heap) , through the stack in the memory of the pointer to the corresponding element in the heap in the memory of the location to achieve access, since the description of the array at this time the form of storage.

What is stack memory and heap memory? I give an example to explain. When executing a method, the method establishes its own memory stack, which is used to add the variables defined in the method to the memory stack one by one, and the memory stack of the method is destroyed when the execution ends, we say that all the variables are stored in the stack memory, that is, with the extinction of the hosting body, and when we create an object, This object is saved in the run-time data area for reuse (because of the high cost of creation) and does not die at the end of the execution method, but it can also be referenced by other objects, and only when the object is not referenced by any reference variable, the garbage collection is recycled at the appropriate point in time. We say that the runtime data area that the variable points to is present in heap memory.

Only type-compatible (that is, the same data-type system and adherence to the low-to-high principle) can pass an array reference to another array reference, but still cannot change the array length (just the point of adjusting the pointer to the array reference).

public class Testarraylength {public    static void Main (string[] args) {        int[] numbers = {3, 5, n};        int[] digits = new INT[4];        SYSTEM.OUT.PRINTLN ("Digits array length:" + digits.length);//4        for (int number:numbers) {            System.out.print (number +), ");//3,5,12,        }        System.out.println (" ");        for (int digit:digits) {            System.out.print (digit + ",");//0,0,0,0,        }        System.out.println ("");        digits = numbers;        SYSTEM.OUT.PRINTLN ("Digits array length:" + digits.length);//3    }}

Although the seemingly digits array length seems to change from 4 to 3, it is only numbers and digits point to the same array, and digits itself loses the reference and becomes garbage, waiting for garbage collection to be recycled (but its length is still 4), but its internal operating mechanism as shown.

So when we look at an array (or other reference variables), we usually see two parts: the array reference variable and the group element itself, and the data element is stored in the heap memory and can only be accessed through the array reference variable.

From the example above, we can see that the array holds the base type, but it also holds the reference type in the array. The memory distributions that store the basic types are explained, and the memory distributions that store reference types are relatively complex. See a very simple procedure.

public class Testprimitivearray {public    static void Main (string[] args) {        //1. Define array        int[] numbers;        2. Allocating memory space        numbers = new int[4];        3. Specify the value for the array element for        (int i = 0;i < numbers.length;i++) {            Numbers[i] = i * TEN;        }}    }

Memory distribution by the above steps:

It can be seen that the array elements are stored directly in the heap memory, while manipulating the array elements is actually a variable that operates on the underlying type. Next look at a program:

Class Person {public    int: age;    public String name;    public void display () {        System.out.println (name +) is: "+ age";    }} public class Testreferencearray {public    static void Main (string[] args) {        //1. Define array        person[] persons;        2. Allocating memory space        persons = new PERSON[2];        3. The array element specifies the value person        p1 = new Person ();        P1.age =;        P1.name = "Miracle";        person P2 = new person ();        P2.age = +;        P2.name = "Miracle He";        Persons[0] = p1;        Persons[1] = p2;        The value of the output element for        (person p:persons) {            p.display ();}}    }

For an array element to be a reference type in memory where the storage is not the same as the base type, the array element still holds the reference, pointing to another piece of memory where valid data is stored.

When it comes to this, I don't know if I have any friends to ask: What is a multidimensional array of Java? My answer is: can have. Why is it? From the bottom, array elements can hold reference types, including arrays. That is, the array element can also contain an array (such as int[][] numbers = new int[length][]), that is, a two-dimensional array can be treated as a one-dimensional array (array length), you can also specify the length of multiple dimensions (such as int[][] Matrix = new Int[length][width]), but at least the left-most array length must be specified. Thus we conclude that: any multidimensional Array (dimension n,n>1) is treated as a one-dimensional array whose array elements are n-1-dimensional arrays
public class Testmultiarray {public    static void Main (string[] args) {        //1. Define a two-dimensional array        int[][] numbers;        2. Allocating memory space        numbers = new int[3][];        Numbers can be treated as a one-dimensional array for the for        (int i = 0;i < numbers.length;i++) {            System.out.print (Numbers[i] + ",");//null, Null,null        }        System.out.println ("");        3. Specify a value for the array element        numbers[0] = new int[2];        NUMBERS[0][1] = 1;        for (int i = 0;i < numbers[0].length;i++) {            System.out.print (Numbers[0][i] + ",");//0,1        }}}    
Finally, a brief introduction to the static methods of arrays (under Java.util): BinarySearch, CopyOf, Copyofrange, equals, fill, sort, tostring, and so on (see JDK for specific usage).
Import Java.util.arrays;public class Testarrays {public    static void Main (string[] args) {        int[] a = {3, 4, 5, 6};        int[] B = {3, 4, 5, 6};        System.out.println ("A and B are equal:" + arrays.equals (A, b));//true        System.out.println ("5 in a position:" + arrays.binarysearch (A, 5)); /2        int[] C = arrays.copyof (A, 6);        System.out.println ("A and C are equal:" + arrays.equals (A, c));//false        System.out.println ("element of C:" + arrays.tostring (c)); /3,4,5,6,0,0        Arrays.fill (C, 2, 4, 1);//assigns the 3rd to 5th Element (not included) in C to 1        System.out.println ("element of C:" + arrays.tostring (c)); /3,4,1,1,0,0        Arrays.sort (c);        System.out.println ("element of C:" + arrays.tostring (c));//0,0,1,1,3,4    }}

Next, we give an example of the actual scenario of two arrays.

Import Java.util.arrays;public class Numbertormb {private string[] numbers = {"0", "one", "II", "three", "Restaurant", "WU", "Lu", "Qi",    "Ba", "JIU"};    Private string[] units = {"Pick up", "Bai", "Thousand"}; /** * Divides a floating-point number into an integer part and a fractional part * @param number of floating-point numbers to be split * @return an array of strings consisting of integers and fractional parts */private string[] Divide (d        Ouble number) {Long Zheng = (long) number;        Long Xiao = Math.Round ((number-zheng) * 100);    return new string[] {zheng + "", String.valueof (Xiao)}; }/** * Convert a four-bit numeric string to four-bit RMB uppercase String * @param str four-bit string to convert * @return four-bit RMB uppercase String */private string Tormbstri        Ng (String str) {String money = "";            for (int i = 0, Len = str.length (), i < Len; i++) {int num = Str.charat (i)-48;            if (i! = len-1 && num! = 0) {money + = Numbers[num] + units[len-2-i];            } else {money + = Numbers[num];    }} return money; } public static void Main (string[] Args) {NUMBERTORMB RMB = new NUMBERTORMB ();        System.out.println (Arrays.tostring (Rmb.divide (2346.789)));    System.out.println (rmb.tormbstring ("2346")); }}
Import java.io.*;p Ublic class Wzq {//define a two-dimensional array as the chessboard private string[][] board;    Define checkerboard size private static int board_size = 15;        Initialize the chessboard private void Initboard () {board = new String[board_size][board_size]; for (int i = 0, i < board_size; i++) {for (int j = 0; J < Board_size; J + +) {Board[i][j] =            "+"; }}}//print the Chessboard private void Printboard () {for (int i = 0; i < board_size; i++) { T j = 0; J < Board_size;            J + +) {System.out.print (board[i][j]);        } System.out.println ("");        }}//start playing chess public void play () throws Exception {Initboard ();        Printboard ();        Get keyboard input BufferedReader br = new BufferedReader (new InputStreamReader (system.in));        String input = null;                Do {if (input! = null) {string[] pos = Input.split (",");        int x = Integer.parseint (pos[0]);        int y = integer.parseint (pos[1]);                BOARD[X-1][Y-1] = "";            Printboard ();        } System.out.print ("Please enter the coordinates of your chess (in the form of X, y):");    } while ((input = Br.readline ()) = null);            public static void Main (string[] args) throws Exception {wzq wzq = new Wzq ();    Wzq.play (); }}

The conversion of digital into RMB capital program, using a one-dimensional array to represent capital and units; in Gobang Games, a two-dimensional array is used to represent the chessboard. You can see from the program that throws exception does not handle any exceptions and will continue to be explained in subsequent chapters.

Java Learning Journey Basics: Arrays and reference types memory allocations

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.