Thinking in Java 4

zhaozj2021-02-11  190

Chapter 3 Control Procedures "As with any perceived organisms, the program must be able to manipulate your own world, make judgments and options during the execution process." In Java, we use operator to manipulate objects and data, and use execution control The statement makes a selection. Java is based on C , so it is very familiar with most of the statements and operators in Java, which are available in C programmers. Of course, Java also made some improvements and simplified work. 3.1 Use the Java operator operator to generate a new value based on one or more independent variables. The self-variable uses a form that is different from the original method, but the effect is the same. According to the experience of the previous writer, the conventional concept of the operator should not be difficult to understand. The usage of the plus ( ), minus, and negative (-), multiplier (*), division (/), and equal sign (=) are similar to all other programming languages. All operators can generate a value according to their own calculation objects. In addition, an operator changes the value of the operation object, which is called "Side Effect). The most common use of the operator is to modify its own calculation object, resulting in side effects. But pay attention to the resulting value can also be generated by an operator without side effects. Almost all operators can only operate "primitives". The only exception is "=", "==" and "! =", Which can operate all objects (it is also a place where object is easy to confuse). In addition, String class supports " " and " =". 3.1.1 The priority of the priority operator determines the calculation order of each part of the existence of multiple operators. Java made a special provision for the calculation order. Among them, the simplest rule is that multiplication and division are completed before the addition and subtraction. Programmers often forget other priority rules, so they should be clearly defined in parentheses. For example: A = x y - 2/2 z; after adding parentheses for the above expression, there is a different meaning. A = x (y - 2) / (2 z); 3.1.2 Assignment assignment is made using an equal number operator (=). It means "get the value on the right, copy it to the left". The value on the right can be any constant, variable, or expression, as long as a value can be generated. But the value on the left must be a clear, named variable. That is, it must have a physical space to save the value on the right. For example, a constant can be assigned to a variable (A = 4;), but nothing can be assigned to a constant (such as 4 = a). The assignment to the primary data type is very straightforward. Since the primary type accommodates the actual value, but does not point to an object's handle, it can be copied from one part to another when it is assigned. For example, suppose to use "A = B" as the main type, then the contents of B is copied to A. If the A is then modified, B will not be affected by this modification. As a programmer, this should be a common sense. However, when the object "assignment", the situation has changed. When an object is operated, we truly operate its handle. So if you assign a value from an object to another object, it is actually copied from one place to another. This means that if "c = D" is used as an object, then C and D will eventually point to that object that is originally pointing only by D. The following example will tell you this. Here are some questions outside.

Before, the first statement you see in the code example will be "package" statement used by "package 03", which represents Chapter 3 of this book. The first code list of each chapter of this book will contain a "package" (package, package, package) statement like this, and its role is to establish a chapter number for the remaining code. In Chapter 17, everyone will see all code lists in Chapter 3 (except those who have different package names) will automatically place a subdirectory named c03; the code in Chapter 4 is placed in C04; analogy. All of this is implemented through the CodePackage.java program displayed in Chapter 17; the basic concept of "package" will be detailed in Chapter 5. For now, everyone only needs to remember that "package 03" is just the corresponding subdirectory for the code list for a chapter. To run the program, it is necessary to ensure that the root directory we install this book source file in the ClassPath is included (including C02, C03C, C04, etc. in that directory). For Java subsequent versions (1.1.4 and higher), if your main () is encapsulated in a file with the package statement, you must specify a complete package name in front of the program name, otherwise the program cannot be run. In this case, the command line is: Java c03.assignment When running in a "parcel" program, pay attention to this problem at any time. Here are examples: 97-98 Program Number Class is very simple, its two instances (N1 and N2) are created in main (). The I value in each Number gives a different value. Subsequently, N2 is assigned to N1, and N1 changes. In many programming languages, we all want N1 and N2 to be independent of each other. But because we have given a handle, the following is true output: 1: N1.I: 9, N2.I: 472: N1.I: 47, N2.I: 473: N1.I: 27, N2 .i: 27 It seems to change N1 while changing N2! This is because N1 or N2 contains the same handle, which points to the same object (the initial handle is in the inside of N1, pointing to an object to accommodate the value 9. During the assignment process, the handle is actually lost; its object It will be automatically cleared by the "garbage collector). This special phenomenon is often called "alias", which is a basic way for Java operation objects. But if you don't want to have an alias in this case, how to do it? The assignment can be abandoned and written to the following code: n1.i = n2.i; this can retain two independent objects instead of bind N1 and N2 to the same object. But you will soon realize that this will make the fields within the object to be confused and contradict the standard object-oriented design guidelines. Since this is not a simple topic, I left Chapter 12 details, that chapter is specially discussing alias. At this time, everyone will notice that the assignment of the object will produce some shocking effect. 1. The alias processing in the method call will generate an alias when passing an object to the inside of the method. 99 Page Program In many programming languages, a copy of your own argument Letter Y is required on the scope of the method in many programming languages. But in the same manner, the actual transmission is a handle. So below this procedure: y.c = 'z'; actually changing objects other than F (). The output is as follows: 1: x.c: a2: x.c: z Alias ​​and its countermeasure is a very complex problem. Although all answers must be obtained, you should get all the answers from now on, you should pay attention to it in order to discrete it early.

3.1.3 The basic arithmetic operator of the arithmetic operator Java is the same as that of most of the programming languages. This includes a plus sign ( ), minus, division (-), inward (/), multiplier (*), and modulus (%, the remainder from integer division). Integer eliminates the rule directly, not carry. Java also operates in a simple form and simultaneously assigning operations. This is marked by an operator before the equal number, and all operators in the language are fixed. For example, in order to add 4 to the variable x, the result is assigned to X, and: x = 4 can be used. The following example shows the various usages of the arithmetic operator: 100-101 Page Operation We noticed some shortcuts for printing (display): PRT () method prints a string; pint () first Print a string, then print an int; and PFLT () first print a string, then print a float. Of course, they must ultimately end with System.out.Println (). To generate numbers, the program first creates a Random object. Since the argument is passed during the creation process, Java uses the current time as a "seed value" by the random number generator. With the Random object, the program can generate many different types of random numbers. The practice is simple, just call different methods: Nextint (), nextlong (), nextfloat () or nextdouble (). If the result of the random number generator is used, the modulus operator (%) can limit the result to the upper limit of the calculation object minus 1 (this example is 99). 1. One yuan plus, the reduction operator is one yuan minus (-) and one yuan plus ( ) and binary plus sign and minus number are the same operator. According to the form of writing, the compiler will automatically determine which one is used. For example, the following statement: x = -a; its meaning is obvious. The compiler correctly recognizes the following statement: x = a * -b; but the reader will be confused, so it is best to write: x = a * (-b); a negative value of the calculation object obtained by one yuan . The meaning of a dollar plus sign is opposite to a dollar, although it doesn't do anything. 3.1.4 Automatic incrementing and decrementing and C are similar, Java provides a wealth of shortcut operations. These quick-ending can make the code more refresh, easier to enter, and more readers to read. Two very good shortcuts are incrementing and delighted operators (often referred to as "automatic increment" and "automatic decreasing" operators). Among them, the decrementing operator is "-", meaning "Reduce a unit"; the incremental operator is " ", meaning "add a unit". For example, it is assumed that A is an int (integer) value, and the expression a is equivalent to (a = a 1). The result of incrementing and decrementing the operator is the value of the variable. For each type of operator, there are two versions available; usually referred to as "prefix" and "suffix". "Pre-increasing" indicates that the operator is in front of the variable or expression; and "post-increment" means that the operator is behind the variable or expression. Similarly, "pre-decreasing" means that the operator is located in front of a variable or expression; and "post-decreasing" means that - the operator is located behind the variable or expression.

For the preceding increments and pre-decreasing (such as A or --a), the calculation is performed first, and the value is enrichd. For post-increasing and post-decreasing (such as A or A-), it will be generated, and the calculation is performed again. Here is an example: 102-103 Program This program is as follows: 103 Uppoints can be seen from it, for the prefix form, we get the value after performing the email. But for the suffix form, it is obtained before the operation is executed. They are unique operators with "side effects" (except those involving assignments). That is, they change the operational object, not just using its own value. The incremental operator is an explanation of the name of "C ", implies "one step of overload C". In the early Java speech, Bill Joy (one of the originners) claimed "Java = C -" (C plus reduction), means that Java has removed C some of the places that have not been tortured, form a More streamlined languages. As everyone learned in this book, many places in Java have been simplified, so Java's learning is easier than C . 3.1.5 Relational operator relational operator is a "Boolean" result. They evaluate the relationship between operational object values. If the relationship is true, the relationship expression will generate True (true); if the relationship is not true, it generates false. The relationship operator includes less than (<), greater than (>), less than or equal to (<=), is greater than or equal to (> =), or equal to (==) and is not equal to (! =). It is equal to and does not equal to all built-in data types, but other comparisons do not apply to the Boolean type. 1. Check if an object is equally related to an equal relational operator == and! = Also applied to all objects, but their meaning usually makes people in the Java field can't find north. Below is an example: 104 page program where the expression system.out.println (n1 == N2) can print out the internal Boolean comparison results. Everyone will think that the output is definitely true, and it is False because the two Integer objects are the same. But although the contents of the object are different, the handle is different, and == and! = The predecessor is the object handle. Therefore, the output is actually false first, and then True. This naturally will be surprised by people in the first contact. If you want to compare whether the actual content of the two objects is the same, how should you operate? At this point, special methods for all objects must be used Equals (). But this method does not apply to "Main Types", and those types are directly used == and! =. The following example shows how to use: 104 page program is as expected, the result is true at this time. But things did not end this! Suppose you have created your own class, just like this: 104-105 Page Program At this time, the result is changed back to False! This is because the default behavior of equals () is a comparison handle. So it is impossible to show our hopes in unless you have changed equals () in your new class. Unfortunately, you will learn how to change behavior in Chapter 7. But pay attention to this behavior of equals () may be able to avoid some "disaster" events.

Most Java class libraries implemented equals (), so it actually compares the content of the object, not their handle. 3.1.6 Logical Operators Logic Operators and NOT (!) Generate a Boolean (TRUE or FALSE) - based on the logical relationship of the argument. The following example shows you how to use the relationship and logical operators. 105-106 Page programs can only be applied to the Boolean value of the AND, OR or NOT. Unlike C , it is not possible to use a non-Boolean value as a Boolean value in a logical expression. If you do this, you will find that the attempt failed and used one "//!". However, subsequent expressions generate a Boolean value by using a relationship, and then logically calculates the results. Output list looks like this: 106 Page Program Note If you are using a String value, the Boolean value will automatically convert into an appropriate text form. In the above program, the definition of INT can be replaced with any other primary data type other than Boolean. But to note that the comparison of floating point numbers is very strict. Even if a number is only a very small difference between the fractional portion and the other number, they still think that they are "not equal". Even if a number is only a little bit more than zero (for example, 2 keeps open square root), it still belongs to the "non-zero" value. 1. When short-circuit operation logic operators, we will encounter a situation called "short circuit". This means that only the expression is logically summarized only if it is clearly clearly conclusions throughout the expression. Therefore, all portions of a logical expression may not be evaluated: 107 Page Merger Each test will compare independent variables and return true or false. It does not display information related to what is prepared. Test is performed in this expression: IF (TEST1 (0)) && test2 (2) && test3 (2)) Naturally, you may think that all three tests will be implemented. But I hope that the output is not surprisingly surprising: 108 Page the first test generates a true result, so the expression evaluation will continue. However, the second test produced a false result. Since this means that the entire expression is definitely false, why should I continue the remaining expressions? This will only be in vain. In fact, the origin of the word "short circuit" is due to this. If all parts of a logical expression do not have to perform, the potential performance improvement will be considerable. 3.1.7 Bittage Operator Bits Operators Allows us to operate a single "bit" in an integer primary data type, namely the binary bit. The bitmap operator performs a Boolean number in two arguments, and eventually generates a result. Billing operations from the low operation of the C language. We often manipulate hardware directly and need to frequently set the binary position in the hardware register. Java's design is the original intention to embed the TV top box, so this low-level operation is still retained. However, due to the advancement of the operating system, it may not be too frequently used to perform a bit by bit. If the two input bits are 1, the bit and operator (&) generates a 1 in the output bit; otherwise generate 0. If there is at least one of the two input bits, the bit OR operator (|) generates a 1 in the output bit; only if the two input bits are 0, it will generate one 0. If one of the two input bits is 1, but not all is 1, then the bit xor (^, the different or) generates one 1 in the output bit. Bit NOT (~, also known as "non-operator) belongs to a primary operator; it only operates an argument (all other operators are binary operators).

By bit Not generates the opposite value of the input bit - if input 0, output 1; input 1, output 0. The same characters are used by bit operators and logical operators, just different quantities. Therefore, we can easily memorize their respective meaning: Since "bit" is very "small", the bit operator uses only one character. The bit operator can be used in conjunction with the equal sign (=) so as to combine operations and assignments: & =, | = and ^ = are legal (because ~ is a one-dimensional operator, it is not used in combination with =.). We treat the Boolean type as a "unit" or "single bits" value, so how much is a unique place. We can perform bit bits and, OR and XOR, but we cannot perform bit bit NOT (probably to avoid confusion with logic NOT). For the Boolean value, the bit operator has the same effect as the logical operator, but they do not "short circuit" in the middle. In addition, the bitwise operations for Boolean values ​​have added a XOR logic operator, which is not included in the list of "logical" operators. In shift expressions, we are banned from using Boolean operations, which will be explained below. 3.1.8 Displacement Operator Shift Operator The Object Operator is also a binary "bit". They can be used individually to handle integer types (one of the main types). The left shift operator (<<) can set the arithmetic object on the left of the operator to the number of bits (at low rating 0) on the right side of the left move operator. The "Symbol" right shift operator (>>) then the calculation object on the left side of the operator The number of bits specified on the right side of the operator on the right movement operator. "Symbol" right shift operator uses "symbol extension": If the value is positive, it is inserted in the high position; if the value is negative, then insert 1 at the high position. Java also added a "no symbol" right shift operator (>>), which used "zero extension": no matter the neiff, insert 0 in the high position. This operator is C or C . If you perform a handling of char, byte or short, they automatically convert into an int. Only 5 low positions on the right will be used. This prevents us from moving unrealistic bits in an int number. If a long value is processed, the final result is also long. At this point, only 6 low positions on the right should be used to prevent the mobile to exceed the current number of bits in the long value. However, it may also encounter a problem when "unsigned" right shift. If the BYTE or SHORT value is changed, it may not be the correct result (Java 1.0 and Java 1.1 are particularly prominent). They will automatically convert into int types and right shift. But "zero extension" does not occur, so the results of -1 are obtained in those cases. You can use the following example to detect your own implementation: 109-110 Program shift can be used in combination with the equal sign (<< = or >> = or >>> =). At this time, the value left on the left side of the operator moves the number specified by the value of the right, and then the resulting result is returned to the value of the left. The following example explains how to apply all operators involving the "bit" operation, as well as their effect: 110-112 Page Program Merchant: Pbinint () and Pbinlong (). They operate an int and long value, and are output with a binary format while attaching a brief description. Currently, they can be temporarily ignored.

Everyone should pay attention to the use of System.out.Print (), not system.out.println (). The Print () method does not produce a new row so that multiple information in the same line. In addition to displaying all bit bit operators, this example also shows the minimum, maximum, 1 and -1 values ​​of int and long, so that you can experience their situation. Pay attention to the high position representation: 0 is positive, 1 is negative. The output of the INT portion is listed below: 112-113 Page program number of binary forms is "a nup value of symbol 2". 3.1.9 Three-membered IF-Else operator This operator is rare because it has three operational objects. But it does belong to an operator because it will eventually generate a value. This is different from the ordinary if-else statement to be described in this section. Expression takes the following form: Boolean expression? Value 0: Value 1 If the "Boolean Expression" is true, "value 0" is calculated, and its result is the value generated by the operator. However, if the result of "Boolean Expression" is false, the calculated "value 1", and its result is the value generated by the operator. Of course, a normal IF-ELSE statement can be exchanged (introduced later), but the three-yuan operator is more concise. Although C is proud of it is a simple language, and most of the introduction of the three-yuan operator is to reflect this high efficiency programming, but if you intend to use it frequently, you still have to make some thinking - - It is easy to generate a code that is extremely readable. Conditional operators can be used for their own "side effects" or for the value it generates. However, it is usually used for values, as it can clearly distinguish between operators and IF-ELSE. The following is an example: Static Int Ternary (INT I) {RETURN I <10? I * 100: i * 10;} It can be seen that the code amount will be more than the above-mentioned code with ordinary IF-ELSE structure. Many. As shown below: Static int alternative (INT i) {IF (i <10) Return i * 100; Return i * 10;}, but the second form is more easily understood, and more entry is not required. So when you pick a three-yuan operator, be sure to weigh the pros and cons. 3.1.10 Command operators In C and C , commas not only use the separator of the function's own variable list, as well as an operator for subsequent calculations. The only place to use a comma in Java is for loop, which explains this later. 3.1.1 String Operators This operator has a special purpose in Java: connect different strings. This has been shown in the previous example. Although it doesn't match 's traditional meaning, it is still very natural with to do this. In C , this feature looks very good, so I introduced an "operator overload" mechanism so that C programmers increase special meaning for almost all operators. But very unfortunately, combined with other restrictions between C , operators overload become a very complicated feature, programmers must think about this when designing their own classes. Compared to C , although operators are overloaded in Java more easily, this is still considered to be too complicated. So Java programmers cannot design their own overload operators like C programmers. We noticed some interesting phenomena when using "String ". If the expression starts with a String, then all subsequent operation objects must be string.

As shown below: INT x = 0, y = 1, z = 2; string sstring = "x, y, z"; system.out.println (SSTRING X Y Z); here, Java Compiler will Convert X, Y, and Z into their string form, instead of adding them together. However, if you use the following statement: System.out.println (x SString); then the earlier version of Java will prompt an error (later version can convert X into a string). Therefore, if you want to connect by the "plus" connection string (using Java's earlier version), be sure to ensure that the first element is a string (or add a series of characters of quotation marks, compiling it into a string) . 3.1.12 Operators Conventional Operating Rules Use a disadvantage of operators to use the brackets to make mistakes. Even however, it is easy to confuse the brackets for an expression. This problem still exists in Java. In C and C , a particularly common mistake is as follows: while (x = y) {// ...} The intent of the program is "equal" (==) instead of assigning assignments. In C and C , if Y is a non-zero value, then the result of this assignment is definitely TRUE. This allows you to get an infinite loop. In Java, the result of this expression is not a Boolean value, and the compiler expects a Boolean value, and does not convert from an int value. So when compiling, the system will prompt an error and effectively prevent us from further running the program. So this shortcomings will never cause more serious consequences in Java. The only time x and y will be a Boolean when compiling errors. In this case, X = Y is a legal expression. In the above case, it may be an error. In C and C , a similar problem is to use bit bits and or OR instead of logical and or or. Bits and and ORs use one of the two characters (& or |), while logical and OR use two identical characters (&& or ||). Just like "=" and "==", type a character to be simply more simpler than type. In Java, the compiler also prevents this because it does not allow us to use a type that is not only. 3.1.1 Model Operator "Cast" effect is "matching with a model". When appropriate, Java will automatically convert a data type into another. For example, suppose we assign an integer value for floating point variables, and the computer will automatically convert int to float. By styling, we can clearly set this type of conversion, or forced it when it is generally not possible. To perform a model, put the data type hidden in parentheses (including all modifiers) on the left side of any other value. Here is an example: void caves () {INT i = 200; long L = (long) i; long L2 = (long) 200;} As you can see, you can use a value to make a model, or A variable is treated. But in both cases shown here, the shape is redundant because the compiler will automatically perform the conversion of the INT to the long value when necessary. Of course, you can still set a shape, remind yourself, and make the program clearer. In other cases, the shape is only important when the code is compiled.

In C and C , the shape is sometimes a headache. In Java, modeling is a relatively safe operation. However, if a "narrowing conversion" is performed (that is, the script is a data type that can accommodate more information, converting it into a small type of capacity), it may face The risk of information loss. At this point, the compiler will force us to make a shape, just like: "This may be a dangerous thing - if you want me to do everything, then I am sorry, please clearly shape." And for "amplification conversion "Wideening conversion, there is no need to make a clear shape, because the new type will definitely accommodate the original type of information, which will not cause loss of any information. Java allows us to "model" for any of the other primary types, but the latter is not allowed to perform any styling processing at all. "Class" is not allowed. In order to convert a class into another, a special method must be adopted (string is a special case, and the book will tell the object to a type "family"; for example, the "oak" can shape "Tree"; vice versa. But for other foreign types, such as "rock", it cannot shape "tree"). 1. When the literal value is starting, if you insert a "literal" in a program, the compiler can usually know what type of type to generate. But at some time, it is unclear for the type. If this happens, the compiler must be appropriately "guidance". The method is to add some additional information in the form of a character associated with a literal value. The following code shows you these characters. Page 116-117 Page 66 Enter (Base 16) - It applies to all integer data types - with a preamplified 0x or 0x indication. And followed by 0-9 and A-f in uppercase or lowercase forms. If you try to initialize a variable into a value that exceeds its own ability (regardless of the value of this value), the compiler reports an error message to us. Note that in the above code, the maximum hexadecimal value will only appear on Char, Byte, and SHORT. If this limit is exceeded, the compiler will automatically turn the value into an int and tell us to "shrink the model" on this time. In this way, we can clearly know that you have overloaded the boundary. Octa (base 8) is an indication of a front 0 and 0-7 in a number. In C, C or Java, there is no corresponding "literal" representation method for binary numbers. The end of the literal value marks its type. If the uppercase or lowercase L, represents long; uppercase or lowercase F, represents float; uppercase or lowercase D, represent Double. The index always uses a marker that we think is very incomplete: 1.39E-47F. In the field of science and engineering, "e" represents the base of natural logarithm, about 2.718 (a more accurate Double value of Java adopts Math.e). It is used in index expressions like "1.39 × E-47", meaning "1.39 × 2.718 -47 times". However, since the inventions in the Fortran language, people naturally think that E represents "10 how many times power". This approach is quite quite, because Fortran is originally facing scientific and engineering design. It is reasonable, and its designers should be cautious about such confusion concepts (annotation 1).

But in any case, this special expression method is stubborn in C, C , and the current Java. So if you are used to use the EM as the base of the natural logarithm, see the expression like "1.39e-47f" in Java, conversion your thinking, think it from the perspective of programming; it is true The meaning is "1.39 × 10 -47 times". 1: John Kirkham wrote: "I used to use Fortran Ii on a IBM 1620 in 1962. At that time - including the early 1970s, Fortran has always used uppercase letters. The reason will appear This situation may be due to most of the early input devices are old-fashioned typewriters, using 5 BAUDOT codes, the code does not have lowercase power. The 'E' in the power expression is definitely capitalized, so no It will conflict with the natural logarithmic base 'e', ​​the latter is inevitably lower-written.'E 'The meaning of this letter is actually very simple, is' Exponential' meaning, namely 'index' or 'power number', representative calculation The base of the system is generally 10. At that time, octal is also widely used in programmers. Although I didn't see it, I would like to see an octave number in the power expression, I will put it. I remember that the first time I saw that I saw the lowercase 'e' indicated the index in the late 1970s. I also thought it was very confused. So, this problem is completely my own 'sneaked in' Fortra Not before the start. If you really want to use the border of natural logarithm, there is actually available functions, but they are all capitalized. "Note If the compiler can correctly identify the type, you don't have to use the trailing character. For the following statement: long N3 = 200; it does not exist in a confirmed place, so a Lar to save later. However, for the following statement: float f4 = 1e-47f; // 10 Power compiler typically uses an index as a double precision number (Double), so if there is no endless F, it will receive an error prompt. Tell us to use a "model" to convert Double to float. 2. The transition can find that if any arithmetic or bitwise operations are performed on the primary data type, as long as they "be smashed" (ie, CHAR, BYTE or SHORT), those values ​​are automatically converted into int. In this way, the final generated value is the int type. Therefore, as long as a value is assumed to a small type, "style" must be used. Further, since the value is assigned to a smaller type, the case where information is lost) may occur. Typically, the maximum data type in the expression is the type that determines the final result size of the expression. If a FLOAT value is multiplied with a double value, the result is Double; if an int and one long value is added, the result is long. 3.1.14 Java No "SizeOf" In C and C , the SIZEOF () operator can meet our special needs: I know the number of characters assigned to the data item. In C and C , the most common application of Size () is "transplant". Different data may have different sizes on different machines, so the programmer must do much to those in the heart when performing some sensitive operations of size. For example, a computer can save an integer with 32, while the other is saved with 16 bits. Obviously, in the first machine, the program can save a larger value. As you may have already thought, transplantation is a problem with C and C programmers is a problem.

Java does not require a SIZEOF () operator to meet the needs of this regard, as all data types are the same in all machines. We don't have to consider the problem - Java itself is a language "unrelated to the platform". 3.1.15 Review Calculation The order is too difficult to complain about the priority of the operator in a training course I hold. A student recommends using a sentence to help memories: "Ulcer Addicts Really Like C A Lot", "Ulcer patients particularly like (vitamin) C". Helpful writer operator type operator ULCER (ulcer) Unary: One dollar - - [[余]] Addicts (patient) arithmetic (shift); arithmetic (and shift) * /% - << >> Really Relational: Relational> <> = <= ==! = Like (like) Logical (Bitwise): Logic (and Bit) && ||> ^ c conditional (TERNARY): Conditions (three yuan) A > B? X: Ya Lot Assignment: assignment = (and compound assignment, such as * =) Of course, for shift and bitwise operators, the above table is not a perfect way to help; but for other operations, it is indeed Personally. 3.1.16 Operators Summary The following example shows you how to use the primary data type with a specific operator. Fundamentally, it is the same example to reversely execute, just use different primary data types. The file is not reported when the file is compiled, because those rows that will cause errors have been used //! The comment content. Page 120-129 Program attention to Boolean's ability is very limited. We can only give TRUE and FALSE values. And you can test it is true or false, but you don't add Boolean values ​​for them, or other other types of operations. In Char, Byte, and Some, we can see the "transformation" effect of the arithmetic operator. Any arithmetic operation for these types will get an int result. It must be explicitly "modeling" back to the original type (narrowing the conversion causes the loss of information) to assign the value back to that type. But for int values, it is not necessary to make shape processing because all data is already int type. However, don't relax vigilance, think that everything is safe. If the multiplication operation is performed on two enough int values, the result value will overflow. The following example shows this: 129 Upload program output is as follows: BIG = 2147483647bigger = -4 and does not receive an error prompt from the compiler, there will be no abnormal reactions when running. Java Coffee (Java) is indeed very good, but there is no "then" good! For char, byte or short, mixing assignment does not require shape. Even if they perform transformation operations, they will also obtain the same results as direct arithmetic operations. On the other hand, the model will be slightly smashed. You can see that any primary type can be made to other main types in addition to Boolean. Similarly, when styling into a smaller type, it is necessary to pay attention to the consequences of "narrowing the conversion". Otherwise it will lose information unconsciously during the styling process.

3.2 Execution Control Java uses all of the all control statements of C, so you used C or C programming before the holidays, most of them should be very familiar. Most programming languages ​​provide some form of control statement, which is usually common in language. In Java, keywords involved include if-else, while, do-while, for, and a selection statement called Switch. However, Java does not support very harmful goto (it is still a solution to some special issues). Can still be jumped like Goto, but there is more than typical goto. 3.2.1 True and false all conditional statements Utilize the truth of the conditional expression or the fake to determine the execution process. An example of a conditional expression is A == B. It determines if the A value is equal to B value with the conditional operator "==". This expression returns True or False. All the relationships that come into contact with this chapter can construct a conditional statement. Note that Java does not allow us to use a number as a Boolean value, even if it is allowed in C and C (true non-zero, and false is zero). If you want to use a nonabul value in a Boolean test, for example, in IF (a), then you must first convert it into a Boolean value, such as IF (A! = 0). 3.2.2 if-elseif-Else statement is pervoiled to control the most basic form of the program process. The ELSE is optional, so it can generate a Boolean result in two forms, if the IF: IF (Boolean expression) statement or if (Boolean expression) statement. "Statement" either use a simple statement ending with a semicolon or a composite statement - a set of simple statements enclosed in parentheses. Anywhere in this book, as long as the word "statement" is mentioned, it is possible to include a simple or compound statement. As an example of IF-Else, the following Test () method can tell us that a number of guess is above the target number, or equal: 131 Page programs best indent the process control statement, so that the reader can be conveniently See the starting point and end. 1. ReturnReturn keyword has two purposes: specify what a method returns something (assuming it does not have a VOID return value) and returns that value immediately. According to this, the above Test () method can be rewritten, so that these features: 131-132 Page programs do not have to be added with ELSE, because the method is no longer continuing after encountering returno. 3.2.3 Repeated While, Do-While and FOR control the loop, sometimes it is divided into "repetitive statements". The statement will be repeated unless the result of the "false" Boolean expression is obtained. The format of the While loop is as follows: While, when the cycle is just started, the value of "Boolean expression" is calculated. For each additional cycle later, it will be recalculated once before the start. The following simple example can generate random numbers until a specific condition is conforming to a specific condition: 132 The program is used to use the Static (static) method Random (). The method of this method is a Double value between 0 and 1 (including 0, but not including 1). While's conditional expression means: "Take it around until the figures are equal to or greater than 0.99." Due to its randomness, every time this program is running, you will get a different number of digits. 3.2.4 Do-Whiledo-While The format is as follows: Do-While WHILE and Do-While The only difference is that do-while will definitely execute at least once; that is, at least the statement will be " One pass "- Even if the expression is first calculated as False. In the While loop structure, if the condition is first for False, then the statement will not be executed at all.

In practical applications, while While is more commonly used than do-while. 3.2.5 The FORFOR cycle is initialized before the first repetition. Subsequently, it will be tested, and in each time it is repeated, some form "Stepping) is performed. The FOR cycle is as follows: for (initial expression; Boolean expression; stepper) statement can be blank regardless of the initial expression, Boolean expression, or steps. Test a Boolean expression before each repeated. If the result is False, the line of code followed behind the For statement will continue. At the end of each cycle, you will be able to take a step. FOR cycle is often used to perform a "count" task: 133 Up the program Note that the variable C is defined when needed - the control expression in the for loop, not the code marked by the starting rough numbers The top of the block. The scope of c is the expression of FOR. For the traditional programming language like C, all variables are required to be defined at one block. So when you create a block in the compiler, it can allocate space for those variables. In Java and C , the variable declaration can be dispersed within the range of the entire block, and it is only defined in the actual needs. This will form a more natural coding style, it is more easily understood. Multiple variables can be defined in the FOR statement, but they must have the same type: 134 Page the program where INT definition in the For statement covers I and J. Only for loops has the ability to define variables in the control expression. This method is not available for any anywhere or loop statement. 1. The comma operator is earlier in Chapter 1, we have mentioned a comma operator - note not a comma separator; the latter is used for different arguments of the separator. The only comma operator in Java is the control expression of the for loop. In the initialization and step control section of the Control Expression, we can use a series of comma-separated statements. And those statements are executed independently. The previous example has used this capability, and the following is another example: 134 Up the program output is as follows: 135 Page Program You can see that the statement is executed in order, whether in the initialization or in the step portion, statement is executed. In addition, although the initialization portion can set any number of definitions, it belongs to the same type. 3.2.6 Interrupt and continue in the main part of any loop statement, can also be used to control the loop of the cycle with the Break and Continue. Among them, BREAK is used to force an exit loop without performing the remaining statements in the loop. Continue stops performing the current repetition, and then returns the cycle start and starting new repetition. Below this program shows you an example of Break and Continue in the For and WHILE loops: 135 Up Procedure Up in this For loop, the value of i will never arrive. Because once I reaches 74, the BREAK statement will interrupt the loop. Usually, it is only necessary to use Break like this when you don't know when the interruption conditions are met. As long as i cannot be 9, the Continue statement will make the program process return the most beginning of the loop (so that the I value is incremented). If it can be removed, the value is displayed. The second part reveals a "unlimited loop". However, there is a BREAK statement inside the loop to stop cycling. In addition, everyone will also see the CONTINUE to move back to the top of the loop, and does not complete the remaining content (so only when I value is 9, it is printed.). The output is as follows: 136 Page program is displayed 0, is due to 0% 9 equal to 0. The second form of an infinite loop is for (;;). The compiler regards while as the same thing as for (;;). So which of the specific use depends on your own programming habits. 1. The notorious "GOTO" GOTO keyword has already appeared in the programming language.

In fact, GOTO is the ancestor of the program control structure of the assembly language: "If the condition A, jump to here; otherwise jump to". " If you read the assembly code generated by almost all compilers, you will find a lot of jumps in program control. However, GOTO is jumping at the source code, so it has incurred a bad reputation. If the program always jumps to another place, what is the way to identify the process of code? With the advent of the famous "GOTO harmful" theory of Edsger Dijkstra, Goto lost. In fact, the real problem is not to use GOTO, but in GOTO's abuse. And in some fewer situations, GOTO is the best means of organizing control flow. Although Goto is still a reserved word of Java, it is not officially used in the language; Java has no goto. However, on the two keywords of Break and Continue, we can still see some goto shadows. It does not belong to a jump, but a way to interrupt the loop statement. The reason why they are incorporated into GOTO issues is because they use the same mechanism: label. "Label" is the identifier of the back with a colon, just like this: Label1: For Java, the only place to use the label is before the loop statement. Further, it actually needs immediateity in front of the cycle statement - is unwise to place any statements between labels and cycles. The only reason for setting labels before cycling is: We want to nest another loop or a switch. This is because Break and Continue keywords typically only interrupt the current loop, but if they use the label, they will be interrupted to where there is a label. As shown below: Label1: External cycle {//...break; //1///...CONTINUE; //2//...CONTINUE LABEL1; //3//...break label1 (// 4}} In the condition 1, the Break interrupts the internal loop and ends at the external cycle. In the condition 2, Continue moves back to the start of the internal cycle. However, in Condition 3, the Continue Label1 simultaneously interrupts the internal cycle and the external cycle, and moves to Label1. Subsequently, it is actually continuing to cycle, but it starts from the external cycle. In the condition 4, Break Label1 will also break all cycles and return to Label1, but do not re-enter the loop. That is, it is actually completely aborted by two cycles. Below is an example of the For loop: 138-139 Page Program This uses the PRT () method that has been defined in other examples here. Note that Break interrupts for loops, and incrementally incremented expressions are not executed before arriving at the end of the FOR cycle. Since Break skips increments expressions, the increment will execute directly in the case of i == 3. In the case of i == 7, the Continue Outer statement will also reach the top of the loop, and it will also jump over, so it is also directly incremented. Here is the output result: 139 Program If there is no Break Outer statement, there is no way to find the path to the external loop in an internal loop. This is because Break itself can only interrupt the innermost cycle (the same is true for Continue). Of course, if you want to exit the method while interrupting cycles, simply use a return. The following example shows you the use of tagged Break and Continue statements in the While loop: 140 Page Program The same rule also applies to while: (1) Simple Continue will return the beginning of the innermost loop (top) And continue to execute.

(2) Continue with the label will reach the location of the label and re-enter the loop next to the label. (3) Break interrupts the current loop and disabled from the end of the current label. (4) BREAK with label will interrupt the current loop and move away from the end of the loop indicated by that tag. The output result of this method is a place where: 141 Page Program Everyone should remember that the only place in Java needs to use the label is a nested loop, and want to interrupt or continue multiple nested levels. In Dijkstra's "GOTO harmful" theory, his most opposed is the label, not Goto. As the label increases in a program, he finds that there is more opportunities to generate an error. Labels and Goto make us difficult to analyze the program. This is because they introduce many "strange circles" in the execution process of the program. But fortunately, the Java label does not cause this problem because their activity places have been limited to pass through a special way to transfer the programs everywhere. This also leads out an interesting question: by limiting the ability of the statement, it can make a language characteristic more useful. 3.2.7 Switch "Switch" is sometimes divided into a "selection statement". According to a value of an integer expression, the Switch statement can be selected from a series of code. Its format is as follows: Switch (integer selection factor) {case integer value 1: statement; break; case integer value 2: statement; break; case integer value 3: statement; break; case integer value 4: statement; break; case integer Value 5: statement; Break; // .. default: statement;} where "integer selection factor" is a special expression that produces an integer value. Switch can compare the results of the integer selection factor with each integer value. If you find that the corresponding statement (simple or complex statement) is performed. If you do not find it, you will execute the DEFAULT statement. In the above definition, everyone will notice that each Case ends with a Break. This allows the execution process to jump to the end of the Switch body. This is a traditional way of building a Switch statement, but Break is optional. If BREAK is omitted, the code of the following CASE statement will continue until a Break is encountered. Although this usually does not want this, it may be able to make good use of experienced programmers. Note that the last Default statement is not Break because the execution process has reached the jump destination of BREAK. Of course, if you take into account the programming style, you can completely place a Break at the end of the default statement, although it doesn't have any actual use. The Switch statement is an easy way to implement multiple selection (such as picking one from a series of execution path). But it requires the use of a selection factor and must be an integer value as INT or CHAR. For example, if a string or floating point number is used as a selection factor, then they do not work in the Switch statement. For non-integer types, a series of IF statements must be used. The following example can randomly generate letters and determine that they are vowels or consonants: 142-143 Page programs Because Math.random () will generate a value between 0 and 1, just multiply it to be wanted Maximum random number (for English letters, this number is 26), plus an offset to get the smallest random number. Although we have to deal with characters on the surface, the integer value of the characters actually used by the Switch statement. In the case statement, the characters that are closed with single quotes also generate an integer value so that we can compare. Note how the CASE statement is aggregated, which is arranged in turn, providing a variety of matching modes for a part of the specific code.

转载请注明原文地址:https://www.9cbs.com/read-4715.html

New Post(0)