Control structures and arrays

control structure

##Bold styles # control the type of loop

  • Sequence control: the program is executed line by line from top to bottom without jump and any judgment

  • Branch control: if - else judgment

    // Single branch
    if(Conditional expression){ 
        Execute statement;
    }
    // Double branch
    if(Conditional expression){ 
        Execute statement;
    }else{
        Execute statement;
    }
    // Multi branch
    if(Conditional expression){ 
        Execute statement;
    }else if(Conditional expression){
        Execute statement;
    }else{
        
    }
    
  • Nested branch: nest another branch structure (preferably no more than three layers) in one branch structure

  • switch branch structure

    switch(expression){ // The expression has a specific value 
           case Constant 1: statement 1; // The expression represents a specific value, and the constant 1 is compared with the value. If it is the same, run statement 1
                      break; // Exit the switch loop, otherwise run statement 2 directly (there is no need to compare constant 2)
    
           case Constant 2: Statement 2; // The expression represents a specific value. Constant 2 is compared with the value. If it is the same, statement 2 is run
                      break; 
           ....
           default: Last statement; // When not equal to all constants, the default statement is executed by default   
    }
    

    Attention to details:

    1. The data type of the expression must be the same as that of the constant, or the data type that can be automatically converted (the data type range of the constant is larger than that of the expression)
    2. The data types of specific values and constants in the expression can only be one of (byte,short,int,char,enum,String)
    3. The default keyword is optional (not mandatory)
  • for loop control & & while loop control & & do... While loop statement

    // Basic grammar
    for(Loop variable initialization;Cycle condition;Change of cyclic variable){
        Loop operation (multiple statements are allowed));
    }
    Running sequence: loop variable initialization --> [ Cycle condition --> Cyclic operation --> Changes in cycle conditions ]
       
    
    // Equivalent to while x
     Loop variable initialization;
    while(Cycle condition){
        Loop operation (multiple statements are allowed));
        Change of cyclic variable;
    }
    
    // Equivalent to do While execute before Judge
     Loop variable initialization;
    do{
        Loop operation (multiple statements are allowed));
        Change of cyclic variable;
    }
    while(Cycle condition);
    

Interrupt control flow statement

break statement

Concept: used to exit the current loop

// Unlabeled statement
for(int i = 0;i < 10;i++){
    for(int j = 0;j < 10;j++){
        break; // Default interrupt current loop
    }
}

// Statement with label (Format: label name custom +:)
label1:
    for(int i = 0;i < 10;i++){
        label2:
        for(int j = 0;j < 10;j++){
            break label1; // Interrupt the cycle of tag 1
        }
    }

// switch interrupt statement
switch(expression){ // The expression has a specific value 
       case Constant 1: statement 1; // The expression represents a specific value, and the constant 1 is compared with the value. If it is the same, run statement 1
                  break; // Exit the switch loop, otherwise run statement 2 directly (there is no need to compare constant 2)

       case Constant 2: Statement 2; // The expression represents a specific value. Constant 2 is compared with the value. If it is the same, statement 2 is run
                  break; 
       ....
       default: Last statement; // When not equal to all constants, the default statement is executed by default   
}

continue Statement

Concept: end this cycle and continue to the next cycle

// Unlabeled statement
for(int i = 0;i < 10;i++){
    for(int j = 0;j < 10;j++){
        continue; // End this cycle by default instead of exiting the cycle. Pay attention to the difference between this cycle and break
    }
}

// Statement with label (Format: label name custom +:)
label1:
    for(int i = 0;i < 10;i++){
        label2:
        for(int j = 0;j < 10;j++){
            continue label1; // End the loop of label1 and jump to the loop header matching the label
        }
    }

return statement

Concept: it means to jump out of the current method. If this method is the main method, it is equivalent to ending the program

break and continue must be used in loop or switch, and return can be used anywhere in the method

Related interview questions

The test part of this chapter is generally in the algorithm problem

In JAVA, how to jump out of the current multiple nested loop? [basic]

A: add label before the outermost loop, and then use the break:label method to jump out of multiple loops.

Can swtich work on byte, long and String? [basic]

A: in switch (expr), the parameters that can be passed to switch and case statements should be int, short, char or byte. long can not act on swtich, and string can act on switch (supported after Java 7)

What is the difference between continue, break and return?

  1. Continue: it means to jump out of the current cycle and continue the next cycle.
  2. break: jump out of the whole loop body and continue to execute the following statements of the loop.
  3. return: used to jump out of the method and end the operation of the method. return can be used in two ways:
    • return; : Directly use the return end method to execute. It is used for methods that have no return value function
    • return value; : Return a specific value for the method of a function with a return value

array

One dimensional array

Array is a reference data type, which can store multiple data of the same type. The reference data type has a default initial value

Array creation

// Declare before initialize
// Declare array name
int[] a; // Define the array data type and array name
 perhaps
int a[]; // It is recommended to use the above form, which is concise and clear
// Initialize array
a = new int[5];  // 5 refers to the array length (a.length) 

// Declaration + initialization
int[] b = new int[5]; // 5 refers to the array length (a.length) 
// Access array values through subscript / index [0, array. Length]. For example, a[1] refers to the second array 

// Static initialization stored in array value
int[] c = {2,3,4,5,6}; // The comma after the last value is optional

Pay attention to details

  • There is a default initial value after the array is created

    data typebyteshortcharintlongfloatdoublebooleanString
    Initial value00\u0000000.00.0falsenull
  • The array range is represented by an open interval: [0, array.length)

The difference between value passing and reference passing

Array copy= Array assignment (reference passing)

// Arrays method
int[] a = {1,2,3};
int[] b = Arrays.copyOf(a,a.length)
    
// Traversal assignment
int[] a = {1,2,3};
int[] b = new int[a.length];
for(int i = 0;i < a.length;i++){
    b
}

Two dimensional array

Array creation

// Declare before initialize
// Declaration method
int[][] a;   int[] a[];  int a[][];  
int[] x,y[]; // x is a set of dimensions and y is a two-dimensional array
// Initialize 2D array
a[n] new int[5];  //The value range [0,5] of n represents the one-dimensional array element of a row

// dynamic initialization
int[][] twoArray = new int[5][]; // 5 one-dimensional arrays, each one-dimensional array element can be different
int[][] twoArray = new int[5][5]; // 5 * 5 two-dimensional array
 
twoArray.length; // Rows of 2D array (number of 2D array elements)
twoArray[n].length; // The value range of n [0,twoArray.length) represents the one-dimensional array element of a row

// initiate static
// Each row of elements in each two-dimensional array is not necessarily equal
int[][] a =  {{1,2},{3,4,5,6,},{1,2,3}};
for (int i = 0; i < a.length; i++) {
    for (int j = 0; j < a[i].length; j++) {
        System.out.print("\t"+a[i][j]);
    }
    System.out.println();
}
	1	2
	3	4	5	6
	1	2	3

Memory graph analysis of two-dimensional array

Error prone questions

Related interview questions

Please explain what is value passing and reference passing?

Investigation point: JAVA reference passing

A: value transfer is for a basic variable. It transfers a copy of the variable. Changing the copy does not affect the original variable
Reference passing is generally for object-oriented variables. It passes a copy of the object address, not the original object itself. Therefore, the operation on the reference object will change the original object at the same time

Yang Hui triangle implementation (two-dimensional array exercise)

final int N = 10;
int[][] array = new int[N][];
for (int i = 0; i < N; i++) {
    array[i] = new int[i+1];
    for (int j = 0; j <= i; j++) {
        if(j == 0 || j == i){
            array[i][j] = 1;
        }else{
            array[i][j] = array [i-1][j] + array[i-1][j-1];
        }
    }
}

for (int i = 0; i < array.length; i++) {
    for (int j = 0; j < array[i].length; j++) {
        System.out.print(array[i][j]+"  ");
    }
    System.out.println();
}
// Realization effect
1  
1  1  
1  2  1  
1  3  3  1  
1  4  6  4  1  
1  5  10  10  5  1  
1  6  15  20  15  6  1  
1  7  21  35  35  21  7  1  
1  8  28  56  70  56  28  8  1  
1  9  36  84  126  126  84  36  9  1  

Keywords: Java IDEA

Added by jtrost on Mon, 17 Jan 2022 03:30:22 +0200