First knowledge of Java ~ # Java program execution process, especially detailed ~ collectable~

Hello ~, I'm Qing and Han Dynasties

After a lapse of one month, I finally came up with the second program execution flow code in the Java beginner series~

It should not be too late. I feel I have made rapid progress in learning this month, although the progress of writing articles is a little slow, ha ha~

Don't say much. Hurry up 🐎~

Statement: there is no advertisement. The knowledge of the full text comes from the Douban score of 9.0 in introduction to JAVA 1-2-3

Note: all > > > symbols in the example are output results

-- snip -- omit location for code

Knowledge block diagram

introduction

  • In what order do programs in Java execute? What kind of process does it have?
    • In the following, we will reveal the execution process of Java program (code) and deeply understand the program execution process mechanism of Java.

Program execution flow in Java (mind map)

Code execution mechanism

  • Sequential execution
  • I wonder if "friends" have found that in the first article of this series, all code examples in the article are executed from the first line of the main() method to the last line of the main() method.
    • public static void main(String[] args) {
    • //First line ⬇
    • //The second line ⬇
    • // ... ... ⬇
    • //Last line ⬇
    • }
  • From this, we can simply draw a conclusion that the code execution process in Java is executed sequentially from top to bottom.
  • But is the program execution process in the Java language really so simple? Will it look rigid?
  • Of course, the Java language can't be just like this. At present, it's just some conclusions summarized by our beginners in Java, and it's just a glimpse of the leopard. Let's continue to explore the world of java with a brisk pace...
  • if... else... Statement
  • There can't be only one way for program execution. How can a high-level language like Java go black like a stubborn donkey? Because this is not flexible enough, it can only deal with some very simple logic, and in the actual development and application, there will be a variety of complex logic to deal with, so there is no future for one way to go to black.
  • These things we can think of must also be thought of by a group of extremely smart Java developers. So Java provides us with if... else... Statements.
  • With the if... else... Statement, the execution of our program has branches. Before, we went to black in the same way. Now we have many branches to choose from, which makes the execution of the program more flexible and can also deal with more complex logic.

Let's take a look at how to use this if... else... Statement!

// if...else.. statement instance

public class PriceAndAmount {
    public static void main(String[] args) {
        // Create two integer variables and assign negative values;
        int price  = -5; 
        int amount = -10;
        
		// Use the if statement to check whether both variables are greater than 0, 
		// If it is greater than 0, return true; otherwise, return false;
        if (price > 0 && amount > 0) { 
        	// The two variables are multiplied, and the result is assigned to the newly created int type variable
            int totalCost = price * amount; 
            
            System.out.print(totalCost); // Output results to console
        }
        else {
            System.out.println("price And amount The value of must be greater than 0, otherwise it cannot be calculated.");
        }
    }
}
// >>>The values of price and amount must be greater than 0, otherwise they cannot be calculated.
  • if... else... Statement is a statement used in Java syntax to support the program to jump the execution process of the program according to a boolean (boolean) value.
  • Structure of if... else... Statement:
    • if (a boolean expression or a boolean value){
    • //If true in if() parentheses, execute the code in {} braces
    • } else {
    • //If the in if() brackets is false, execute the code in else braces
    • }
  • If... else... Can be understood as: if... Otherwise
  • If the conditions are met, execute this code, otherwise execute another code

Of course, if... else... Statements don't have to be used in pairs. There are several ways to use them. Now let's introduce them one by one

1. Single if()

// Single if statement instance

public class IfDemo1 {

    public static void main(String[] args) {

        int a = 0, b = 1;

        if (a > 0) {
            System.out.println("variable a Greater than 0, print a: " + a);
        }
        System.out.println("variable a Not greater than 0, previous if Statement does not meet the condition,\n Program skip if The contents in the statement body are executed here and printed b: " + b);
    }
}
// >>>Variable a is not greater than 0, and the previous if statement does not meet the conditions,
// >>>The program skips the contents in the if statement body, executes here, and prints b: 1

2. Multiple if()

// Multiple if statement instances

public static void main(String[] args) {

        int a = 0, b = 1, c = 2;

        if (a > 0) {
            System.out.println("variable a Greater than 0, print a: " + a);
        }
        if (b == 0) {
            System.out.println("variable b Equal to 0, print b: " + b);
        }
        if (c == 1) {
            System.out.println("variable c Equal to 1, print b: " + c);
        }
        System.out.println("The program is executed in sequence, the first three if Statements do not meet the conditions. Skip if The contents of the statement body are executed here");
    }
}
// >>>The program is executed sequentially. The first three if statements do not meet the conditions. Skip the contents in the if statement body and execute here

3. if()...else if()...else statement

// if()...else if()...else statement instance

public class CountScrip {
    public static void main(String[] args) {
        int totalCost = 350;

        if (totalCost < 100) {
            System.out.println("No coupon for less than 100 yuan");
        }
        else if (totalCost <= 500) {
            System.out.println("55 yuan coupon for 100 yuan or more");
        }
        else {
            System.out.println("500 RMB 155 coupons for more than RMB");
        }
    }
}

// >>>55 yuan coupon for 100 yuan or more

If()... else if()... else statement

  • This sentence structure can be understood as:
    • If... If... Otherwise
  • The process is as follows:
  1. If the first if satisfies the condition, the following else if... Else will not be executed
  2. If the first if does not meet the condition, judge whether else if meets the condition
  3. else if the conditions are met, then else will skip
  4. else if the condition is not met, else is executed
  • By learning the if statement, we know that Java programs can not only go black in one way, but also choose different branches through the if statement.
  • Although the program has a fork in the road, you can choose different code to execute, but the whole program is still indomitable and "don't look back", which still doesn't feel very smart.
  • Moreover, in practical application, sometimes you have to process the same code repeatedly. What should you do? Do you have to type the same code every time you execute it? Although copy and paste can be used, it's OK to copy and paste twice and three times. If it's tens of thousands of times, do you also copy and paste repeatedly?
  • Obviously, copy and paste is unreasonable. In this way, the amount of code is too large, and they are repeated. We are not assignment and paste robots. We are programmers who give the program soul "are we not"?

Let's introduce the circular statements in Java

Circular statement

  • In Java, there are three kinds of circular statements, namely:
    • while
    • do...while
    • for
  • How to use it and what is its function?
  • Let's talk about it~
  • while statement
// while statement instance

/**
 * Cashier work case
 * Requirements: the cashier should check in 5 times, that is, repeat the work 5 times
 */
public class SettleAccountsUsingWhile {
    public static void main(String[] args) {
        int times = 5; // Set the cashier times as the while cycle condition.

        while (times > 0) {
            // Create two variables of type int and assign values to them respectively
            int price = 5;      // commodity price
            int amount = 10;    // Quantity of goods

            if (price > 0 && amount > 0) { // Judge whether the two variables are greater than 0;
                int totalCost = price * amount;
                System.out.println(totalCost);
            } else {
                System.out.println("price And amount The value of must be greater than 0, otherwise it cannot be calculated.");
            }
            times -= 1; // The number of cashier times is reduced by 1, and it is 0 after 5 cycles. If the while cycle conditions are not met, exit the cycle.
        }
        System.out.println("After checking out today, the cashier can get off work");
    }
}
// >>> 50
// >>> 50
// >>> 50
// >>> 50
// >>> 50
// >>>After checking out today, the cashier can get off work
  • Functions of while
    • The while statement can execute a piece of code 0 to countless times according to the value of a boolean expression.
    • It can be understood that when the conditions are met, the code in the while statement {} braces will be executed in a loop. When the conditions are not met, the cycle ends.

Structure of while statement:

  • While (a boolean expression or a boolean value){
  • //Code to execute
  • }

Execution flow of while statement

  • ⬆ ➑ Evaluates the value of a conditional expression
  • ⬆      ⬇
  • ⬆ while statementThe value of a conditional expression ➑ false
  • ⬆      ⬇           ⬇
  • ⬆        end of execution of while statement
  • ⬆      ⬇
  • ⬆ β¬… Execute the code in the while statement {}
  • do... while statement
// do...while statement instance

/**
 * Cashier work case
 * Requirements: the cashier should check in 5 times, that is, repeat the work 5 times
 */
public class SettleAccountsUsingDoWhile {
    public static void main(String[] args) {
        int times = 5;

        do { // //do while statement, loop body. Whether the expression conditions are met or not, the code block must be executed first.
            // Create two variables of type int and assign values to them respectively
            int price = 5;      // commodity price
            int amount = 10;    // Quantity of goods

            if (price > 0 && amount > 0) { // Judge whether the two variables are greater than 0;
                int totalCost = price * amount;
                System.out.println(totalCost);
            } else {
                System.out.println("price And amount The value of must be greater than 0, otherwise it cannot be calculated.");
            }
            times -= 1;
        } while (times > 0); // do while statement, the conditional expression should be placed after the loop body, and a semicolon should be added;
        System.out.println("After checking out today, the cashier can get off work");
    }
}

// >>> 50
// >>> 50
// >>> 50
// >>> 50
// >>> 50
// >>>After checking out today, the cashier can get off work
  • Functions of do... while
    • The code implementation instance of do... While here is basically the same as that of while, and you can get the same results, but replace while with do... While;
    • The difference is that the code in the do... while statement {} braces will be executed first, and then the conditional expression will be judged.

Structure of do... while statement:

  • do {
  • //Code to execute
  • }While (a boolean expression or a boolean value)

Execution flow of do... while statement

  • Execute the code in the while statement {}
  • ⬆      ⬇
  • true   evaluates the conditional expression
  • ⬆      ⬇
  • ⬆ β¬… Value of do...while conditional expression
  •        ⬇
  •        false
  •        ⬇
  •   end of while statement execution
  • for statement
public class SettleAccountsUsingFor {
    public static void main(String[] args) {
        //for (initialization statement; conditional statement; conditional change statement;)
        for (int times = 0; times < 5; times++) {
         // The number of cycles is 5
         // The loop ends when the times is not less than 5
         // Starting from 0, 0-1-2-3-4, 5 times in total

            // Create two variables of type int and assign values to them respectively
            int price = 5;      // commodity price
            int amount = 10;    // Quantity of goods

            if (price > 0 && amount > 0) { // Judge whether the two variables are greater than 0;
                int totalCost = price * amount;
                System.out.println(totalCost);
            } else {
                System.out.println("price And amount The value of must be greater than 0, otherwise it cannot be calculated.");
            }
        }
        System.out.println("After checking out today, the cashier can get off work");
    }
}

// >>> 50
// >>> 50
// >>> 50
// >>> 50
// >>> 50
// >>>After checking out today, the cashier can get off work
  • Functions of the for statement
    • Loop executes the code in for {} braces until the loop condition is not met.
  • Syntax structure of for statement
    • for (initialization statement; conditional statement; conditional change statement){
    • //Code to execute
    • }
  1. The initialization statement is executed first and only once. It will create a variable, which will be used in subsequent conditional statements and conditional change statements.
  2. Conditional statements are used to determine whether the loop body (the code in the for {} braces) is executed. true is executed and false is not executed.
  3. Conditional change statements are executed after each execution of the loop body (). They are generally used to change the conditions used in conditional statements. Commonly used are variable + +, – (self increasing and self decreasing) operations.

Execution flow of for statement

  • Initialization statement
  •    ⬇
  • ⬆ ➑ Conditional statement ➑ false
  • ⬆  ⬇     ⬇
  • ⬆   true for statement execution ends
  • ⬆  ⬇
  • ⬆   circulatory body
  • ⬆  ⬇
  • ⬆ β¬… Conditional change statement
  • continue and break keywords
  • Here are two keywords used in the loop: continue and break. Using these two keywords in the loop body can make our code more flexible.
  • The specific functions and usage methods are shown one by one below~

continue keyword

// continue keyword demo instance

public class ContinueDemo {

    public static void main(String[] args) {

        for (int i = 1; i <= 5; i++) {
            if (i == 2) {
                continue;
                // Note: the code after the continue keyword will not be executed
                // Java syntax stipulates that continue should be placed on the last line of the code block
            }
            System.out.println("i The value of is:" + i);
        }
    }
}
// >>>The value of I is: 1
// >>>The value of I is: 3
// >>>The value of I is: 4
// >>>The value of I is: 5
  • Function of continue keyword
    • Through the above example, the results of the output console can draw a conclusion: when the continue keyword is executed in the loop body, the code after continue will no longer be executed, but instead calculate the loop condition expression and judge whether to execute the next loop body according to the value.
    • Therefore, in the above example, the output print result is not 2;
    • continue has the same effect in all loops, whether it is a while, do... While or for loop.
    • Java syntax stipulates that continue should be placed on the last line of the code block

break keyword

// break keyword instance

public class BreakDemo {

    public static void main(String[] args) {
        // Declare variable a
        int a = 1;
        // Use the while loop, and the conditional expression is true
        while (true) {
            // Output the value of a to the console
            System.out.println("a The value of is:" + a);
            // Use the if statement to judge that when a is equal to 5, execute the break statement
            if (a == 5) {
                break;
            }
            // Variable a performs auto increment
            a++;
        }
    }
}

// >>>The value of a is: 1
// >>>The value of a is: 2
// >>>The value of a is: 3
// >>>The value of a is: 4
// >>>The value of a is: 5
  • Function of break keyword
    • The semantics of the break keyword is to terminate the loop in which it is located.
    • Java syntax stipulates that break should be placed on the last line of the code block
    • In the above example code, we use the while loop, and the condition judgment is assigned to true; that is, the loop will be executed forever~
    • However, we added an if statement judgment in the while code block. When the judgment conditions are met, the break statement will be executed, and the while loop will end after execution.
    • Finally, we can see from the printout of the console that the value of a is printed to 5 instead of accumulating all the time.

expand

switch statement

  • The switch statement is not a loop statement, but a branch statement like an if statement.
  • Its function is similar to that of if statement. It also creates forks for our program and selects different roads according to different conditions.
  • OK, let's see how to use the switch statement~
// switch statement instance

public class SwitchDemo1 {

    public static void main(String[] args) {
        int goodsNumber = 4; // Create a variable of type int and assign a value of 4

        switch (goodsNumber) { // Parameter must be an int type or char type variable

            // If the condition value 1 is equal to the goodsNumber value, the code executes from here
            // case statements can only be in switch statements and can contain 0 to more than one
            case 1:
                System.out.println("This item belongs to the food division");
                break;

            case 2: // If the condition value 2 is equal to the goodsNumber value, the code executes from here
                System.out.println("This product also belongs to the food division");
                break;
            case 3:
                System.out.println("This item belongs to the department store division");
                break;
            case 4:
                System.out.println("This item also belongs to the department store division");
                break;
            case 5:
                System.out.println("This product also belongs to the department store division");
                break;

            // If the value of goodsNumber cannot be found in the previous case, the code executes from here
            default:
                System.out.println("No such product");
                break;
        }
        System.out.println("switch Statement execution completed");
    }
}

// >>>This item also belongs to the department store division
// >>>The switch statement has been executed
  • Syntax structure of switch statement
  • Switch (value to be matched){
  • case condition value 1:
  •   code block
  • case condition value 2:
  •   code block
  • case condition value..:
  •   code block
  • ... ... ...
  • default:
  •   code block
  • }

switch statement function

  • Select which case code block to execute according to the matching value. If the matching value cannot match the value of case, the default code block will be executed.
  • Usually, we will add a break statement at the end of the case code block to end the switch statement.
  • This is done because the switch statement has the characteristics of breakdown.
  • The following example demonstrates this feature.
public class UsingSwitch {
    public static void main(String[] args) {
        int goodsNumber = 3; 

        switch (goodsNumber) { 
        
            case 1: 
                System.out.println("This item belongs to the food division");
                break;
            case 2: 
                System.out.println("This product also belongs to the food division");
                break;
            case 3:
           		System.out.println("This product belongs to the toy department");
            case 4:
            	System.out.println("This product belongs to the food department");
            case 5:
                System.out.println("This item also belongs to the department store division");
                break;

            default:
                System.out.println("No such product");
                break;
        }
        System.out.println("switch Statement execution completed");
    }
}
// >>>This product belongs to the toy department
// >>>This product belongs to the food department
// >>>This item also belongs to the department store division
// >>>The switch statement has been executed
  • breakdown ⚑

    • In the above example, we can see that our matching value is 3, but the corresponding case 3 does not end with a break statement.
    • After executing the code of case 3, the program executes the code of case 4, and the code of case 4 does not end with break.
    • So the program executes the code of case 5 again. The code of case 5 ends with break.
    • This completes the execution of the switch statement.
  • Advantages and disadvantages of breakdown

    • Benefits: when multiple codes in the case are repeated, you can omit the repeated code and execute the last code for many times.
    • Disadvantages: the function of our switch statement is to provide branches (give a lot of paths) to the program. If multiple paths are opened, what's the meaning of our switch statement?
label
  • When there are multiple loop statements, the label and break can specify which loop statement to jump out of.
  • The specific implementation method will be demonstrated in the following example.
// Demo examples of tags

public class LoDemo {

    public static void main(String[] args) {
        
        // Use the while loop and define a label w1
        w1:while (true) {
            // Nest a for loop and define a label f1
            f1:for (int i = 0; i < 5; i++) {
                // Nest a switch statement
                switch (i) {
                    case 1:
                        System.out.println("i The value of is:" + i);
                        break;
                    case 2:
                        System.out.println("i The value of is:" + i);
                        // It is specified here that the loop that the break statement jumps out is w1
                        // That is, the while loop
                        break w1;
                    case 3:
                        System.out.println("i The value of is:" + i);
                        break;
                    case 4:
                        System.out.println("i The value of is:" + i);
                        break;
                    case 5:
                        System.out.println("i The value of is:" + i);
                        break;
                    default:
                        break;
                }
            }
        }
    }
}

// >>>The value of I is: 1
// >>>The value of I is: 2
  • In the above example, when the code is executed to break w1 of the case 2 code block of the switch statement; The break statement will not jump out of the current switch statement, but will jump out of the while statement where the label is located, and then the while loop ends and the program is executed.
  • In the above example, we also labeled the for loop, that is, we can also specify to jump out of the for loop. Here we do not demonstrate the effect of jumping out of the for loop instead of the while loop, because the judgment condition of while is true, that is, it is an dead loop. If the for loop jumps out of case 2, what will the console always output? (interested partners can try it by themselves)

Summary of this paper

  • Java is not straightforward

  • Branch statement:

    • if statement
      • Judge whether the code block of the if statement is executed according to a condition.
    • if... else statement
      • The code block that determines whether to execute if or else according to the condition.
    • If... else if... else statement
      • Determine whether to execute if, else if or else code blocks according to conditions.
    • switch statement
      • According to an int or char variable that matches the value in the case statement, which piece of code to execute is determined.
      • Understand penetration characteristics.
    • It should be used skillfully. For nested use, it should be clear and need the support of code quantity.
  • Loop statement:

    • while statement
    • do... while statement
    • for statement
    • The functions of the three loops are essentially the same. Try to use the for loop when the number of cycles is determined, and try to use the while loop when the number of cycles is uncertain. Set conditions to end the loop, otherwise it will cause dead loop.
  • Skillfully use the continue and break keywords and understand the functions of each keyword.

  • The expanded tag function will sometimes help you solve the problems encountered in programming.

If there is anything wrong in the article, you are welcome to point out error correction and make common progress!!

Thank you, young Xia, for reading this carefully! Let's have a hand slide triple. Don't get lost~


See you next time, waiting for you~


Keywords: Java

Added by noobstar on Sat, 16 Oct 2021 00:08:19 +0300