The thinking Logic of computer program (9)-the essence of conditional execution "turn"

Source: Internet
Author: User
Tags case statement

Conditional execution

In the previous sections we described how to define data and perform basic operations, and in order to have a thorough understanding of the data, we introduced a binary representation of various types of data.

Now, let's review the program itself, only the basic operation is not enough, in order to carry out practical operation, we need to control the process of the operation. The most basic of process control is conditional execution, that is, some operations can only be performed when certain conditions are met, perform some operation under some conditions, and perform some other operation under some other conditions. This is similar to the red light stop in traffic control and the Green Line condition execution.

The basic syntax for expressing this process control in Java is the IF statement.

If

The syntax for if is:

If(conditional statement) {  code block}

Or

The meaning of the expression is also very simple, only in the case of the condition statement is true, only execute the following code, false will not do. Specifically, the conditional statement must be a Boolean value, can be a direct Boolean variable, or it can be the result of a variable operation, we introduced in the 3rd section, the comparison and the logical operation of the result is a Boolean value, so it can be used as a conditional statement. If the conditional statement is true, the code in the brackets {} is executed, and if there is no parenthesis, then the first semicolon (the code before the;) is executed.

For example, output only if the variable is even:

int a=10;  if (a%2==0) {   System.out.println ("even");}   

Or

int a=10;  if (a%2==0) System.out.println ("even"); 

If's trap

Beginners sometimes forget to add parentheses to the code block after the if and sometimes want to execute multiple statements without parentheses, resulting in only the first statement being executed. It is recommended that all if are followed by parentheses.

If/else

The IF implementation is what to do when the conditions are met, if you need to do a branch according to the conditions, that is satisfied when the execution of some logic, but not satisfied when the execution of another logic, you can use If/else.

The syntax of If/else is:

If(judging condition) {   code block 1}else{   code block 2}  

If/else is also very simple, judging the condition is a Boolean value, true when executing code block 1, for false when executing code block 2.

Ternary operators

We have introduced a variety of basic operations, here is a conditional operation, and if/else very much like, called ternary operators, the syntax is:

Judging the conditions? Expression 1: Expression 2

The ternary operator gets a result that returns the value of expression 1 when the condition is true, or returns the value of expression 2. Ternary operators are often used to assign values to a variable, such as a maximum of two numbers:

int max = x > y? x:y;

The ternary operator can be replaced entirely with if/else, but it is more concise to write in some scenarios.

If/else If/else

If you have multiple judging criteria and you need to perform certain actions based on the combination of these criteria, you can use If/else if/else.

Syntax is

If(condition 1) {  code block 1}if(condition 2) {  code block 2} ... if(condition N) {code block n}else{code block n+1        

If/else If/else is also relatively simple, but can express complex conditional execution logic, it checks the condition one by one, the condition 1 satisfies then executes the code Block 1, does not satisfy the check condition 2, ..., finally if there is no condition to satisfy, and has else statement, then executes the code inside the else. The last else statement is not required, and nothing is done.

If/else If/else Traps

It should be noted that in If/else If/else, the Order of judgment is important, and the subsequent judgment is only executed when the previous condition is false. Beginners are sometimes mistaken in this order, as in the following code:

if (score>60) {  return "pass";} if (score>80return "good";} Elsereturn "excellent"}        

You see the problem? If score is 90, you may expect to return "good", but actually only return "pass".

Switch

In If/else If/else, if the condition is based on the same variable, only depending on the value of the variable and there are different branches, if the value is more, such as according to the day of the week to judge, there are 7 possibilities, or according to the English alphabet to judge, there are 26 possibilities, the use of If/else if /else more verbose, this situation can be used Switch,switch syntax is:

Switch(expression) {case value 1: Break case, break case, break              Default: Code n+1} 

Switch is also relatively simple, depending on the value of the expression to perform different branches, specifically, according to the value of the expression to find a matching case, found, after the execution of the Code, the end of the break when hit, and if no matching value is found, execute the statement in default.

The data type of an expression value can be only a byte, short, int, char, enumeration, and string (after Java 1.7). Enumerations and strings we introduce in subsequent articles.

Switch simplifies the writing of some code, but break and case syntax can cause some confusion for beginners.

Easy to ignore break

Break means to jump out of the switch statement and execute the statement following the switch. Each case statement should be followed by a break statement, otherwise it would continue to execute the code in the following instance until the break statement or switch ends, for example: The following code outputs all numbers, not just 1.

int a = 1;  Switch(a) {case1: System.out.println ("1");  Case 2: System.out.println ("2");  Default: System.out.println ("3");}           

Case stacking

The case statement can be followed by no code to execute, as follows:

char c = ' A '; // character switch(c) {case '   A ' case' B ' case' C ': System.out.println ("A-Z");  Break case' D ': ....}          

Case ' A '/' B ' is not immediately followed by code to execute, they will actually execute the first piece of code encountered, that is, case ' C ' matching code

Summary of conditions

Conditional execution is relatively simple in general, when a single condition is met when performing an operation using the IF, depending on whether a condition satisfies the execution of different branches using if/else, expressing complex conditions using if/else If/elese, the conditional assignment uses the ternary operator, Use switch to perform different branches depending on the value of one expression.

Logically, If/else, If/else if/else, ternary operators, and switch can all be used only if instead, but the use of different syntax to express more concise, when the conditions are more, switch from a higher performance (immediately explain why).

Conditional nature

As we explore the data types, we look at the binary representations of the data, and we also see how these conditions are implemented specifically.

The program is ultimately a line of instructions, the CPU has a directive indicator, pointing to the next command to execute, the CPU is based on the indicator's instructions to load and execute. Directives are mostly specific operations and operations, and when you perform these operations, the instruction indicator automatically points to the next command next to you.

But there are special instructions, called jump instructions, that modify the value of the instruction indicator to allow the CPU to jump to a specified place to execute. There are two kinds of jumps, one is conditional jump, the other is unconditional jump. Conditional jump Check a condition, meet then jump, unconditional jump is directly to jump.

If, else is actually converted to these jump commands, such as the following code:

int a=10;  if (a%2==0){4 System.out.println ("even");} // other code        

The transfer instruction that is converted to may be:

int a=10;  2 conditional Jump: If a%2==0, jump to line 4th unconditional Jump: Jump to line 7th {5 System.out.println ("even");} // other code         

You may be surprised by the unconditional jump instruction, without it? No, there is no command, no matter what the conditions, the code in parentheses will be executed.

However, the corresponding jump instruction may also be:

int a=10;  2 conditional Jump: If a%2!=0, jump to line 6th {4 System.out.println ("even");} // other code        

There is no unconditional jump instruction, specifically how to correspond with the compiler implementation. In the case of a single if, there may be no unconditional jump instruction, but a slightly more complex situation is required. If, If/else, If/else if/else, ternary operators are converted to conditional jumps and unconditional jumps. But switch is not the same.

Switch conversions are related to the specific system implementation, and may be converted to a jump instruction if the branch is relatively small. However, if the branch is more, the use of conditional jump transfer for many times the comparison operation, the efficiency is low, may use a more efficient way, called the jump table. A jump table is a mapping table that stores the possible values and addresses to jump to, such as:

Value 1 Address of code block 1
Value 2 Address of code block 2
...
Value n Address of code block n

Why is a jump table more efficient? Because, the values must be integers, and sorted by size order. Integers sorted by size can use efficient binary lookups, which are compared to the median value, and if less than the middle value is found between the start and middle values, or between the median and the end values, each time you look for a narrowing of the lookup range. if the value is continuous, then the jump table will also be a special optimization, optimized to an array, not even looking for, the value is the array subscript index, directly according to the value can find the address of the jump. Even though the values are not contiguous, but the numbers are dense and the difference is not much, the compiler may also optimize to an array-type jump table, with no values pointing to the default branch.

The arrangement of case values in the program source code does not require sorting, and the compiler automatically sorts. Previously, the type of the switch value could be byte, short, int, char, enum, and string. Where Byte/short/int is an integer, as we have said in the previous section, char is essentially an integer, and the enumeration type has a corresponding integer. String is also converted to an integer for switch (through the Hashcode method, described later), why can not use long? The value of the jump table is typically 32-bit storage space and cannot accommodate long.

Summarize

The syntax for conditional execution is natural and easy to understand, and it is important to note some of the syntax details and pitfalls. The nature of its execution relies on conditional jumps, unconditional jumps, and jump tables.

The jump in the conditional execution will only jump to the instruction after the jump statement, can you jump to the previous instruction?

----------------

The thinking Logic of computer program (9)-the essence of conditional execution "turn"

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.