Java learning notes -- operators and control statements

Posted by DaveSamuel on Sat, 05 Mar 2022 05:19:07 +0100

1, Operator

1.1.1 overview of operators

Operator refers to the operation of operands.

1.1.2 arithmetic operators

public class Test02 {
public static void main(String[] args) {
        //Arithmetic operator
        //Addition, subtraction, multiplication and division
        int a = 10;
        int b = 3;
        System.out.println(a + b);
        System.out.println(a - b);
        System.out.println(a * b);
        //3.3333 part of decimal
        System.out.println(a / b);
        
        //Modulus operation for remainder
        //10 divided by 3 leaves 1
        System.out.println(a % b);
    }
}

Operation results

//++ --
        //Indicates the operation of self increasing 1 / self decreasing 1

        int i = 10;
        i++;
        System.out.println("i= "+i);

        int j = 10;
        ++j;
        System.out.println("j= "+j);
        
        
        /*
            ++If it appears on the right side of the variable, execute the expression where + +, and then execute++
            Expression int m - k + +;
            Execute int m = k first; (execute expression first)
            Then execute k = K + 1 (auto increment operation)


            ++If it appears on the left side of the current variable, name is the expression where + + is executed first and then + +
            Expression int p = + O;
            Execute o = O + 1 first (auto increment first)
            Execute int p = o again (execute expression later)

            int i = 10;
            ++i:Is the value of i itself, increasing by 1
            i+1: i Its own value will not change

         */
        int k = 10;
        int m = k++;
        System.out.println("k="+ k);//11
        System.out.println("m="+ m);//10
        
        int o = 10;
        int p = ++o;
        System.out.println("o=" + o);//10
        System.out.println("p=" + p);//11
    }

Operation results

1.1.3. Relational operators

Relational operators are mainly used to complete the comparison between data. For example, if 5 > 3, the result is true, if 5 > 10, the result is false.

public class Test03 {
    public static void main(String[] args) {
        //Relational operator
        int a = 10;
        int b = 20;
        System.out.println(a > b);
        System.out.println(a >= b);
        System.out.println(a < b);
        System.out.println(a <= b);
        System.out.println(a == b);
        System.out.println(a != b);

         /*
            If = =, instead of comparing numbers, compare strings
            Through our current case, the conclusion is no problem
            But = = is not used to compare strings, which will cause serious problems in the future

            Conclusion:
                Although we have seen the following cases, it is easy to use = = to compare strings
                But don't use it like that

                In the future, we will use the equals method to compare strings
         */
        System.out.println("----------------------");

        String str1 = "abc";
        String str2 = "abc";
        System.out.println(str1==str2);
        System.out.println(str1.equals(str2));

    }
}

Operation results

1.1.4 logical operators

Logical operators mainly include logical and (&), logical or (|), logical XOR (^), short circuit and (& &), short circuit or (|). The characteristic of all logical operators is that the operands are Boolean, and the final operation result is also Boolean.

public class Test05 {
public static void main(String[] args) {
        /*
            &Representation and
                Both sides must be true, and the final result is true
            |Indicates or
                On both sides, one side is true, and the final result is true

            !Indicates negation
                !ture The result is false
                !false The result is true
         */
        System.out.println((5 > 3) & (5 < 4));
        System.out.println((5 > 3) & (5 > 4));
        System.out.println((5 > 100) & (5 > 4));

        System.out.println(true & true);//true
        System.out.println(true & false);//false
        System.out.println(true | false);//true
        System.out.println(false & false);//false
        System.out.println(!true);//false
        System.out.println(!false);//true

        /*
            ^Indicates XOR
                Both sides are true, and the final result is false
                Both sides are false, and the final result is false

                There are different values on both sides, and the final result is true

                Less used, understand
         */
        System.out.println("---------------------------");
        System.out.println(true ^ false);
        System.out.println(false ^ true);
        System.out.println(true ^ true);
        System.out.println(false ^ false);


        /*
            The difference between logic and (&), and short circuit and (& &)

            Logical and (&)
                &The expressions on both sides of the symbol will execute completely
            Short circuit & &)
                &&If the sign on the left side of the expression is false, the final result will be false
                &&The part to the right of the symbol has no comparison and continues to be executed

            Short circuit or (/ /)
                //If the expression on the left side of the symbol is true, the final result must be true
                //There is no need to continue the part to the right of the symbol

            Premise:
            m > n && m >n++The readability of the statement is very poor
            In the future actual project development, we will effectively disassemble the above statements
            More importantly, + + is an operation, and the operation is involved in the comparison
            Therefore, it is troublesome to read whether to compare first or compare first and then calculate, which needs to be judged


         */
        System.out.println("==========================");
        int m = 99;
        int n = 100;
        System.out.println(m > n & m >n++);
        System.out.println(n);//We see 101, which means that the above n + + is executed


        System.out.println("==========================>>>>");
        int a = 99;
        int b = 100;
        System.out.println(a > b && a >b++);
        System.out.println(b);//We see 100, which means that the above n + + is not executed

        System.out.println("------------------------->short circuit");
        //short circuit
        int q = 99;
        int w = 100;
        boolean flag1 = q > w;
        w++;
        boolean flag2 = q > w;
        System.out.println(flag1 & flag2);//false
        System.out.println(q > w & q>w++ | 10 >100 && !(q >= n));//false


    }
}

Operation results

1.1.5 assignment operator

At present, assignment operators only need to master =, + =, - =, =, / =,% =. Other binary related contents will be studied in detail later. The operators of assignment class include basic assignment operators (=) and extended assignment operators (+ =, - =, =, / =,% =).

public class Test05 {
    public static void main(String[] args) {
        //Assignment Operators 
        int i;
        i = 10;
        System.out.println("i=" + i);

       /* int x = 10;
        x += 1;//Effect x = x + 1;
        x -= 1;//x = x + 1;
        x *= 2;
        x /= 2;
        x %= 3;
        System.out.println("x="+ x);*/


        //Written test question: Xiaokeng
        // x += 1; And x = x + 1; Differences between

        int x = 10;
        x += 1;
        x = x + 1;
        System.out.println("x=" + x);//12

        byte b = 10;
        //b = b + 1 ; An error is reported during compilation. There are variables on the right. byte is no longer special
        //Forced rotation is required
        b =(byte)(b+1);
        System.out.println(b);//11

        byte a = 10;
        a += 1;//Compile through
        System.out.println(a);//11

        /*
            From the effect of the above cases
            If we make an int type
            x += 1;And x = x + 1;
            The effect seems to be the same without any difference

            But if we operate on integers of a type smaller than int
            x += 1;And x = x + 1; It's different
            x = x + 1;Error in compilation, forced conversion required
            x += 1;Compile through

            Why x += 1; You don't need a strong turn?
            Because using this copy operation+=
            If we encounter an operation that requires forced conversion, the system will automatically convert it for us

            For byte b= 10;
            b += 1;
            Is equivalent to b =(byte)(b+1); The system will help us with strong conversion
         */



    }
}

Operation results

1.1.6. About priority

1.1.7 condition operator

Conditional operator is often called ternary operator. Its syntax structure is: Boolean expression? Expression 1: expression 2.

public class Test06 {
    public static void main(String[] args) {
        //ternary operator 

        /*
            Syntax:
                Boolean expression? Expression 1: expression 2
                If the value of Boolean expression is true, expression 1 is executed
                If the value of Boolean expression is false, expression 2 is executed

         */
        boolean flag1 = true;
        int k = flag1 ? 1 : 0;
        System.out.println(k);

        boolean flag2 = false;
        int q = flag2 ? 1 : 0;
        System.out.println(q);

        int x = 100;
        int y = 200;
        System.out.println(x==y? "x and y The values of are equal":"x and y The values of are not equal");

        int x1 = 100;
        int y1 = 100;
        System.out.println(x1==y1? "x and y The values of are equal":"x and y The values of are not equal");



    }
}

Operation results

1.1.8 string splicing

The symbol of string splicer is the plus sign "+". In fact, the "+" operator has two functions in java language: one is to sum numbers, and the other is string connection.

public class Test07 {
    public static void main(String[] args) {
        //String splicing operator+
        int i = 10;
        int j = 20;
        String s = "abc";
        boolean flag = true;
        //System.out.println(i+flag+"");// Compilation error
        System.out.println(""+i+ flag);
    }
}

Operation results

2, Control statement

Sequential program statements can only be executed once.

If you want to perform the same operation multiple times, you need to use a loop structure.

  • There are three main loop structures in Java:
  1. while Loop
  2. do... while loop
  3. for loop

2.2.1. Select statement if

Selection statement, also known as branch statement, determines which of two or more branches to execute by judging the given conditions. Therefore, before writing the selection statement, we should first clarify the judgment conditions and determine what operations / algorithms should be performed when the judgment result is "true" or "false".

Let's first look at the if statement. The writing methods of if statements can be summarized into the following four types:
As shown in the figure:

public class Test01 {
    public static void main(String[] args) {
        /*
            Process control
            if
         */

        /*
            Case 1:
                If it rains outside, take an umbrella with you when you go out. Otherwise (it doesn't rain), don't take an umbrella

                If the boolean value is true, the contents in the if statement body {} will be executed
                If the boolean value is false, the contents in the if statement body {} will not be executed

                if(boolean){

                }


                If the boolean value is true, the contents in the if statement body {} will be executed
                If the boolean value is false, execute the content in the else statement question {}

                if(boolean){

                }else{

                }

         */
        boolean raining = true;
        //If
        if(raining){
            System.out.println("It's raining outside. I need to take an umbrella");
        //otherwise
        }else{
            System.out.println("It doesn't rain outside. You don't need to take an umbrella");
        }

        System.out.println("-------------------------------");

        //If you're full, go shopping, otherwise continue to eat

        boolean eatFull = true;
        if(eatFull){
            System.out.println("When you're full, go shopping");
        }else
            System.out.println("I'm not full. Keep eating");

        System.out.println("----------------------------------");

        /*
            Case 2:
                Multiple judgment
                Provide a variable value int a = 1;
                If the value of variable value a is 1, the value is printed as one
                If the value of variable value a is 2, the value is printed as 2
                If the value of variable value a is 3, the value is printed as three
                If the value of variable value a is not any one of 1, 2 and 3, print: it is not the desired number

         */
        /*int a = 3;
        if(a == 1){
            System.out.println("This value is 1 ");
        }else if(a == 2){
            System.out.println("This value is 2 ");
        }else if(a == 3){
            System.out.println("This value is 3 ");
        }else{
            System.out.println("Not the number I want ";
        }
*/
        /*
            Case 3:
                if Nested use of
                According to case 2 above, make subsequent judgment
                If the value of a is 1, judge the value of b and enter the corresponding information
         */

        int a = 1;
        int b = 1;
        if(a == 1){
            System.out.println("a The value of is 1");

            if(b ==1){
                System.out.println("b The value of is also 1");
            }else{
                System.out.println("b The value of is not the desired number");
            }


        }else if(a == 2){
            System.out.println("This value is 2");
        }else if(a == 3){
            System.out.println("This value is 3");
        }else{
            System.out.println("Not the number I want");
        }

        System.out.println("--------------------------");

        /*
            Supplement:
                if Statement without curly braces {}, such syntax can also be used

                Do not enlarge the parentheses, only for the next line

                In the actual project development, if statements should be uniformly added with {}, which has strong readability
         */

        /*int a1 = 1;
        if(a1==1)
            System.out.println("a1 The value of is 1 ");
            System.out.println("Is the result I want ";*/
        //The above code is equivalent to
        int a1 = 1;
        if(a1==1){
            System.out.println("a1 The value of is 1");
        }
        System.out.println("It's the result I want");


    }
}

Operation results

2.2.2. Select switch

Take a look at the operation principle of switch statement
The literal description of the operation principle of switch is as follows: compare c with expression 1. If it is equal, execute statement 1. If it is not equal, continue to compare c with expression 2. If it is equal, execute statement 2. If it is not equal, continue... And so on (nonsense text...)

public class Test02 {
    public static void main(String[] args) {
        /*
            Process control
            switch
                You need to add break after the case statement;
                Otherwise, penetration will occur


            Case 1: the judged value is an integer
         */
        int a = 2;
        switch (a){
            case 1:
                System.out.println("a The value of is 1");
                break;
            case 2:
                System.out.println("a The value of is 2");
                break;
            case 3:
                System.out.println("a The value of is 3");
                break;
            default:
                System.out.println("Invalid number");
        }

        /*
            Case 2: the judged value is character type

         */

        char gender = 'male';
        switch (gender){
            case 'male':
                System.out.println("Male");
                break;
            case 'female':
                System.out.println("female sex");
                break;
            default:
                System.out.println("Invalid gender");
        }

        /*
            Case 3: the judged value is a string

         */
        String gender1 = "1-male";
        switch (gender1){
            case "1-male":
                System.out.println("Male");
                break;
            case "1-female":
                System.out.println("female sex");
                break;
            default:
                System.out.println("Invalid gender");
        }

        /*
            case 4: the cases in the switch statement can be merged
            It uses the penetration phenomenon of case without adding break keyword


            Score 100 90 80 70 passed
            Fail at 60
         */
        int score = 80;
        switch (score){
            case 100:case 90: case 80:
                System.out.println("excellent");
                break;
            case 70:
                System.out.println("secondary");
                break;
            case 60:
                System.out.println("Fail, keep trying");
                break;
            default:
                System.out.println("You have entered an invalid grade");
        }

    }
}

Operation results

2.2.3 circular statement for

In many practical problems, there are many regular repetitive operations, so it is necessary to execute some statements repeatedly in the program. A group of repeatedly executed statements is called the loop body. Whether it can continue to repeat depends on the termination condition of the loop. Loop structure is the process structure of repeatedly executing a certain program under certain conditions. The repeatedly executed program is called loop body. Loop statement is composed of loop body and loop termination condition.

The syntax format is shown in the following figure:

public class test01 {
    public static void main(String[] args) {
        //Case 1: for loop syntax

        //Enter 10 lines Hello World
        //Variables declared in a for loop () can only be in a for loop
        //Cannot be accessed externally
        for(int i = 0; i < 10; i++){
            System.out.println("i="+i);
            System.out.println("Hello World");
        }
        //System.out.println("i="+i);

        System.out.println("--------------------1");

        //The i variable you want to use in the for loop can also be accessed outside the for loop
        //Put the declaration of i on top of the for loop
        //This kind of writing method is not commonly used in the project, but it is not practical
        //The i variable used in the body of the for loop. Generally, the demand can only arrange i to be used in the for loop, and it will hardly be used outside
        //Therefore, our future writing method is still to write the declaration of I variable in for(), for(int i=0; I < 5; I + +)
        int j = 0;
        for( j = 0; j < 10; j++){
            System.out.println(j);
            System.out.println("Hello World");
        }
        System.out.println("j="+j);

        System.out.println("-------------------2");

        //Divided by the above, let's take a look at the following for loop declarations, judgments, and ways to change conditions
        //The way you change conditions is not readable, and it is difficult to predict the final printed information
        for(int k = 10;k > 0;k--){
            System.out.println(k);
            System.out.println("Hello world");
        }


        for(int i=10;i>0;i-=2){
            System.out.println("h w");
        }

        for(int i=100;i>0;i/=3){
            System.out.println("q w");
        }

        //Supplement: about the scope of action of variables
        /*
            Watch the code block {}
            {}Variables declared inside cannot be accessed outside
            Variables declared outside can be accessed inside {}
         */

        //The variables declared in {} cannot be accessed outside
        if(true){
            int  i = 10;
        }
        //System.out.println(i); It's not accessible outside

        int i = 10;
        if(true){
            System.out.println(i);//10
        }

        System.out.println("----------------------3");

        //Case 2: nested use of for loop
        /*
            //Outer circulation
            for(){

                //inner loop 
                for(){

                }
            }

            Inside the inner loop, you can also continue to nest loops indefinitely
            In our actual project development, two layers are most used for nested loops
            3 There is very little demand for layer for loop in the future. The demand for layer 3 + for loop can hardly be used if it does not meet the special needs of special industries

         */

        /*
            Outer cycle
            It is equivalent to a complete execution of the inner loop
         */
        for(int f=0;f<5;f++){

            for(int g=0;g<5;g++){

                System.out.println("g="+g);
            }
            System.out.println("---------------------- f="+f);

        }

        /*
            Notes on for loop:
         */
        //(1) All three expressions in the for loop can be omitted without writing
        //But good points; Cannot be omitted
        //In this case, there will be an infinite cycle. In the IT world, infinite cycle is also called dead cycle
      /*  for(;;){
            System.out.println(123);
        }*/

        //(2) When expression 1 is omitted, a compilation error occurs
        //The solution is to write expression 1 outside the for loop
        //Although it can be solved, don't write that
        int y = 0;
        for(;y <10; y++){
            System.out.println(y);
        }

        //(3) When expression 2 is omitted
        //In case of an endless loop, when expression 2 is omitted, the position of expression 2 will provide us with the value of true by default
        /*for(int l=0;;l++){
            System.out.println(123);//Dead cycle
        }*/

        System.out.println("---------------------------4");

        //(4) When expression 3 is omitted, it is also an endless loop
        //Solution: the change of variables can be written directly inside the loop body
        for(int p=0;p<10;){
            System.out.println(123);
            p++;
        }




    }
}

Operation results

Operation results
i=0
Hello World
i=1
Hello World
i=2
Hello World
i=3
Hello World
i=4
Hello World
i=5
Hello World
i=6
Hello World
i=7
Hello World
i=8
Hello World
i=9
Hello World
--------------------1
0
Hello World
1
Hello World
2
Hello World
3
Hello World
4
Hello World
5
Hello World
6
Hello World
7
Hello World
8
Hello World
9
Hello World
j=10
-------------------2
10
Hello world
9
Hello world
8
Hello world
7
Hello world
6
Hello world
5
Hello world
4
Hello world
3
Hello world
2
Hello world
1
Hello world
h w
h w
h w
h w
h w
q w
q w
q w
q w
q w
10
----------------------3
g=0
g=1
g=2
g=3
g=4
---------------------- f=0
g=0
g=1
g=2
g=3
g=4
---------------------- f=1
g=0
g=1
g=2
g=3
g=4
---------------------- f=2
g=0
g=1
g=2
g=3
g=4
---------------------- f=3
g=0
g=1
g=2
g=3
g=4
---------------------- f=4
0
1
2
3
4
5
6
7
8
9
---------------------------4
123
123
123
123
123
123
123
123
123
123
Process finished with exit code 0

2.2.4 circular statement while

In addition to the for loop, loop statements also include while and do... While. Next, let's take a look at the while loop ~, and first learn the syntax structure of the while loop
As shown in the figure:

The execution principle is shown in the figure below:

public class test02 {
    public static void main(String[] args) {
        /*
            while loop

            As long as the value of boolean in () is true
            The contents of the loop body are executed

            When the value of loolean in () is false
            Then exit the loop body
         */

        //Requirement: print numbers 1, 2, 3, 4, 5
        int t = 1;
        while(t<=5){
            System.out.println(t);
            t++;
        }

        //Use the while loop to make an endless loop
        while(true){
            System.out.println(123);
        }
    }
}

Operation results

2.2.5. Circular statement do... while

The do... While loop is a variant of the while loop. The difference between them is that the do... While loop can = = ensure that the execution times of the loop body are at least 1 times, = = that is, the execution times of the loop body of the do... While loop is 1~N times, which means cutting first and then playing out, while the execution times of the loop body of the while loop is 0~N times.

As shown in the figure:

public class test03 {
    public static void main(String[] args) {
        /*
            do....while loop
            At least once
            First execute the information in the do statement block, and then judge in while()

            This kind of recycling is rarely used
         */

        //Requirement: print numbers 1,2,3,4,5,
        int i=1;
        do{
            System.out.println(i);
            i++;
        }while (i<=5);
    }
}

Operation results

2.2.6 turn statement break

Turn statements are used to realize the jump of program flow in the process of circular execution. In Java, turn statements include break and continue statements.

public class test04 {
    public static void main(String[] args) {
        /*
            break;sentence
            It is used in switch to prevent case penetration

            Used in the loop body to terminate the loop
         */
        //Case 1: for loops 10 times. When the value of i is 5, yes (if the value of i is 5), terminate the loop
        for(int i=0; i <10; i++){
            if(i==5) {
                break;
            }
            System.out.println(i);
        }

        System.out.println("=========================>1");

        //Case 2: break is used in nested loops
        /*
            This conclusion can be reached through the results of the following tests
            break Statement, by default, can only terminate the closest loop
            It will not affect the complete implementation of the outer cycle
         */
        for(int q=0;q<10;q++){
            for(int w=0;w<10;w++){
                if(w==5){
                    break;
                }
                System.out.println("w="+w);
            }
            System.out.println("-----------------q="+q);
        }

        System.out.println("========================>2");

        //If you want to break, terminate the outer loop as well
        //Solution: add specific identification in front of the corresponding for keyword
        //break should choose to exit the loop through the ID




       /* Outer cycle
          It is equivalent to a complete execution of the inner loop*/
        one:for (int i = 0; i < 10; i++) {
            two:for (int j = 0; j < 10; j++) {
                if(j==5){
                    break one;
                }
                System.out.println("j="+j);//01234
            }
            System.out.println("---------------- i="+i);//  break two cycle ten times

        }


    }
}

Result run
0
1
2
3
4
=========================>1
w=0
w=1
w=2
w=3
w=4
-----------------q=0
w=0
w=1
w=2
w=3
w=4
-----------------q=1
w=0
w=1
w=2
w=3
w=4
-----------------q=2
w=0
w=1
w=2
w=3
w=4
-----------------q=3
w=0
w=1
w=2
w=3
w=4
-----------------q=4
w=0
w=1
w=2
w=3
w=4
-----------------q=5
w=0
w=1
w=2
w=3
w=4
-----------------q=6
w=0
w=1
w=2
w=3
w=4
-----------------q=7
w=0
w=1
w=2
w=3
w=4
-----------------q=8
w=0
w=1
w=2
w=3
w=4
-----------------q=9
========================>2
j=0
j=1
j=2
j=3
j=4

Process finished with exit code 0

2.2.7. Turn to statement continue

The continue statement is also a java statement with a single word, such as "continue;", It and the break statement are used to control the loop. The break statement is used to terminate the execution of the loop, while the continue statement is used to terminate the current loop and directly enter the next loop to continue execution.

public class test05 {
    public static void main(String[] args) {
        /*
             continue;sentence
                Terminate this cycle and automatically jump to the next cycle
         */
        //Case: print integer 1 ~ 10, not 5
        for(int i = 0; i < 10; i++){
            if(i==5){
                continue;
            }
            System.out.println(i);
        }


    }
}

Result run

2.2.8 use of Scanner class

Scanner is the console that outputs the running results.

public class Test01 {
    public static void main(String[] args) {
        //Scanner class: input from the operation console (System.out used to output from the console)

        //Create a console input object s
        Scanner s = new Scanner(System.in);
        System.out.println("Please enter an integer");

        //System.out.println("=========================>1");

        //Through s, call the specified next method to receive the specified type of data
        //Receive the input data and assign it to the variable num of type int
        int num = s.nextInt();
        System.out.println("The data entered in the console is:"+num);
        System.out.println("Continue entering a string:");
        String str = s.next();
        System.out.println("The string you entered is:"+str);

    }
}

Operation results



That's all for the above. Follow up...

Topics: Java JavaEE