Zero basis of Java syntax -- definition and use of array

Java series article directory

Write once,Runanywhere.???

This article explains arrays. The knowledge explained from this article is different from that of C language.

?? ?? ?? If you think my article is helpful to you, please also [focus on praise collection]. Getting your support is my biggest motivation!!!
?? ?? ??

Copyright notice: This article was originally created by [] and launched in CSDN. If you need to reprint it, please contact the blogger.
Copyright notice: This article is the original article of CSDN blogger, "", which follows the CC 4.0 BY-SA copyright agreement. For reprint, please attach the source link of the original text and this notice.

??? New knowledge begins???

Article catalogue

1. Definition of array

Array concept: a collection of elements of the same type.
In Java, an array is a contiguous space that stores a collection of the same element types.

2. Creation and initialization of array

2.1 creation of array

T [] array name = new T[N];

T: Represents the type of element stored in the array
T []: indicates the type of array
N: Represents the length of the array
new keyword: an array is an object created on the heap

2.2 initialization of array

The initialization of arrays is mainly divided into dynamic initialization and static initialization. Note that arrays are on the heap as objects.

2.2.1 dynamic initialization

When creating an array, directly specify the number of elements in the array
The following examples are the creation and initialization of arrays:

  //dynamic initialization
        int[] arr1 = new int[5];
        double[] arr2 = new double[5];
        String[] arr3 = new String[5];

2.2.2 static initialization

When creating an array, you do not directly specify the number of data elements, but directly specify the specific data content
Generally, when statically initializing an array, we will omit new T [] and abbreviate it into the following syntax format
Syntax format: T [] array name = {data1,data2,...,datan};
The following examples are the creation and initialization of arrays:

 //initiate static
        int[] array1 = new int[]{1,2,3,4,5};
        double[] array2 = new double[]{1.0,2.0,3.0,4.0};
        String[] array3 = new String[]{"hello","java"};

2.2.3 null

null represents an empty reference in Java, that is, a reference that does not point to any object.
The function of NULL is similar to NULL (NULL pointer) in C language, which indicates an invalid memory location Therefore, no read or write operations can be performed on this memory A NullPointerException is thrown once an attempt is made to read or write
There is no agreement in Java that null has any association with the memory of address 0

 int[] arr = null;
        System.out.println("arr:"+arr);
        System.out.println(arr.length);//Because arr does not point to any object, arr.length will be exception

Operation results:

2.2.4 some instructions

  • For static initialization, although the length of the array is not specified during initialization, the compiler will determine the length of the array according to the number of elements in {} during compilation

  • During static initialization, the data type in {} must be consistent with the data type before []

  • Arrays can also be created according to the following number of C languages. It is not recommended. See the following comparison:

    //Create integer variable
    int a = 10; // The variable name is a and the variable type is int
    //Create array: create in C language
    int arr [] ={1,2,3,4,5};// The array name arr can easily lead to the misunderstanding that the array type is int type

  • Static and dynamic initialization can also be divided into two steps, but new T [] cannot be omitted

    //Static
    int[] array9;
    array9 = new int[5];
    //Dynamic
    int[] array10;
    array10 = new int[]{1,2,3,4,5};

  • If the array is not initialized, the elements in the array have their default values - > if the element type stored in the array is a basic type, the default value is the default value corresponding to the basic type, such as:

type

Default value

byte

0

short

0

int

0

long

0

float

0.0f

double

0.0

char

/u0000

boolean

false

3. Access and print of array

3.1 array access by subscript

Array access: array name [subscript]
Array length: array name length
Example: for loop traversal array

public static void main(String[] args) {
        int[] arr = {1,2,3,4,5,6,7,8,9,10};
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i]+" ");
        }
    }

Note: when the number does not point to any object - > null, an error will be reported when calculating the length of the array object.

 public static void main(String[] args) {
        int[] arr = null;
        System.out.println(arr.length);
    }

Operation results:

3.2 array printing

Printing with subscript:

public static void main(String[] args) {
        int[] arr = {1,2,3,4,5,6,7,8,9,10};
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i]+" ");
        }
    }

for each print: for (type variable name: array name) {print statement} does not use subscripts. Read the elements from the array in turn and put them into the variables before:.

 public static void main(String[] args) {
        int[] arr ={1,2,3,4,5};
        for(int x:arr){
            System.out.print(x+" ");
        }
    }

In order to better operate Arrays, Java provides a series of methods in the tool class Arrays:

import java.util.Arrays;//Import package
 In order to let us operate arrays better, we provide a series of methods, which are in the tool class Arrays among
    public static void main(String[] args) {
        int[] arr = {1,2,3,4,5};
        String ret = Arrays.toString(arr);The array you pass in is output in the form of string tostring The return type of is String type
        System.out.println(ret);
    }

Operation results:

4. Reference type

Array reference type

3.1 memory distribution of initial JVM

Memory is a continuous space, which is mainly used to store the data when the program is running.
1. When the program is running, the code needs to be loaded into memory
2. The intermediate data generated by program operation shall be stored in memory
3. The constants in the program should also be saved
4. Some data may need to be stored for a long time, while some data will be destroyed after the method runs
Let's look at the division of different regions within the JVM:

PC register: it is only a small space to save the address of the next instruction to be executed
Virtual machine stack: some information related to method call. When each method is executed, it will first create a stack moving frame. The stack frame contains: local variable table, operand stack, dynamic link, return address and other information. It saves some information related to method execution. For example: local variables. When the method runs, the stack frame is destroyed, that is, the data saved in the stack frame is also destroyed.
Native method stack: the function of local method stack is similar to that of virtual machine stack, except that the saved content is the local variable of native method. In some versions of JVMs (such as HotSpot), local method stack and virtual machine stack are together.
Heap: the largest memory area managed by the JVM. Objects created with new are saved on the heap (for example, the previous new int[]{1,2,3,4,5}). The heap is created when the program starts running and destroyed when the program exits. As long as the data in the heap is still in use, it will not be destroyed.
Method area: used to store class information, constants, static variables, code compiled by the real-time compiler and other data that have been loaded by the virtual machine. The bytecode compiled by the method is saved in this area
Now we only care about the heap and virtual machine stack, which will be described in detail in the subsequent JVM.

3.2 differences between basic type variables and reference type variables

Variables created by basic data types are called basic variables, and their corresponding values are directly stored in the variable space;
Variables created by referencing data types are generally referred to as object references, and their space stores the address of the space where the object is located
The following is an example:

  public static void main(String[] args) {
        int a = 10;
        int b = 20;
        int[] array = {1,2,3,4,5};
        System.out.println(a);
        System.out.println(b);
        System.out.println("array:"+array);
        }

Operation results:

In the above code, a, b and arra are variables inside the main function, so their space is allocated in the stack frame corresponding to the main method.
a. b is a basic type variable, so its space saving is the value initialized to the variable.
Array is a reference variable of array type, and its internal contents can be simply understood as the corresponding address of the array in the heap space (which can be understood as the first address).
Look at the following figure:

**As can be seen from the above figure, the reference variable does not directly store the object itself, which can be simply understood as storing the starting address of the object in the heap space. Through this address, the reference variable can operate on the object** It is a bit similar to the pointer in C language, but the operation of reference in Java is simpler than that of pointer.

Look at the following code:

  public static void main(String[] args) {
        int[] arr1 = new int[3];
        arr1[0] = 10;
        arr1[1] = 20;
        arr1[2] = 30;
        
        int[] arr2 = new int[]{1,2,3,4,5};
        arr2[0] = 100;
        arr2[1] = 200;
        
        arr1=arr2;
        arr1[2] = 300;
        arr1[3] = 400;
        arr1[4] = 500;
        for (int i = 0; i < arr2.length; i++) {
            System.out.println(arr2[i]);
        }
    }

Analysis process and operation results:

4. Usage scenario of array

4.1 saving data

        int[] arr = {1,2,3,4,5};
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i]+" ");
        }

4.2 parameters as functions

4.2.1 basic data type transfer parameters

Basic data type parameter passing means that the basic type is passed into the called method as an argument.

 public static void fuc(int b){
        b = 20;
    }
    public static void main(String[] args) {
        int a = 10;
        fuc(a);
        System.out.println(a);
    }

Operation results:

Because a is a local variable in the main method. In the main method stack frame, b is a local variable in the fuc method. In the fuc method stack frame, when fuc is called in the main method, b is a temporary copy of A. after the fuc call, the fuc method stack frame is destroyed, and the value of a has not changed.

4.2.2 reference type transfer parameters

Look at the following code:

  public static void func1(int[] array) {
        array = new int[]{1,2,3};
    }
    public static void func2(int[] array) {
        array[0] = 99;
    }

    public static void main(String[] args) {
        int[] array = {9,8,7};
        func1(array);
        for (int i = 0; i < array.length; i++) {
            System.out.print(array[i]+ " ");
            System.out.println();
        }
        System.out.println("===========");
        func2(array);
        for (int i = 0; i < array.length; i++) {
            System.out.print(array[i]+ " ");
        }
        System.out.println();
    }

Operation results:


Summary:
1. In Java, both basic data type parameters and reference type parameters are actually passed values. However, basic data type parameters pass simple values, while reference type parameters pass the first address of an object opening up a continuous space in heap space.
2. Even if the reference type is passed, it may not affect the array object in the main method, because after the reference type in func1 method is copied to the address of the array object in the main method, it can still point to a newly opened space on the heap through the keyword new without affecting the array object pointed to by the reference type in the main method.

4.2.3 array as return value of function

//Array is used as the return value of the function to obtain the first N items of the Fibonacci sequence
    public static int[] fib(int n){
        if(n<=0){
            return null;
        }
        int[] arr = new int[n];
        arr[0]=1;
        arr[1]=1;
        if(n>2){
            for (int i = 3; i < n; i++) {
                arr[i] = arr[i-1]+arr[i-2];
            }
        }
        return arr;
    }
    public static void main(String[] args) {
        int[] arr = fib(10);
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i]+" ");
        }
    }

Operation results:

5. Two dimensional array

Two dimensional array is essentially a special one-dimensional array, but each element of the two-dimensional array is a one-dimensional array.
Definition syntax of two-dimensional array: data type [] [] array name = new data type [number of rows] [number of columns] {data initialization content}
There are three ways to create and initialize two-dimensional arrays:

 int[][] arr1 = {{1,2,3},{4,5,6}};
 int[][] arr2 = new int[2][3];
 int[][] arr3 = new int[][]{{1,2,3},{4,5,6}};

Traverse two-dimensional array:

public static void main(String[] args) {
        int[][] arr1 = {{1,2,3},{4,5,6}};
        for (int i = 0; i < arr1.length; i++) {//arr1.length indicates the number of rows
            for (int j = 0; j < arr1[i].length; j++) {//arr1[i].length indicates the array length of each row element
                System.out.print(arr1[i][j]+" ");
            }
            System.out.println();
        }
    }

??? Do you understand today and learn a lot here???

?? ?? ?? See you next time, huh??

Tags: Java Back-end Interview

Posted by slava_php on Sun, 15 May 2022 00:41:51 +0300