JavaSE basic syntax (below), are you sure you understand it?

foreword

This blogger will use CSDN to record the experience and knowledge gained and learned on the road of software development and learning. Interested friends can follow the blogger!
Maybe a person walking alone can go very fast, but a group of people walking together can go further! Let us learn from each other on the road of growth, welcome to pay attention!


Follow and private message bloggers, you can get JDK1.8 Chinese version!


1. Program flow control

1 Overview

A flow control statement is a statement used to control the execution order of each statement in a program. The statement can be combined into a small logic module that can complete a certain function.

2. Classification

Its process control method adopts three basic process structures specified in structured programming, namely:

  1. Sequence structure
    The program is executed line by line from top to bottom without any judgment or jump in the middle.

  2. Branch structure
    Selectively execute a section of code based on a condition.
    There are if…elseand switch-casetwo branch statements.

  3. A loop structure
    executes a certain piece of code repeatedly according to a loop condition.
    There are three kinds of loop statements while, , do…while, and .for

Note: JDK1.5 provides foreachloops to easily traverse collection and array elements.

2. Sequential structure

A valid forward reference is used when defining member variables in Java. Such as:

public class Test{
     
     
  int num1 = 12;
  int num2 = num1 + 2;
}
//错误形式:
public class Test{
     
     
  int num2 = num1 + 2int num1 = 12;
}

insert image description here

3. Branch structure

1. if-else structure

1.1 Format

ifThere are three forms of sentences:

1.
if(条件表达式){
     
     
  执行代码块;
}

insert image description here

2. 
if(条件表达式){
     
     
  执行代码块1;
}else{
     
     
  执行代码块2;
}

insert image description here

3. 
if(条件表达式1){
     
     
  执行代码块1;
}
else if (条件表达式2){
     
     
  执行代码块2;
}
……
else{
     
     
  执行代码块n;
}

insert image description here

1.2 Instructions for use

⭕ Conditional expressions must be Boolean expressions (relational expressions or logical expressions), Boolean variables.

⭕ When there is only one execution statement in the statement block, a pair of {} can be omitted, but it is recommended to keep it.

if-elseStatement structure, which can be nested as needed.

⭕ When the if-elsestructure is "multiple choice one", the last one elseis optional and can be omitted as needed.

⭕ When multiple conditions are in a "mutually exclusive" relationship, the order between the conditional judgment statements and execution statements doesn't matter. When multiple conditions are in an "inclusive" relationship, "small upper and larger lower/child upper parent lower".

2. switch-case structure

2.1 Format

switch(表达式){
     
     
  case 常量1:
    语句1;
// break;
  case 常量2:
    语句2;
// break; … …
  case 常量N:
    语句N;
// break;
  default:
    语句;
// break;
}

insert image description here

2.2 Instructions for use

The value of the expression in ⭕ switch(expression) must be one of the following types: byte, short, char, int, 枚举 (jdk 5.0), String (jdk 7.0).

The value in the ⭕ caseclause must be a constant, not a variable name or indeterminate expression value.

switch⭕ The constant values ​​in all clauses of the same statement caseare different from each other.

The ⭕ breakstatement is used to make the program jump out of the statement block caseafter executing a branch ; if not , the program will execute sequentially to the end.switchbreakswitch

The ⭕ defaultclause is optional. At the same time, the location is also flexible. When there is no match case, execute default.

2.3 Examples

Example 1

public class SwitchTest {
     
     
    public static void main(String args[]) {
     
     
        int i = 1;
        switch (i) {
     
     
          case 0:
            System.out.println("zero");
            break;
          case 1:
            System.out.println("one");
            break;
          default:
            System.out.println("default");
            break; 
        } 
    }
}

Example 2

String season = "summer";
    switch (season) {
     
     
      case "spring":
        System.out.println("春暖花开");
        break;
      case "summer":
        System.out.println("夏日炎炎");
        break;
      case "autumn":
        System.out.println("秋高气爽");
        break;
      case "winter":
        System.out.println("冬雪皑皑");
        break;
      default:
        System.out.println("季节输入有误");
        break; 
    }

3. Comparison of switch and if statements

ifSimilar switchto a statement, which statement should be used in specific scenarios?

⭕ If the specific value of the judgment is not many, and it conforms to byte、short 、char、int、String、枚举several types. Although both statements can be used, the statement is recommended swtich. Because the efficiency is slightly higher.
⭕ Other cases: For interval judgment, for the result of booleantype judgment, use if, ifthe use range is wider. That is to say, what is used switch-casecan be rewritten as if-else. The opposite does not hold.

4. Cyclic structure

1 Overview

Repeatedly execute the function of a specific code when certain conditions are met.

2. Classification

⭕cycle⭕cycle⭕cycle for_
_ while_
_ do-while_

3. Structure

(1) Initialization part (init_statement)
(2) Loop condition part (test_exp)
(3) Loop body part (body_statement)
(4) Iterative part (alter_statement)
insert image description here

1. for loop

1.1 Syntax format

for (①初始化部分; ②循环条件部分; ④迭代部分){
       ③循环体部分;

1.2 Execution process

①-②-③-④-②-③-④-②-③-④-…-②

1.3 Description

⭕ ②The loop condition part is a boolean type expression. When the value is false, the loop is exited.
⭕ ①In the initialization part, you can declare multiple variables, but they must be of the same type, separated by commas.
⭕ ④ There can be multiple variable updates, separated by commas.

insert image description here

1.4 Examples

public class ForLoop {
     
     
    public static void main(String args[]) {
     
     
      int result = 0;
      for (int i = 1; i <= 100; i++) {
     
     
           result += i; 
      }
     System.out.println("result=" + result);
    } 
}

2. while loop

2.1 Syntax format

①初始化部分 while(②循环条件部分){
     ③循环体部分; 
     ④迭代部分;
 }

2.2 Execution process

①-②-③-④-②-③-④-②-③-④-…-②

2.3 Description

⭕ Be careful not to forget to declare the ④ iteration part. Otherwise, the loop will not end and become an infinite loop.
⭕ For loop and while loop can be converted into each other.

2.4 Examples

public class WhileLoop {
     
     
  public static void main(String args[]) {
     
     
    int result = 0;
    int i = 1;
    while (i <= 100) {
     
     
      result += i; i++;
    }
    System.out.println("result=" + result);
 } 
}

3. do-while loop

3.1 Syntax format

①初始化部分;
do{
     
     
  ③循环体部分
  ④迭代部分
}while(②循环条件部分); 

3.2 Execution process

①-③-④-②-③-④-②-③-④-…②

3.3 Description

⭕ The do-whileloop executes the loop body at least once.

3.4 Examples

public class DoWhileLoop {
     
     
    public static void main(String args[]) {
     
     
      int result = 0, i = 1;
      do {
     
     
        result += i; i++;
      } while (i <= 100);
      System.out.println("result=" + result);
    } 
}

Note: The simplest "infinite" loop format: while(true), for(;;), The reason for the existence of an infinite loop is that you don't know how many times to loop, and you need to control the end of the loop according to certain conditions inside the loop body.

4. Nested loops

⭕ Nested loops are formed by placing a loop within the body of another loop. Among them, for ,while ,do…whileboth can be used as outer circulation or inner circulation.
⭕ In essence, a nested loop is to treat the inner loop as the loop body of the outer loop. When only the loop condition of falsethe inner loop is , the inner loop can be completely jumped out, the current loop of the outer loop can be ended, and the next loop can be started.
⭕ Assuming that the number of loops in the outer layer is m times and the number of loops in the inner layer is n times, the inner loop body actually needs to be executed m*n times.

5. Use of special keywords: break, continue

5.1 break

(1) A breakstatement is used to terminate the execution of a block of statements

{
     
      ……
break;
……
} 

(2) breakWhen a statement appears in a multi-level nested statement block, the label can indicate which level of statement block is to be terminated.

label1: {
     
      ……
label2:       {
     
      ……
label3:            {
     
      ……
                 break label2;
                    ……
                    } 
               } 
        }

(3) Example

public class BreakTest{
     
     
  public static void main(String args[]){
     
     
    for(int i = 0; i<10; i++){
     
      
      if(i==3)
       break;
      System.out.println(" i =" + i);
    }
     System.out.println("Game Over!");
  } 
}

5.2 continue

continuecan only be used in looping structures.
The ⭕ continuestatement is used to skip one execution of the loop statement block where it is located and continue to the next loop.
When a ⭕ continuestatement appears in a multi-level nested loop body, you can use a label to indicate which level of loop to skip.

5.3 break 与 continue

breakcan only be used in switchstatements and loops.
continuecan only be used in loop statements.
⭕ The functions of the two are similar, continuebut terminating this loop breakis to terminate the loop of this layer.
break, continuethere can be no other statements after it, because the program will never execute the statement after it.
⭕ The labelled statement must immediately follow the head of the loop. Labeled statements cannot be used before non-loop statements.
⭕ Many languages ​​have gotostatements that gototransfer control at will to any statement in the program and then execute it. But makes the program error prone. JavaThe breaksum continuein is different goto.

5.4 return and break and continue

return: Not specifically used to end a loop, its function is to end a method. When a method reaches a return statement, the method will be terminated.

⭕The difference from and is that breakthe entire method is directly ended, no matter how many layers of loops the return is in.continuereturn

Guess you like

Origin blog.csdn.net/weixin_52533007/article/details/123673398