[Take you step by step to learn JavaSE] Part 3: Operators and program logic control

Preface

Hello everyone ~ I’m here again! Today I will summarize the knowledge about operators and program logic control! Let’s start learning today!

correct! I would like to recommend you a tool for studying and interviewing questions——Niuke.com




There are a lot of question banks and interview experience in it ~ very conscientious! !

1. Operator

1.1 Arithmetic operators

Basic four arithmetic operators: + / * %

These operators have been discussed in detail in C language!
It’s worth noting the division:

0 cannot be used as a divisor! ! !

% represents remainder. It can not only modulo int, but also modulo double.

Incremental assignment operator += -= *= /= %=

Increment/decrement operator++ –

in conclusion:
1. If the return value of the expression of the auto-increment operation is not taken, there is no difference between pre-increment and post-increment.
2. If the return value of an expression is taken, the return value of the preceding auto-increment is the value after the auto-increment, and the return value of the post-increment is the value before the auto-increment.

1.2 Relational operators

There are six main relational operators:

Note: The expression return values ​​of relational operators are all of type boolean.

1.3 Logical operators

There are three main logical operators: && || !



1.4 bit operators

There are four main bitwise operators: & | ~ ^

1.5 Shift operation

There are three shift operators:

<< >> >>>
Java is equivalent to C language with one more >>>
This is an unsigned right shift: the rightmost bit is omitted and the leftmost bit is filled with 0
Right shift>>: The rightmost bit is omitted, and the sign bit is added to the leftmost bit (positive numbers are filled with 0, negative numbers are filled with 1)
Shift left<<: The leftmost bit is omitted, and the rightmost bit is filled with 0.

Notice:
1. Shift 1 bit to the left, which is equivalent to the original number * 2. Shift N bits to the left, which is equivalent to the Nth power of the original number * 2.
2. Shift right by 1 bit, which is equivalent to the original number / 2. Shift right by N bits, which is equivalent to the Nth power of the original number / 2.
3. Since the computer is more efficient in calculating shifts than in calculating multiplication and division, when a certain code exactly multiplies and divides 2 to the Nth power, it can be replaced by a shift operation.
4. It is meaningless to move negative digits or shift digits that are too large.

1.6 Conditional operators

There is only one conditional operator: Expression 1 ? Expression 2 : Expression 3 (all Boolean expressions)

If expression 1 is true, the result is expression 2. expression1 is false, the result is expression3

2. Comments

Comments are additional descriptive information to make the code easier to read. They do not participate in compilation and execution, but they are very important.

Always remember! The code is written for others to see, and it is also for yourself to see three months later.

2.1 Basic rules

Annotations in Java are mainly divided into the following three types:

Single line comment: //Comment content (most commonly used)
Multi-line comments: /* Comment content*/ (not recommended)
Documentation comments: /** Documentation comments*/ (commonly used on methods and classes to describe the functions of methods and classes), can be used to automatically generate documentation

2.2 Annotation specifications

1. Accurate content: The comment content should be consistent and matched with the code, and should be updated in a timely manner when the code is modified.
2. Reasonable length: Notes should neither be too concise nor lengthy.
3. Use Chinese: Generally, Chinese companies require notes to be written in Chinese, while foreign companies are a different matter.
4. Be positive: Do not include negative energy in comments (such as leader SB, etc.).

3. Keywords

Get to know some keywords for the first time

4. Sequential structure


If you adjust the writing order of the code, the execution order will also change.

5. Branch structure

5.1 if statement

Example:

public static void main(String[] args) {
        int n = 10;
        //if can only contain Boolean expressions
        if(n % 2 == 0) {
            System.out.println("even number");
        }else{
            System.out.println("odd number");
        }
 
    }
}


Read in string

Read the string. If there are spaces in the string, end it when it encounters a space.

If you want to read a string and an integer, read the string first and then the integer.

If you want to simply use the input function, you can use it. During the project, be careful! ! ! ! ! !

Determine whether it is a leap year:

public class TestDemo {
 
  Method 1: public static void main1(String[] args) {
        int year = 2000;
        if (year % 100 == 0) {
            if (year % 400 == 0) {
                System.out.println("It's a leap year");
            } else {
                System.out.println("Not a leap year");
            }
        } else {
            if (year % 4 == 0) {
                System.out.println("It's a leap year");
            } else {
                System.out.println("Not a leap year");
            }
        }
    }
 
  Method 2: public static void main(String[] args) {
        int year = 2000;
        if(year % 100!= 0 && year % 4== 0 ||year % 400 == 0){
            System.out.println("It's a leap year");
        }else{
            System.out.println("Not a leap year");
        }
 
 
    }
}

draping else problem

You don’t need to add braces in the if / else statement. But you can also write a statement (only one statement can be written). At this time, else matches the closest if.

However, we do not recommend writing it like this in actual development. It is best to add braces.
Code style issues

//I prefer it in java
int x = 10;
if(x == 10){
	//To meet the conditions
}else{
	//The conditions are not met
}

Although both methods are legal, it is recommended to use style 1 in Java, with { placed on the same line as if / else.

semicolon problem

int x = 20;
if(x == 10):{
	System . out . p ri ntl n (" hehe") ;
}
//Print results
hehe

An extra semicolon is written here, causing the semicolon to become the statement body of the if statement, and the code in { } has become a code block that has nothing to do with an if.

5.2 switch statement


Example:

public static void main(String[] args) {
        //long double float boolean cannot be used as a parameter in the switch statement
        int a = 10;
        switch (a){//There is an expression in the parentheses. It must be a simple expression, not like the C language, for example, a>=10 && a<=20
            case 1:
                System.out.println("1");
                break;
            case 2:
                System.out.println("2");
            default:
                System.out.println("Parameters do not match");
                break;
        }
    }
}

String type can be used as parameter of switch statement in Java

Depending on the value in switch, the corresponding case statement will be executed. When break is encountered, the case statement will end.
If the value in switch does not have a matching case, the statement in default will be executed.
We recommend that every switch statement should have default
We found that when break is not written, the case statements will be executed downwards in sequence, thus losing the multi-branch effect.

Note 1
Don’t omit break, otherwise you will lose the effect of “multi-branch selection”
Note 2
The value in switch can only be integer | enumeration | character | string
Note 3 switch cannot express complex conditions
For example: If the value of num is between 10 and 20, print hehe
Such code is easy to express using if, but it cannot be expressed using switch.

6. Loop structure

6.1 while loop

Basic syntax format:

while(Boolean expression){

statement block;

}

If the loop condition is true, the loop statement will be executed; otherwise, the loop will end.
Example:

Find the sum of 1 to 10   
public static void main(String[] args) {
       int i = 1;
       int sum = 0;
       while(i <=10) {
           sum += i;
           i++;
       }
        System.out.println(sum);
    }
}
 
Find the factorial of n
 
    public static void main(String[] args) {
        int j = 3;
        int ret = 0;
            int sum = 1;
            int i = 1;
                while(i<=j) {
 
                    sum *=i;
                    i++;
                }
        System.out.println(sum);
 
        }

Precautions:

  1. Similar to if, the statement below while does not need to write { }, but when it is not written, it can only support one statement. It is recommended to add { }

  2. Similar to if, the { after while is recommended to be written on the same line as while.

  3. Similar to if, do not write more semicolons after while, otherwise the loop may not be executed correctly.

6.2 break

The function of break is to end the loop early

Code example: Find the first multiple of 3 in 100 – 200

public static void main(String[] args) {
        int num = 100;
        while (num <= 200) {
            if (num % 3 == 0) {
                System.out.println("Found a multiple of 3, which is: " + num);
                break;
            }
            num++;
        }
// Results of the
        //Found a multiple of 3, which is: 102

Execution to break will end the loop.

6.3 continue

The function of continue is to skip this loop and immediately enter the next loop.

Example:

//Find the triple number between 1 and 10
 
public static void main(String[] args) {
        int i = 1;
        while(i<=10) {
            if(i % 3 !=0 ){
                i++;
                continue;
            }
            System.out.println(i);
                  i++;
        }

When the continue statement is executed, it will immediately enter the next loop (determine the loop condition), so that the print statement below will not be executed.

Summary: break ends all loops, continue ends this loop

Both break and continue must be in a loop, [Special: break can be in a switch statement]

6.4 for loop

Basic syntax:

for(Boolean expression 1; Boolean expression 2; Boolean expression 3) {

statement block;

}
Example:

//Find the sum between 1 and 100 
public static void main(String[] args) {
       int sum = 0;
        for (int i = 1; i <= 100; i++) {
            sum += i;
        }
        }

Things to note (similar to while loop)

  1. Similar to if, the statement below for does not need to write { }, but when it is not written, it can only support one statement. It is recommended to add { }

  2. Similar to if, the { after for is recommended to be written on the same line as while.

  3. Similar to if, do not write more semicolons after for, otherwise the loop may not be executed correctly.

6.5 do…while loop

Basic syntax do{

loop statement;

}while(loop condition);

The loop statement is executed first, and then the loop condition is determined.

Example:

//Print 1-10
public static void main(String[] args) {
    int num = 1;
    do {
        System.out.println(num);
        num++;
    } while (num <= 10);
}

Precautions:

  1. Don’t forget the semicolon at the end of the do while loop

  2. Generally, do while is rarely used, and for and while are more recommended.

Related Posts

Java experiment – define a class Student that represents student information, the requirements are as follows:

Huawei Cloud IOT Android application development detailed tutorial

Why do many people with computer majors switch careers and quit computer science after graduation? [Revealing the truth]

IDEA’s high-quality plug-in Translation has updated its translation engine following the IDEA 2022.3 version.

[SpringBoot Series] How SpringBoot integrates SSMP

JAVA Exercise 73-III. Printing Binary Tree from Top to Bottom III

Alibaba Yu Jun: DingTalk should take the path of low-code practice

Distributed ID solution

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*