Java interview questions (basic) operator

  • What is the most efficient way to calculate 2 times 8?
    2 << 3 (shifting 3 bits to the left is equivalent to multiplying by 2 raised to the third power, and shifting 3 bits to the right is equivalent to dividing by 2 raised to the third power). The shift operation requires knowledge of the original code, the complement code, and the complement code. What is stored in the computer is binary data, int 4 bytes, one byte is 8 bits, and has a sign bit. In the original code of 2, the first bit is the sign bit 0 (0 represents a positive number, 1 represents a negative number, don’t forget that 0 is neither a positive number nor a negative number), and then there are 29 0+10, which is the int in Javas The data type 2 is represented in the computer as: 000000000000000000000000000010. Shift left by 3 bits to become 00000000000000000000000000010000, which is 16 in decimal.

  • What is the difference between & and &&?

The & operator has two uses: (1) bitwise AND; (2) logical AND. The && operator is a short-circuit AND operation. The difference between logical AND and short-circuit AND is very huge, although both require that the Boolean values ​​on the left and right sides of the operator are true for the value of the entire expression to be true. && is called a short-circuit operation because if the value of the expression on the left of && is false, the expression on the right will be directly short-circuited and no operation will be performed. Many times we may need to use && instead of &. For example, when verifying user login to determine that the username is not null and not an empty string, it should be written as: username != null &&!username.equals( ""), the order of the two cannot be exchanged, nor can the & operator be used, because if the first condition is not true, the equals comparison of strings cannot be performed at all, otherwise a NullPointerException will occur. Note: The same is true for the difference between the logical OR operator (|) and the short-circuit OR operator (||).

  • What is the difference between i++ and ++i?
    i++ is assigned first and then incremented; ++i is first incremented and then assigned;
    Extension: ++/-- is non-thread safe, that is Said ++/-- operation may cause confusion under multi-threading; the reason is because the "++" operation causes confusion under multi-threading: because the ++ operation is not a CPU operation instruction for the underlying operating system. , but three CPU operation instructions - value acquisition, accumulation, storage, so atomicity cannot be guaranteed.

Guess you like

Origin blog.csdn.net/chen15369337607/article/details/126050167