Keywords and reserved words

The definition and characteristics of a keyword

  • Definition: A string (word) given a special meaning by the Java language for a specific purpose
  • Features: All letters in the keyword are lowercase
  • The official address: docs.oracle.com/javase/tuto…

Java Reserved Word:

The current Java version is not in use, but it may be used as a keyword in future versions. Avoid the reserved words goto and const when naming your own identifiers.

Identifier (Identifier)

Identifier:

  • The sequence of characters Java uses to name elements such as variables, methods, and classes are called identifiers
  • Tip: Call any place you can name yourself an identifier.

Defining rules for legal identifiers :(must be followed. Otherwise, the compilation fails.)

  • Consists of 26 uppercase and lowercase letters, 0-9, _, or $
  • Numbers may not begin.
  • The keyword and reserved word cannot be used, but can contain the keyword and reserved word.
  • Java is case sensitive and has unlimited length.
  • Identifiers cannot contain Spaces.

Naming conventions in Java

Naming conventions :(can be ignored without affecting compilation and running. But you are required to comply)

  • Package name: lowercase letters when multiple words are used: XXXYYYZZz
  • Class name, interface name: When multiple words are used, the first letter of all words is uppercase XxxYyyZzz
  • Variable name, method name: when multiple words are formed, the first word starts with lowercase letters and the second word starts with uppercase letters: xxxYyyZzz
  • Constant name: all letters are capitalized. For multiple words, underline each word: XXX_YYY_ZZZ
  • Note 1: in the name, in order to improve the reading, to be as meaningful as possible, “see the name know the meaning”.
  • Note 2: Java uses the Unicode character set, so identifiers can also be declared using Chinese characters, but this is not recommended.
  • For more details, see Code Clean. PDF. Password: SFMM

Code neatness – About identifiers

  • introduce

    Naming is ubiquitous in software. We name variables, functions, parameters, classes, and packages. We name the source code and the directory in which it resides. So much naming to do, might as well do it.

  • Here are some simple rules for choosing a good name.

    • True to the name, known by its name

      The variable name is arbitrary, and haha, list1, OK, theList, etc., are meaningless

    • To avoid misleading

      Contains class names, keywords, or special words such as List, import, and Java. The letter O and the number 0, the letter L and the number 1, etc. Beware of using smaller names with differences. For example: XYZControllerForEfficientHandlingOfStrings XYZControllerForEfficientStorageOfStrings

    • Make meaningful distinctions

      Negative textbook, variable names: A1, A2, A3

      Avoid redundancy. Avoid Variable, avoid table in a table field, avoid nameString in a string, just name, know it is a string

      For example: define two classes: Customer class and CustomerObject class, how to distinguish?

      GetActiveAccount (), getActiveAccounts(), getActiveAccountInfo().

    • Use readable names

      Don’t use words you cobbled together, such as XSXM (student name); Genymdhms (generated date, year, month, day, hour, minute, second)

      So called hump nomenclature, try to use full words

    • Use searchable names

      For constants, it is best not to use numbers directly, but to specify a variable name that can be easily searched.

      For example, it’s easy to find MAX_CLASSES_PER_STUDENT, but hard to find the number 7.

    • Avoid coding

      • Hungarian notation

        That is, the variable name begins with a lowercase letter indicating the variable’s data type. For example, the prefix sz of szCmdLine stands for “zero-terminated string.”

      • Members of the prefix

        Avoid using prefixes, but a good Android likes to use m for private, etc., personally feel better

      • Interfaces and implementations

        The authors don’t like to start the interface with I, and the implementation wants to just add the ImpL after it

    • Avoid mental mapping

      For example, traditional single-letter names are used for loop counters. So don’t name variables that are not counters: I, j, k, etc

    • The name of the class

      Class and object names should be nouns and noun phrases. Examples are Customer, WikiPage, Account, and AddressParser. Avoid using class names like Data or Info. You can’t use a verb. For example, Manage and Process

    • The method name

      The method name should be a verb or phrasal verb. Such as postPayment, deletePage, or Save

    • Don’t dress up as lovely

      Some variables are called haha and banana

      Don’t say eatMyShorts() abort()

    • Each concept corresponds to a word

      There are controllers and managers in the project, why not use one or the other? For programmers who use your code, a consistent nomenclature is a godsend.

    • No puns

      Sometimes add may not be appropriate, compared to insert and append. Add represents the complete meaning of the new addition.

    • Use the solution domain name

      The people who look at the code are programmers, so try to use computer science terms, algorithm names, schema names, mathematical terms. It’s not smart to name the problem according to the domain it covers.

    • Use names derived from the problem domain. If you can’t name the work at hand in terms familiar to programmers, use names derived from the problem domain. At the very least, the programmer responsible for maintaining the code can consult a domain expert.

    • Add meaningful context

      You can put related variables into a class and use this class to indicate context.

    • Don’t add useless context

      It’s not necessary to have an acronym for the project in the name. For example, there is a project called “Gas Station Deluxe” where adding a GSD prefix to each class is not a good strategy.

    • The last word

      The hardest part about choosing a good name is that it requires good descriptive skills and a shared cultural background.

variable

What is a variable? Variables are the concepts of algebra in junior high school mathematics, such as a simple equation, x and y are variables: y=x+1Copy the code

Concept of variable:

  • A storage area in memory
  • The data in this region can vary over time within the same type range
  • Variables are the most basic storage unit in a program. Contains the variable type, variable name, and stored value

Functions of variables:

  • Used to hold data in memory

Using variables Note:

  • In Java, each variable must be declared before it is used
  • Use the variable name to access the data in this area
  • Scope of a variable: the pair {} in which it is defined
  • A variable is only valid within its scope, and within its scope, it is valid. In other words, out of scope, out of scope
  • Variables with the same name cannot be defined in the same scope

Declare a variable

  • Syntax: < data type > < variable name >

    For example, int var;

Assignment of a variable

  • Syntax: < variable name > = < value >

    For example, var = 10;

Declare and assign variables

  • Syntax: < data type > < variable name > = < initial value >

    For example, int var = 10;

Classification of variables

By data type

Specific data types (strongly typed languages) are clearly defined for each type of data, and different sizes of memory space are allocated in memory.Copy the code

Depending on the location of the declaration

  • Outside of a method, variables declared inside a class are called member variables.
  • Variables declared inside a method body are called local variables.

  • Note the similarities and differences in initialization values:

    Both have a life cycle

    Different: Local variables must be explicitly initialized except for parameters.

Integer types

Integer types: byte, short, int, and long

  • Each Integer type in Java has a fixed table number range and field length, independent of the specific OS, to ensure the portability of Java programs.
  • Java integer constants default to int, declare long constants must be followed by ‘l’ or ‘l’
  • Variables in Java programs are usually declared as ints, except when long is not sufficient to represent a large number

1MB = 1024KB 1KB= 1024B B= byte ? bit? Bit: The smallest unit of storage in a computer. Byte: indicates the basic storage unit of a computer.Copy the code

Floating point types

Floating point types: float, double

  • Like integer types, Java floating point types have a fixed range of table numbers and field lengths, independent of the operating system.

  • Floating-point constants can be represented in two ways:

    • Decimal number: 5.12 512.0 F. 512 (must have a decimal point)

    • Scientific notation: 5.12e2 512E2 100E-2

  • Float: single-precision, mantissa can be accurate to 7 significant digits. In many cases, accuracy is difficult to meet.

    Double: the precision is twice that of float. This type is usually used.

  • Java floating-point constants default to double and declare float constants followed by ‘f’ or ‘f’.

Character types

Character type: char(1 character =2 bytes)

  • Char data is used to represent “characters” in the usual sense (2 bytes)

  • All characters in Java are encoded in Unicode, so a character can store a letter, a Chinese character, or a character of another written language.

  • There are three representations of character variables:

    • A character constant is a single character enclosed in single quotes (‘ ‘). Char c1 = ‘a’; Char c2= ‘c ‘; char c3 = ‘9’;

    • Java also allows the use of the escape character ‘\’ to convert the following character into a special character type constant.

      For example: char c3 = ‘\n’; // ‘\n’ represents a newline character

    • Use Unicode values directly to represent character constants: ‘\uXXXX’. XXXX is a hexadecimal integer. For example: \u000a means \n.

  • The char type is operable. Because they all have Unicode codes.

Understand: ASCII code

  • Inside the computer, all data is represented in binary. Each bit has two states, zero and one, so eight bits can combine 256 states, which is called a byte. A byte can be used to represent a total of 256 different states, and each state corresponds to a symbol, that is, 256 symbols, ranging from 0000000 to 11111111.
  • ASCII code: last century in the 1960s, the United States developed a set of character codes, the relationship between English characters and binary bits, do uniform rules. This is called ASCII code. ASCII codes specify A total of 128 characters, such as 32 for the SPACE “SPACE” (binary 00100000) and 65 for the uppercase letter A (binary 01000001). The 128 symbols (including 32 non-printable control symbols) occupy only the last seven bits of a byte, with the first bit uniformly specified as zero.
  • disadvantages:
    • Cannot represent all characters.
    • The same code represents different characters: 130, for example, stands for e in French, but Gime in Hebrew (ג)

Understand: Unicode encoding

  • Garbled code: There are many encoding methods in the world, the same binary number can be interpreted as different symbols. Therefore, in order to open a text file, it is necessary to know how it is encoded, otherwise it will be garbled if it is interpreted in the wrong way.
  • Unicode: the code that includes all the symbols in the world. Each symbol is given a unique encoding, and there are no garbled problems with Unicode.
  • Disadvantages of Unicode: Unicode only specifies the binary of a symbol, but not how that binary should be stored: Cannot distinguish Unicode from ASCII: computers cannot distinguish between three bytes representing one symbol and three symbols separately. In addition, we know that a single byte is enough to represent an English letter, and if Unicode were to specify three or four bytes for each character, two or three bytes of zeros must precede each letter, which is a huge waste of storage space.

Understand: utf-8

  • Utf-8 is the most widely used implementation of Unicode on the Internet.
  • Utf-8 is a variable length encoding. It can represent a symbol in 1-6 bytes, varying the length of the byte depending on the symbol.
  • Utf-8 encoding rules:
    • For single-byte UTF-8 encoding, the highest bit of this byte is 0, and the remaining 7 bits are used to encode characters (equivalent to ASCII).
    • For multi-byte UTF-8 encodings, if the encodings contain n bytes, the first n bits of the first byte are 1, the n+1 bits of the first byte are 0, and the remaining bits of the byte are used to encode the characters. All bytes after the first byte have the top two bits of “10” and the remaining six bits are used to encode characters.

First, the basic knowledge of coding

1. The bit is the smallest unit in a computer

Byte The unit of machine language

    1 byte = 8 bits
    1 KB = 1024 byte
    1 MB = 1024 KB
    1 GB = 1024 MB
Copy the code

(2) into the system

Binary octal decimal Decimal hexCopy the code

3

Character: is the general name of various characters and symbols, including the characters of various countries, punctuation marks, graphic symbols, numbers, etc.

Character set: A character set is a collection of symbols, each containing a different number of characters.

Character encoding: The character set only specifies which characters are available, but the final decision on which characters to use and how many bytes to represent each character is determined by the encoding. To process various characters accurately, the computer needs to carry out character coding so that the computer can recognize and store various characters.

Second, the introduction of common character encoding

Let’s take a look at some common encodings, from Notepad++. Among them, ANSI in Mainland China is GBK (GB2312 before), GBK and UTF8 are most commonly used without BOM encoding format. The last three are text formats with BOM headers. Ucs-2 is commonly known as Unicode encoding, which is divided into big encoder and small encoder.

A Byte Order Mark (BOM) is the first few bytes in a text file that do not represent any characters and can be seen using a binary editor (such as bz.exe).

The UTF8 BOM header is 0xEF 0xBB 0xBF Unicode big-ende mode is 0xFE 0xFF Unicode small-ende mode is 0xFF 0xFECopy the code

ASCII

Computers were first invented to solve numerical problems, but later people found that computers could do more things, such as text processing. But since computers only know “numbers”, they must be told which number to represent which particular character, for example 65 for the letter ‘A’, 66 for the letter ‘B’, and so on. However, the character-number correspondence between computers must be consistent, otherwise the same number will appear differently on different computers. So the American National Standards Institute, ANSI, developed a standard that defines the Set of commonly used characters and the corresponding number for each Character. This is the ASCII Character Set, also known as ASCII code. At that time, the character codec system was very simple, it was a simple table lookup process. For example, to encode a character sequence into a binary stream and write it to the storage device, you only need to find the corresponding bytes in the ASCII character set and directly write the bytes to the storage device. The process of decoding a binary stream is similar.

Among them:

  • 0 ~ 31 and 127(a total of 33) are control characters or communication special characters (the rest are displayable characters), such as control characters: LF (newline), CR (enter), FF (page change), DEL (delete), BS (backspace)
  • The value contains 95 characters ranging from 32 to 126(32 is a space). The value 48 to 57 contains 0 to 9 Arabic digits.
  • There are 26 upper-case letters ranging from 65 to 90, 26 lower-case letters ranging from 97 to 122, and other punctuation marks and operation symbols.
  • The last 128 are called extended ASCII codes. Many x86-based systems support the use of extended (or “high”) ASCII. Extended ASCII allows the 8th bit of each character to be used to determine the additional 128 special symbolic characters, loanword letters, and graphic symbols.
PDF download address:Character Set.PDFPassword: SFMM

OEM character set derivation

As computers began to develop, people began to realize that the 128 characters in the ASCII character set were no longer enough for them. One byte can represent 256 digits, and ASCII characters only use 0x00~0x7F. That is, the first 128 digits are used, so many people have the idea of the last 128 digits. The problem is that many people have this idea at the same time, but they have different ideas about what the 128 digits following 0x80-0xff correspond to. This resulted in a wide variety of OEM character sets available on machines sold around the world at the time. The interpretation of the range 0x00~0x7F is basically the same, but the interpretation of the second part 0x80~0xFF is not necessarily the same. Sometimes even the same characters correspond to different bytes in different OEM character sets. Different OEM character sets made it impossible for people to communicate various documents across machines. For example, employee A sends a resume resumes to employee B and employee B sees an R? sum? S, because e corresponds to 0x82 bytes in the OEM character set on employee A’s machine, but on employee B’s machine, because the OEM character set is different, decoding 0x82 bytes will result in a character? .

Multi-byte Character Set (MBCS) and Chinese character set

The character sets mentioned above are based on single-byte encodings, that is, one byte is translated into one character. This may not be a problem for The Latino-speaking countries, because by extending the eighth bit, they get 256 characters, which is enough. But for Asian countries, 256 characters is far from enough. Therefore, in order to use computers in these countries and to remain compatible with the ASCII character Set, the multi-byte encoding method was invented. The corresponding character Set is called the muilti-bytes Charecter Set. China, for example, uses double-byte character set encoding. For example, the most commonly used Chinese character set GB2312 covers all simplified characters and some other characters. GBK (K represents the meaning of extension) in GB2312 on the basis of the addition of traditional characters and other non-simplified characters. Characters in both character sets are represented by 1-2 bytes. Windows system uses 936 code page to encode and decode GBK character set. When parsing a byte stream, if the highest bit of a byte is 0, the first table in the 936 code page is used to decode the byte stream, which is consistent with single-byte character sets. If the highest bit of a byte is 1, it means that two byte values are required for one character.

Suppose you write this sentence in GB2312: My name is ABC

Its binary encoding looks like this:

The Angle?

Full corner is a computer character, and each full corner character takes up two standard character (or half corner character) positions. Letters, numbers, and symbols are half – corner, and the display code of half – corner is one byte. English and other Latin characters and punctuation are also provided in full corner format for order. In the Chinese input method, the shortcut key for switching full-angle and half-angle formats is SHIFT+ space.

ANSI standards, National standards, ISO standards

The emergence of different ASCII derived character sets made it very difficult for documents to communicate, so various organizations continued to standardize processes. For example, the American ANSI organization has developed the ANSI standard character code (note that we now usually refer to the ANSI code, usually refers to the default platform code, such as ISO-8859-1 in English operating system, GBK in Chinese system), ISO organizations have developed various ISO standard character codes, There are also some national standard character sets, such as GBK, GB2312 and GB18030 in China. Operating systems usually ship with these standard character sets and platform-specific character sets, so as long as your documents are written in the standard character set, they are more versatile. For example, a document you write with the GB2312 character set will display correctly on any machine in mainland China. At the same time, we can also read documents in multiple countries and different languages on a single machine, provided that the native machine has the character set used for the document installed.

The emergence of the Unicode

Although it is possible to look up documents in different languages on a single machine by using different character sets, we still cannot solve the problem that if a document contains characters from different languages in different countries, it cannot display all characters in a single document. To solve this problem, we need a huge character set that all of humanity can agree on, which is the Unicode character set.

The Unicode character set covers all characters currently used by humans, and each character is uniformly numbered and assigned a unique Code Point. The Unicode character set divides all characters into 17 planes according to their frequency of use, each of which has 2 16=65536 character code Spaces. The 0 level BMP covers almost all characters used in today’s world. Other layers are either used to represent ancient texts or are reserved for extension. The Unicode characters we use are usually at the BMP level. There is a large amount of unused character space in the Unicode character set.

Changes in the coding system

Before Unicode, all character sets were bound to a specific encoding scheme (i.e., character set ≈ encoding), which directly bound the character to the final byte stream. For example, the ASCII encoding system required the use of 7 bits to encode the ASCII character set. GB2312, as well as the GBK character set, limits the use of up to 2 bytes to encode all characters, and specifies the byte order. Such encodings often use simple lookups, which map characters directly to byte streams on storage devices through code pages. Take this example:

Unicode is also not perfect, and there are three problems. One is that, as we already know, only one byte is enough for the English letter, and the other is how do you distinguish Unicode from ASCII? How does the computer know that two bytes represent one symbol, rather than two separate symbols? Third, if the highest bit is 1 or 0 to represent two bytes and one byte, as is the case with GBK and other double-byte encodings, there are too few values to represent characters, not enough to represent all characters. Unicode was not widely used for a long time until the advent of the Internet. In order to solve the problem of how to Transfer Unicode over the Internet, a variety of UTF (UCS Transfer Format) standards for transmission emerged. As the name implies, UTF-8 is to Transfer data eight bits at a time. Utf-16 is 16 bits at a time.Utf-8 is the most widely used implementation of Unicode on the InternetThis is code designed for transmission and makes it borderless so that it can display characters from all cultures around the world.

One of the biggest features of UTF-8 is that it is a variable length encoding method. It can use 1 to 4 bytes to represent a symbol. The conversion from Unicode to UFT-8 is not a direct correspondence, but requires some algorithms and rules (Uncidoe character set ≠UTF-8 encoding).

Thus, Unicode simply defines a large, universal character set and assigns a unique number to each character, depending on the character encoding scheme. The recommended Unicode encodings are UTF-16 and UTF-8.

Early concepts like character encodings, character sets, and code pages all meant the same thing. For example, the GB2312 character set, the GB2312 code, the 936 code page, actually say the same thing. However, for Unicode, the Unicode character set only defines a set of characters and unique numbers, while Unicode encoding is a general term for utF-8, UCS-2/UTF-16 and other specific encoding schemes, rather than a specific encoding scheme. So when it comes to character encodings, you can write GB2312, codepage936, UTF-8, UTF-16, but don’t write Unicode. Garbled characters are caused by using the wrong character encoding to decode the byte stream, so when we think about anything related to text display, keep in mind what character encoding is currently in use. Only in this way can we correctly analyze and deal with the problem of garbled code.

Common charsets include GBK, GB2312, US-ASCII, ISO-8859-1, UTF-8, UTF-16BE, UTF-16LE, and UTF-16

Boolean type

Boolean type: Boolean

  • The Boolean type is used to determine logical conditions. It is commonly used for program flow control:

    • If condition control statement;
    • While loop control statement;
    • Do -while loop control statement;
    • For loop control statement;
  • Boolean data can be true and false only, but not NULL.

    • Unlike C, you cannot replace false and true with 0 or non-0 integers.
    • The Java virtual machine does not have any bytecode instructions dedicated to Boolean values. The Java language uses the Java virtual machine’s int data type to replace Boolean values after compilation: true is represented by 1, false by 0. — Java Virtual Machine Specification Version 8

Basic data type conversion

Automatic type conversion (involving only the 7 basic data types)

Data types with small capacity are automatically converted to data types with large capacity. Data types are as follows in order of capacity:

  • When multiple types of data are mixed, the system automatically converts all data to the data type with the largest capacity before computing.
  • Byte,short, and char are not converted to each other; they are first converted to int when evaluated.
  • Boolean types cannot operate with other data types.
  • When concatenating the value of any primitive data type with a String (+), the value of the primitive data type is automatically converted to String.
  • Note: at this time the capacity size refers to the number of large and small range. For example, float has more capacity than long

Cast (only for the 7 basic data types)

  • The reverse process of automatic type conversion to convert a high-capacity data type to a low-capacity data type. Use the cast character :(), but it may cause loss of accuracy or overflow.
  • In general, strings cannot be converted to primitive types directly, but they can be converted to primitive types through the wrapper class corresponding to the primitive type.
    • For example, String a = “43”; int i = Integer.parseInt(a);
    • Boolean types cannot be converted to other data types.

String type

String type: String

  • String is not a basic data type; it is a reference data type

  • String is an immutable sequence of characters implemented in the char[] array

  • Use the same as the basic data type. For example, String STR = “abcd”;

  • A string can be concatenated to another string or directly concatenated to other types of data. Such as:

    STR = STR + "xyz"; int n = 100; str = str + n;Copy the code
  • Example – StringTest class

public class StringTest {
     public static void main(String[] args) {
         int no = 10;
         String str = "abcdef";
         String str1 = str + “xyz” + no;
         str1 = str1 + "123";
         char c = 'the';
         double pi = 3.1416;
         str1 = str1 + pi;
         boolean b = false;
         str1 = str1 + b;
         str1 = str1 + c;
        System.out.println("str1 = "+ str1); }}Copy the code

Base (understanding)

There are 10 kinds of people in the world who know and don’t know binary.

On the base

  • All numbers exist in binary form at the bottom of the computer.

  • For integers, there are four representations:

    • Binary: 0,1,1. Start with 0b or 0b.

    • Decimal (decimal) : 0-9, decimal into 1 after 10.

    • Octal: 0-7, 1 in the full 8, starting with the digit 0.

    • Hex: hexadecimal number (0-9 or a-F). 1. The value starts with 0x or 0x. A-f here is case insensitive.

      0x21AF +1= 0X21B0

binary

  • Java integer constants default to int, and when integers are defined in binary, their 32nd bit is a sign bit. For long, binary defaults to 64 bits, with the 64th being the sign bit

  • Binary integers have the following three forms:

    • Source code: Converts a value directly to a binary number. The highest bit is the sign bit
    • The inverse of a negative number is the reverse of the original code, except that the highest bit (sign bit) is determined to be 1.
    • The complement of a negative number: its inverse is added by 1.
  • The computer keeps all integers in the form of binary complement.

    • Positive numbers have the same source code, inverse code and complement
    • The complement of a negative number is its inverse +1
  • Why use source, inverse, complement representations?

    Computer recognition of “sign bits” obviously complicates the basic circuit design of a computer! So people came up with a way to include sign bits in the operation. We know that according to the algorithm subtracting a positive number is equal to adding a negative number, i.e., 1-1 = 1 + (-1) = 0, so the machine can only add without subtracting, making the design of computer operations much easier.

Conversion between bases

  • Basic conversion of base

    • Decimal binary rotation

      • Binary to decimal times a power of two

      • Decimal to binary divided by 2 for remainder

    • Binary octal reversal

    • Binary hexadecimal mutual transfer

    • Decimal octal reversal

    • Decimal hexadecimal mutual transfer

The operator

An operator is a special symbol used to represent operations, assignments, comparisons, etc.

  • Arithmetic operator
  • The assignment operator
  • Comparison operators (relational operators)
  • Logical operator
  • An operator
  • Ternary operator

Attention to arithmetic operators

  • If you take the modulus of a negative number, you can ignore the minus sign of the modulus, for example: 5%-2=1. However, if the modulus is negative, it cannot be ignored. Furthermore, the result of modulo operations is not always an integer.
  • For the division sign “/”, there is a difference between integer division and decimal division: when dividing integers, only the integer part is kept and the decimal part is discarded. For example, int x=3510; x=x/1000*1000; What is the result of x?
  • In addition to adding strings, “+” can also convert non-strings to strings. For example: System. Out. Println (” 5 + 5 = “+ 5 + 5); // What is the print result? 5 + 5 = 55?

Special instructions

1. / / (former) + + : since the first 1, operation / / (back) + + : after first operation, since the increased after 1 2. / / (former) - : since the first minus 1, after the operation / / (after) - : before operation, after the minus 1 3. The hyphen: + : can only be used between strings and other data type variables.Copy the code

Typical code

    // Divisor: /
    int num1 = 12;
    int num2 = 5;
    int result1 = num1 / num2;
    System.out.println(result1);/ / 2
    
    // %: mod operation
    // The result has the same sign as the moduli
    // In development, % is often used to determine whether it can be divisible.
    int m1 = 12;
    int n1 = 5;
    System.out.println("m1 % n1 = " + m1 % n1);

    int m2 = -12;
    int n2 = 5;
    System.out.println("m2 % n2 = " + m2 % n2);

    int m3 = 12;
    int n3 = -5;
    System.out.println("m3 % n3 = " + m3 % n3);

    int m4 = -12;
    int n4 = -5;
    System.out.println("m4 % n4 = " + m4 % n4);
    
    //(front)++ : increment 1 first, then calculate
    //(after)++ : calculate first, then increment by 1
    int a1 = 10;
    int b1 = ++a1;
    System.out.println("a1 = " + a1 + ",b1 = " + b1);

    int a2 = 10;
    int b2 = a2++;
    System.out.println("a2 = " + a2 + ",b2 = " + b2);

    int a3 = 10;
    ++a3;//a3++;
    int b3 = a3;
    //(before)-- : first subtract 1, then calculate
    //(after)-- : calculate first, then subtract 1

    int a4 = 10;
    int b4 = a4--;//int b4 = --a4;
    System.out.println("a4 = " + a4 + ",b4 = " + b4);
Copy the code

The assignment operator

  • Symbol: =

    • When the data types on both sides of “=” are inconsistent, you can use automatic type conversion or cast principle to handle the problem.
    • Continuous assignment is supported.
  • Extended assignment operators: +=, -=, *=, /=, %=

Special instructions

1. The result of the operation does not change the data type of the variable itself. 2. Int num = 10; Num = num + 2; Num += 2; (Recommended) In development, if you want a variable to implement +1 operation, how many ways? Int num = 10; Num = num + 1; Num += 1; Method 3: num++; (recommended)Copy the code

Typical code

int i2,j2;
// Continuous assignment
i2 = j2 = 10;

/ * * * * * * * * * * * * * * * /
int i3 = 10,j3 = 20;
int num1 = 10;
num1 += 2;//num1 = num1 + 2;
System.out.println(num1);/ / 12

int num2 = 12;
num2 %= 5;//num2 = num2 % 5;
System.out.println(num2);

short s1 = 10;
//s1 = s1 + 2; // Failed to compile
s1 += 2;// Conclusion: The data type of the variable itself is not changed
System.out.println(s1);
Copy the code

Comparison operator

  • The results of comparison operators are Boolean, that is, either true or false.

  • The comparison operator “==” cannot be mistakenly written as “=”.

Special instructions

1. The result of the comparison operator is of Boolean type 2.> < >= <= : Can only be used between data of numeric type. 3. = = and! =: can be used not only between numeric type data, but also between variables of other reference types. Account acct1 = new Account(1000); Account acct2 = new Account(1000); boolean b1 = (acct1 == acct2); // Compare whether two accounts are the same Account. boolean b2 = (acct1 ! = acct2);Copy the code

Typical code

int i = 10;
int j = 20;

System.out.println(i == j);//false
System.out.println(i = j);/ / 20

boolean b1 = true;
boolean b2 = false;
System.out.println(b2 == b1);//false
System.out.println(b2 = b1);//true
Copy the code

Operators: Logical operators

& - logic and | - logic or! - logic && - short circuit and | | - short circuit or ^ - xor logicCopy the code

  • The logical operator is used to concatenate Boolean expressions. Instead of writing 3<x<6 in Java, it should be written x> 3&x <6.

  • The difference between & and & :

    • Single &, whether the left side is true or false, the right side is calculated;
    • For double &, if the left is true, the right is involved, and if the left is false, the right is not involved.
  • “|” and “| |” in the same way, the difference between a | | said: when the left side is true, the right not to participate in the operation.

  • Xor (^) and or (|), the difference is: when all is true, the result is false.

    Understanding: different or, what pursue is “different”!

Special instructions

1. Logical operators operate on Boolean variables. The result is also a Boolean type

Typical code

// Distinguish & from &&
1: & and && have the same result
// Similarity 2: When the left side of the symbol is true, both perform the operation on the right side of the symbol
// difference: When the left side of the symbol is false, & continues to perform the operation on the right side of the symbol. Am& no longer performs the operation to the right of the symbol.
// In development, the recommended use of &&
boolean b1 = true;
b1 = false;
int num1 = 10;
if(b1 & (num1++ > 0)){
        System.out.println("I'm in Beijing now.");
}else{
        System.out.println("I'm in Nanjing now.");
}
System.out.println("num1 = " + num1);


boolean b2 = true;
b2 = false;
int num2 = 10;
if(b2 && (num2++ > 0)){
        System.out.println("I'm in Beijing now.");
}else{
        System.out.println("I'm in Nanjing now.");
}
System.out.println("num2 = " + num2);

/ / to distinguish: | and | |
/ / the same 1: | and | | operation result is the same
// Similarity 2: When the left side of the symbol is false, both perform the operation on the right side of the symbol
/ / the difference 3: when the symbol on the left is true | continue symbol to the right of the operation, and | | no longer perform symbol to the right of the operation
/ / development, it is recommended to use | |
boolean b3 = false;
b3 = true;
int num3 = 10;
if(b3 | (num3++ > 0)){
        System.out.println("I'm in Beijing now.");
}else{
        System.out.println("I'm in Nanjing now.");
}
System.out.println("num3 = " + num3);


boolean b4 = false;
b4 = true;
int num4 = 10;
if(b4 || (num4++ > 0)){
        System.out.println("I'm in Beijing now.");
}else{
        System.out.println("I'm in Nanjing now.");
}
System.out.println("num4 = " + num4);
Copy the code

An operator

  • Bitwise operations are operations performed directly on the binary of an integer

Special instructions

  1. Bitwise operators operate on integer data

  2. << : Within a certain range, every 1 bit to the left is equal to * 2

    >> : within a certain range, every 1 bit to the right is equal to / 2

Typical code

    int i = 21;
    i = -21;
    System.out.println("i << 2 :" + (i << 2));
    System.out.println("i << 3 :" + (i << 3));
    System.out.println("i << 27 :" + (i << 27));

    int m = 12;
    int n = 5;
    System.out.println("m & n :" + (m & n));
    System.out.println("m | n :" + (m | n));
    System.out.println("m ^ n :" + (m ^ n));
Copy the code

The interview questions

Can you write the most efficient 2 * 8 implementation?

Answer: 2 << 3 or 8 << 1

Ternary operator

Special instructions

(1) The result of the conditional expression is Boolean. (2) Depending on whether the conditional expression is true or false, decide whether to execute expression 1 or 2. If the expression is true, expression 1 is executed. If the expression is false, expression 2 is executed. ③ The requirements of expression 1 and expression 2 are identical. If (else) {if (else) {if (else) {if (else) {if (else) { 3. If the program can use both ternary operators and if-else constructs, the ternary operators are preferred. Reason: Simple and efficient.Copy the code

The priority of the operator

  • Operators have different priorities, which are the order of operations in an expression operation. As shown in the right table, the previous line always takes precedence over the next line.
  • Only the unary, ternary, and assignment operators operate from right to left.