java if statement
Java control statements are divided into three categories: ① sequential structure; ② selection structure; ③ loop structure.
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Selected structures are further divided into: ① Single-select structure; ② Double-select structure; ③ Multi-select structure.
Mainly involved: if_else , switch , while , break and continue , for.
if single selection structure
Perform a test on the conditional expression. If the test is true, execute the following statement, otherwise skip the statement.
Example (Usage of Math class)
random(), returns a decimal of a positive sign, and the interval size is [0,1).
Pay attention to the problem of scope of if: if statement does not add {}, its control scope is limited to the first sentence. (Generally recommended to add {} to develop a good habit)
if-else double-select structure
When the conditional expression is true, statement block 1 is executed, otherwise, statement block 2 is executed, that is, the else part.
if-else if-else multi-select structure
Let me introduce Java switch statements to you below
Java control statement - switch statement
The equivalent value judgment of the above if statement can be replaced by switch.
Note that break is generally added after each case, indicating that the current case has been executed; prevent case penetration, that is, continue to execute the case and do not jump out until the break is encountered.
The following example in turn takes advantage of case penetration phenomenon.
【example】
New features of JDK7.0: Enhanced switch
Before JDK7, switch (expression) {...}, the expression result can only be int (byte, short, char that can be automatically converted to int), enumeration type.
However, in JDK7, the expression result can also be a string.
(ps: Automatic type conversion: Data types with small capacity can be automatically converted to data types with large capacity. byte (1 byte) → short (2 bytes) → int (4 bytes).)
The above are the if and switch statements of Java control statements shared by the editor. I hope they will be helpful to everyone.