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 in this area. 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. The following is: //: Assignment.java
// Assignment with Objects is a bit tricky
Package C03;
Class Number {
INT I;
}
Public class associx {
Public static void main (String [] args) {
Number n1 = new number ();
Number n2 = new number ();
N1.i = 9;
N2.i = 47;
System.out.println ("1: n1.i:" n1.i
", N2.I:" n2.i);
N1 = N2;
System.out.println ("2: n1.i:" n1.i
", N2.I:" n2.i);
n1.i = 27;
System.out.println ("3: n1.i:" n1.i
", N2.I:" n2.i);
}
} ///: ~
The Number class is very simple, and 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. //: PassObject.java
// Passing Objects to Methods Can Be a bit tricky
Class letter {
Char C;
}
Public class passObject {
Static void f (letter y) {
Y.c = 'z';
}
Public static void main (String [] args) {
Letter x = new letter ();
X.c = 'a';
System.out.println ("1: x.c:" x.c);
f (x);
System.out.println ("2: x.c:" x.c);
}
} ///: ~
In many programming languages, a copy of your own argument Letter Y is designed on the method's scope of the method. 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 various usages of the arithmetic operator: //: Mathops.java
// Demonstrate the Mathematical Operators
Import java.util. *;
PUBLIC CLASS Mathops {
// Create a Shorthand to save Typing:
Static Void PRT (String S) {
System.out.println (s);
}
// shorthand to print a string and an int:
Static void PINT (String S, INT I) {
PRT (S "=" i);
}
// shorthand to print a string and a float:
Static void Pflt (String S, Float F) {
PRT (s "=" f);
}
Public static void main (String [] args) {
// Create a Random Number Generator,
// seeds with current time by Default:
Random Rand = new random ();
INT I, J, K;
// '%' Limits Maximum Value to 99:
J = Rand.NextINT ()% 100;
K = rand.nextint ()% 100;
Pint ("J", J); PINT ("K", K);
I = J K; PINT ("J K", I);
I = J - K; PINT ("J - K", I);
i = k / j; pint ("k / j", i);
i = k * J; PINT ("k * j", i);
i = k% J; PINT ("K% J", I);
J% = k; PINT ("j% = k", j);
// Floating-Point Number Tests:
Float U, V, W; // Applies to Doubles, TOO
v = rand.nextfloat ();
W = rand.nextfloat (); PFLT ("v", v); PFLT ("W", W);
U = V W; PFLT ("V W", U);
U = V - w; PFLT ("V - W", U);
u = v * w; PFLT ("v * w", u);
u = v / w; PFLT ("v / w", u);
// the Following Also Works for
// char, byte, short, int, long,
// and double:
U = V; PFLT ("U = V", U);
U - = V; PFLT ("U - = V", U);
u * = v; pflt ("u * = v", u);
U / = V; PFLT ("U / = V", U);
}
} ///: ~
The first thing we noticed is to print some shortcuts for printing (display): PRT () method prints a string; Pint () first print a string, then print an int;, PFLT () first prints a string, Print a float again. 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: //: Autoinc.java
// DemonStrates the and - operators
Public class autoc {
Public static void main (String [] args) {
INT i = 1;
PRT ("i:" i);
PRT (" i:" i); // pre-increment
PRT ("i :" i ); // post-inccess ("i:" i);
PRT ("- i:" --i); // pre-Decrement
PRT ("I -:" I -); // Post-Decrement
PRT ("i:" i);
}
Static Void PRT (String S) {
System.out.println (s);
}
} ///: ~
The output of the program is as follows:
i: 1
i: 2
i : 2
I: 3
--I: 2
I -: 2
I: 1
It can be seen from it. For the form of the prefix, we get the value after the operation is performed. 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:
//: Equivalence.java
Public class equivalence {
Public static void main (String [] args) {
Integer n1 = new integer (47);
Integer n2 = new integer (47);
System.out.println (N1 == N2);
System.out.println (N1! = N2);
}
} ///: ~
Among them, 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: //: Equalsmethod.java
Public class equalsmethod {
Public static void main (String [] args) {
Integer n1 = new integer (47);
Integer n2 = new integer (47);
System.out.println (n1.equals (n2));
}
} ///: ~
As we expect, the result at this time is TRUE. But things did not end this! Suppose you have created your own class, just like this:
//: Equalsmethod2.java
Class value {
INT I;
}
Public class equalsmethod2 {
Public static void main (String [] args) {
Value v1 = new value ();
Value v2 = new value ();
v1.i = v2.i = 100;
System.out.println (v1.equals (v2));
}
} ///: ~
At this time, the results 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.
//: bool.java
// RELATIONAL and LOGICAL Operators
Import java.util. *;
Public class bool {
Public static void main (String [] args) {
Random Rand = new random ();
INT i = rand.nextint ()% 100;
INT j = rand.nextint ()% 100;
PRT ("i =" i);
PRT ("j =" j);
PRT ("I> J IS" (i> J));
PRT ("i PRT ("I> = j IS" (i> = j)); PRT ("i <= j is" (i <= j)); PRT ("i == j IS" (i == j)); PRT ("i! = j is" (i! = j)); // treating an int as a boolean is // Not Legal Java //! PRT ("I && J IS" (I && J)); //! PRT ("I || J IS" (i || j)); //! PRT ("! i is" ! i); PRT ("(i <10) && (j <10) IS" ((i <10) && (j <10))); PRT ("(i <10) || (j <10) IS" ((i <10) || (j <10))); } Static Void PRT (String S) { System.out.println (s); } } ///: ~ You can only apply both, OR or NOT to the Boolean value. 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: i = 85 J = 4 I> j is true i I> = j is true i <= j is false i == j is false I! = j is true (i <10) && (j <10) is false (i <10) || (j <10) IS TRUE Note If you are expected to use 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: //: Shortcircuit.java // Demonstrate Short-circuiting Behavior // with logical operators. Public class shortcircuit { Static Boolean Test1 (Int Val) { System.out.println ("TEST1 (" VAL ")") System.out.println ("Result:" (Val <1)); Return Val <1; } Static Boolean Test2 (INT VAL) { System.out.println ("TEST2 (" VAL ")") System.out.println ("Result:" (Val <2)); Return Val <2; } Static Boolean Test3 (int val) { System.out.println ("TEST3 (" VAL ")") System.out.println ("Result:" (Val <3)); Return Val <3; } Public static void main (String [] args) { IF (TEST1 (0) && test2 (2) && test3 (2)) System.out.println ("Expression IS True"); Else System.out.Println ("Expression is false"); } } ///: ~ 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 surprised to make you a shock: IF (TEST1 (0) && test2 (2) && test3 (2)) 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. Use the following example to detect your own implementation: //: urshift.java // Test of unsigned Right Shift Public class urshift { Public static void main (String [] args) { INT i = -1; I >>> = 10; System.out.println (i); Long L = -1; l >>> = 10; System.out.println (L); Short s = -1; S >>> = 10; System.out.println (s); BYTE B = -1; B >>> = 10; System.out.println (b); } } ///: ~ The 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: //: Bitmanipulation.java // using the bitwise operators Import java.util. *; Public class bitmanipulation { Public static void main (String [] args) { Random Rand = new random (); INT i = rand.nextint (); INT j = rand.nextint (); Pbinint ("- 1", -1); Pbinint (" 1", 1); INT MAXPOS = 2147483647; Pbinint ("MAXPOS", MAXPOS; INT MAXNEG = -2147483648; Pbinint ("Maxneg", Maxneg; Pbinint ("i", i); Pbinint ("~ i", ~ i); Pbinint ("- i", -i); Pbinint ("j", j); Pbinint ("I & J", I & J); Pbinint ("i | j", i | j); Pbinint ("i ^ j", i ^ j); Pbinint ("i << 5", i << 5); Pbinint ("I >> 5", I >> 5); Pbinint ("(~ I) >> 5", (~ i) >> 5); Pbinint ("I >>> 5", I >>> 5); Pbinint ("(~ i) >>> 5", (~ I) >>> 5); Long L = rand.nextlong (); Long m = rand.nextlong (); Pbinlong ("- 1L", -1L); Pbinlong (" 1L", 1L); Long ll = 9223372036854775807L; Pbinlong ("MAXPOS", LL); Long lln = -9223372036854775808L; Pbinlong ("Maxneg", LLN); Pbinlong ("L", L); Pbinlong ("~ L", ~ L); Pbinlong ("- l", -l); Pbinlong ("M", M); Pbinlong ("L & M", L & M); Pbinlong ("L | M", L | M); Pbinlong ("l ^ m", l ^ m); Pbinlong ("l << 5", l << 5); Pbinlong ("L >> 5", L >> 5); Pbinlong ("(~ L) >> 5", (~ L) >> 5); Pbinlong ("L >>> 5", L >>> 5); Pbinlong ("(~ L) >>> 5", (~ L) >>> 5); } Static void Pbinint (String S, INT I) { System.out.println ( S ", INT:" i ", binary:"); System.out.print (""); For (int J = 31; J> = 0; J -) IF ((1 << j) & i)! = 0) System.out.print ("1"); Else System.out.print ("0"); SYSTEM.OUT.PRINTLN (); } Static void Pbinlong (String S, long L) { System.out.println ( S ", long:" l ", binary:"); System.out.print (""); For (int i = 63; i> = 0; I -) IF ((1L << i) & l)! = 0) System.out.print ("1"); Else System.out.print ("0"); SYSTEM.OUT.PRINTLN (); } } ///: ~ Two methods were measured at the end of the program: 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: -1, int: -1, binary: 1111111111111111111111111111111111 1, Int: 1, binary: 00000000000000000000000000000000000000000000000000001 Maxpos, Int: 2147483647, binary: 0111111111111111111111111111111111 Maxneg, Int: -2147483648, binary: 1000000000000000000002002 I, Int: 59081716, Binary: 00000011100001011000001111110100 ~ i, int: -59081717, binary: 11111100011110100111111000000001011 -i, int: -59081716, binary: 1111110001111010011111000000001100 J, INT: 198850956, Binary: 000010111101101001011100110001100 I & J, Int: 58720644, Binary: 000000111000000000000000011000000100 i | J, Int: 199212028, Binary: 0000101111101111111011101111111100 I ^ J, Int: 140491384, Binary: 00001000010111111101110100111110 I << 5, Int: 1890614912, Binary: 01110000101100000111111010000000000 I >> 5, Int: 1846303, Binary: 000000000001111000010110000011111 (~ i) >> 5, int: -1846304, binary: 11111111111100011110100111111100000 I >>> 5, Int: 1846303, binary: 000000000001111000010110000011111 (~ I) >>> 5, Int: 132371424, binary: 000011111111000000000000 The binary form of the number is manifested as "the value of the 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. "For" amplified conversion ", it is not necessary to make clear shape, because the new type will definitely accommodate the original type of information, which will not cause loss of information. Java allows us to put any main type" model "for anything else A primary type, but the boolean is except for the boolean, the latter is not allowed to perform any styling processing. "Class" is not allowed. In order to convert a class into another, special methods must be used (string string It is a special case, and the book will tell the object to a type "family"; for example, "oak" can be "tree"; vice versa. But for other foreign types, such as "rock" However, it cannot shape "Tree"). 1. When the literal value is started, if you insert a "literal" (literal), the compiler can usually know what type of type to generate. But at some time For types, it is unclear. If this happens, the compiler must be properly "guidance". The method is to add some additional information in the form of a literal value. The following code shows everyone. These characters. //: Literals.java Class Literals { CHAR C = 0xffffff; // max char HEX Value Byte b = 0x7f; // max byte hex value Short s = 0x7fff; // max short hex value INT I1 = 0x2f; // Hexadecimal (LowerCase) INT i2 = 0x2f; // Hexadecimal (Uppercase) INT i3 = 0177; // octal (Leading Zero) // HEX and Oct Also Work with long. Long n1 = 200L; // long suffix Long N2 = 200L; // long suffix Long N3 = 200; //! long l6 (200); // not allowed FLOAT F1 = 1; FLOAT F2 = 1F; // Float SUFFIX FLOAT F3 = 1F; // Float SUFFIX Float F4 = 1e-45f; // 10 to the power Float F5 = 1e 9F; // Float SUFFIX Double D1 = 1D; // Double SUFFIX Double D2 = 1d; // Double SUFFIX Double D3 = 47E47D; // 10 to the power } ///: ~ Hexadecimal (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". Joining Operator type Operator Ulcer Unary - - [[REST ...]] Addicts Arithmetic (and Shift) * /% - << >> Really RELATIONAL > <> = <= ==! = Like Logical (and Bitwise) && ||> ^ C Conditional (Ternary) A> b? X: y A lot Assignment = (And Compound Assignment Like * =) Of course, for shift and standby operators, the above table is not a perfect way to help; but for other operations, it is really useful. 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. / /: Allops.java // Tests All the Operators on All The // Primitive Data Types to show which // ones areatically accountted by the Java Compiler. Class allops { // TO Accept The Results of A Boolean Test: Void F (Boolean B) {} Void BooLtest (Boolean X, Boolean Y) { // Arithmetic Operators: //! x = x * y; //! x = x / y; //! x = x% y; //! x = x y; //! x = x - y; //! x ; //! x -; //! x = y; //! x = -y; // RELATIONAL and LOGICAL: //! f (x> y); //! f (x> = y); //! f (x //! f (x <= y); f (x == y); f (x! = y); f (! y); x = x && y; x = x || y; // bitwise operators: //! x = ~ y; X = x & y; X = x | y; X = x ^ y; //! x = x << 1; //! x = x >> 1; //! x = x >>> 1; // Compound Assignment: //! x = y; //! x - = y; //! x * = y; //! x / = y; //! x% = Y; //! x << = 1; //! x >> = 1; //! x >>> = 1; X & = Y; X ^ = Y; X | = Y; // Casting: //! char C = (char) x; //! Byte B = (byte) x; //! short s = (short) x; //! INT i = (int) x; //! long L = (long) x; //! float f = (float) x; //! Double D = (double) x; } Void Chartest (char x, char y) { // Arithmetic Operators: X = (char) (x * y); x = (char) (x / y); X = (char) (x% y); X = (char) (x y); X = (char) (x - y); X ; X-; x = (char) y; X = (char) -y; // RELATIONAL and LOGICAL: f (x> y); f (x> = y); f (x f (x <= y); f (x == y); f (x! = y); //! f (! x); //! f (x && y); //! f (x || y); // bitwise operators: x = (char) ~ y; X = (char) (x & y); X = (char) (x | y); X = (char) (x ^ y); x = (char) (x << 1); x = (char) (x >> 1); x = (char) (x >>> 1); // Compound Assignment: X = Y; X - = Y; X * = Y; X / = Y; X% = Y; x << = 1; x >> = 1; x >>> = 1; X & = Y; X ^ = Y; X | = Y; // Casting: //! Boolean B = (Boolean) x; BYTE B = (byte) x; Short s = (short) x; INT i = (int) x; LONG L = (long) x; Float f = (float) x; Double D = (double) x; } Void bytest (byte x, byte y) { // Arithmetic Operators: X = (byte) (x * y); X = (byte) (x / y); x = (byte) (x% y); X = (byte) (x y); x = (Byte) (x - y); X ; X-; x = (byte) y; x = (byte) - Y; // RELATIONAL and LOGICAL: f (x> y); f (x> = y); f (x f (x <= y); f (x == y); f (x! = y); //! f (! x); //! f (x && y); //! f (x || y); // bitwise operators: x = (byte) ~ y; X = (byte) (x & y); X = (Byte) (x | y); X = (byte) (x ^ y); X = (byte) (x << 1); x = (Byte) (x >> 1); x = (byte) (x >>> 1); // Compound Assignment: X = Y; X - = Y; X * = Y; X / = Y; X% = Y; x << = 1; X >> = 1; x >>> = 1; X & = Y; X ^ = Y; X | = Y; // Casting: //! Boolean B = (Boolean) x; Char c = (char) x; Short s = (short) x; INT i = (int) x; LONG L = (long) x; Float f = (float) x; Double D = (double) x; } Void Shorttest (short x, short y) { // Arithmetic Operators: X = (short) (x * y); X = (short) (x / y); X = (short) (x% y); X = (short) (x y); X = (short) (x - y); X ; x -; X = (short) y; X = (short) -y; // RELATIONAL and LOGICAL: f (x> y); f (x> = y); f (x f (x <= y); f (x == y); f (x! = y); //! f (! x); //! f (x && y); //! f (x || y); // bitwise operators: X = (short) ~ Y; X = (short) (x & y); X = (short) (x | y); X = (short) (x ^ y); x = (short) (x << 1); x = (short) (x >> 1); x = (Short) (x >>> 1); // Compound Assignment: X = Y; X - = Y; X * = Y; X / = Y; X% = Y; x << = 1; X >> = 1; x >>> = 1; X & = Y; X ^ = Y; X | = Y; // Casting: //! Boolean B = (Boolean) x; Char c = (char) x; BYTE B = (byte) x; INT i = (int) x; LONG L = (long) x; Float f = (float) x; Double D = (double) x; } Void IntTest (int X, int y) { // Arithmetic Operators: X = x * y; x = x / y; x = x% y; X = x y; x = x - y; X ; X-; X = Y; x = -y; // RELATIONAL and LOGICAL: f (x> y); f (x> = y); f (x f (x <= y); f (x == y); f (x! = y); //! f (! x); //! f (x && y); //! f (x || y); // bitwise operators: X = ~ y; X = x & y; X = x | y; X = x ^ y; X = x << 1; X = x >> 1; X = x >>> 1; // Compound Assignment: X = Y; X - = Y; X * = Y; X / = Y; X% = Y; x << = 1; X >> = 1; x >>> = 1; X & = Y; X ^ = Y; X | = Y; // Casting: //! Boolean B = (Boolean) x; Char c = (char) x; BYTE B = (byte) x; Short s = (short) x; LONG L = (long) x; Float f = (float) x; double d = (double) x; } Void Longtest (long x, long y) { // Arithmetic Operators: X = x * y; x = x / y; x = x% y; X = x y; x = x - y; X ; X-; X = Y; x = -y; // RELATIONAL and LOGICAL: f (x> y); f (x> = y); f (x f (x <= y); f (x == y); f (x! = y); //! f (! x); //! f (x && y); //! f (x || y); // bitwise operators: X = ~ y; X = x & y; X = x | y; X = x ^ y; X = x << 1; X = x >> 1; X = x >>> 1; // Compound Assignment: X = Y; X - = Y; X * = Y; X / = Y; X% = Y; x << = 1; X >> = 1; x >>> = 1; X & = Y; X ^ = Y; X | = Y; // Casting: //! Boolean B = (Boolean) x; Char c = (char) x; BYTE B = (byte) x; Short s = (short) x; INT i = (int) x; Float f = (float) x; Double D = (double) x; } Void floattest (float x, float y) { // Arithmetic Operators: X = x * y; x = x / y; x = x% y; X = x y; x = x - y; X ; X-; X = Y; x = -y; // RELATIONAL and LOGICAL: f (x> y); f (x> = y); f (x f (x <= y); f (x == y); f (x! = y); //! f (! x); //! f (x && y); //! f (x || y); // bitwise operators: //! x = ~ y; //! x = x & y; //! x = x | y; //! x = x ^ y; //! x = x << 1; //! x = x >> 1; //! x = x >>> 1; // Compound Assignment: X = Y; X - = Y; X * = Y; X / = Y; X% = Y; //! x << = 1; //! x >> = 1; //! x >>> = 1; //! x & = y; //! x ^ = y; //! x | = y; // Casting: //! Boolean B = (Boolean) x; Char c = (char) x; BYTE B = (byte) x; Short s = (short) x; INT i = (int) x; LONG L = (long) x; Double D = (double) x; } Void DoubleTest (double x, double y) { // Arithmetic Operators: X = x * y; x = x / y; x = x% y; X = x y; x = x - y; X ; X-; X = Y; x = -y; // RELATIONAL and LOGICAL: f (x> y); f (x> = y); f (x f (x <= y); f (x == y); f (x! = y); //! f (! x); //! f (x && y); //! f (x || y); // bitwise operators: //! x = ~ y; //! x = x & y; //! x = x | y; //! x = x ^ y; //! x = x << 1; //! x = x >> 1; //! x = x >>> 1; // Compound Assignment: X = Y; X - = Y; X * = Y; X / = Y; X% = Y; //! x << = 1; //! x >> = 1; //! x >>> = 1; //! x & = y; //! x ^ = y; //! x | = y; // Casting: //! Boolean B = (Boolean) x; Char c = (char) x; BYTE B = (byte) x; Short s = (short) x; INT i = (int) x; LONG L = (long) x; Float f = (float) x; } } ///: ~ Note that Boolean 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. Here's this example shows this: //: Overflow.java // surprise! Java lets you overflow. Public clas overflow { Public static void main (String [] args) { INT BIG = 0x7fffffff; // Max Int ValuePRT ("BIG =" BIG); INT BIGGER = BIG * 4; PRT ("Bigger =" Bigger; } Static Void PRT (String S) { System.out.println (s); } } ///: ~ The output is as follows: BIG = 2147483647bigger = -4 and does not receive an error prompt from the compiler, and 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, this Test () method can tell us that a number of guess is above the target number, or equal: Static int Test (int testval) { Int results = 0; IF (TestVal> Target) Result = -1; Else IF (TestVal Result = 1; Else Result = 0; // match Return Result; } It is best to indent the process control statement to make the reader can easily 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 it utilizes these features: static int test2 { IF (TestVal> Target) Return -1; IF (TestVal Return 1; Return 0; // match } It is not necessary to add Else because the method is no longer continuing after encountering return. 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 it meets specific conditions: //: Whiletest.java // Demonstrates the While loop Public class whiletest { Public static void main (String [] args) { Double R = 0; While (r <0.99d) { r = math.random (); System.out.println (r); } } } ///: ~ It uses the Static (Static) method of Math Coat 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. The For loop is usually used to perform the "Count" task: //: Listcharacters.java // Demonstrates "for" loop by listing // all the ascii character. Public class listcharacters { Public static void main (String [] args) { For (CHAR C = 0; C <128; C ) IF (C! = 26) // Ansi Clear Screen System.out.println ( Value: " (int) C "Character:" C); } } ///: ~ Note that the variable c is defined when it is required to use - the control expression inside the for loop, not the most beginning of the code block marked by the starting rough numbers. 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: For (int i = 0, j = 1; i <10 && j! = 11; i , J ) / * body of for loop * /; 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 it is another example: //: Commaoperator.java Public class commaoperator { Public static void main (String [] args) { For (int i = 1, j = i 10; i <5; i , j = i * 2) { System.out.println ("i =" i "j =" j); } } } ///: ~ The output is as follows: i = 1 j = 11 i = 2 j = 4 i = 3 j = 6 i = 4 j = 8 As you can see, whether in terms of initialization or in the step part, statements are executed sequentially. 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: //: BreakandContinue.java // Demonstrates Break and Continue Keywords Public class breafandcontinue { Public static void main (String [] args) { For (int i = 0; i <100; i ) { IF (i == 74) Break; // out of for loopif (i% 9! = 0) Continue; // Next ity System.out.println (i); } INT i = 0; // AN "Infinite loop": While (true) { i ; INT J = I * 27; IF (j == 1269) BREAK; // out of loop IF (i% 10! = 0) Continue; // Top of Loop System.out.println (i); } } } ///: ~ In this For loop, the value of i will never arrive at 100. 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: 0 9 18 27 36 45 54 63 72 10 20 30 40 The reason why 0 is displayed because 0% 9 is 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. Here is an example of for loop: //: labeledfor.java // java's "labeled for loop" Public class labeledfor { Public static void main (String [] args) { INT i = 0; Outer: // can't Have Statements Here For (; true;) {// infinite loop Inner: // can't Have Statements Here For (; i <10; i ) { PRT ("i =" i); IF (i == 2) { PRT ("Continue"); CONTINUE; } IF (i == 3) { PRT ("Break"; i ; // OtherWise I Never // Gets Increment. Break; } IF (i == 7) { PRT ("Continue Outer"); i ; // OtherWise I Never // gets incremented. CONTINUE OUTER; } IF (i == 8) { PRT ("Break Outer"); Break outer; } For (int K = 0; k <5; k ) { IF (k == 3) { PRT ("Continue Inner"); Continue Inner; } } } } // can't Break or Continue // to labels here } Static Void PRT (String S) { System.out.println (s); } } ///: ~ The PRT () method that has been defined in other examples is used 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. Below is the output result: i = 0 Continue Inner i = 1 Continue Inner i = 2 Continue i = 3 Break i = 4 Continue Inner i = 5 Continue Inner i = 6 Continue Inner i = 7 Continue Outer i = 8 Break Outer 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 usage of the tagged BREAK and the Continue statement in the While loop: //: labeledwhile.java // java's "labeled while" loop Public class labeledwhile { Public static void main (String [] args) { INT i = 0; Outer: While (true) { PRT ("Outer While Loop"; While (true) { i ; PRT ("i =" i); IF (i == 1) { PRT ("Continue"); CONTINUE; } IF (i == 3) { PRT ("Continue Outer"); CONTINUE OUTER; } IF (i == 5) { PRT ("Break"; Break; } IF (i == 7) { PRT ("Break Outer"); Break outer; } } } } Static Void PRT (String S) { System.out.println (s);} } ///: ~ The same rule also applies to while: (1) Simple continue will return the beginning of the innermost loop (top) and continue. (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 an eye: Outer while loop i = 1 Continue i = 2 i = 3 Continue Outer Outer while loop i = 4 i = 5 Break Outer while loop i = 6 i = 7 Break Outer Everyone should remember is: The only place in Java needs to use the label is a nested loop, and when you 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: //: Vowelsandconsonants.java// Demonstrates the switch statement Public Class Vowelsandconsonants { Public static void main (String [] args) { For (int i = 0; i <100; i ) { CHAR C = (char) (Math.random () * 26 'a'); System.out.print (C ":"); Switch (c) { Case 'a': Case 'E': Case 'I': Case 'o': Case 'u': System.out.println ("Vowel"); Break; Case 'Y': Case 'W': System.out.println ( "Sometimes a vowel"); Break; DEFAULT: System.out.Println ("consonant"); } } } } ///: ~ Since Math.random () generates a value between 0 and 1, just multiply the maximum random number (for English letters, this number is 26), plus an offset, get it Minimum 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. It should also be noted that the BREAK statement is placed at the end of a particular CASE, otherwise the control process will simply move, and continue to determine if the next condition is consistent. 1. Specific calculations should pay special attention to the following statement: char c = () * 26 'a'); Math.random () generates a Double value, so 26 will be converted to Double type In order to perform multiplication. This calculation also produces a Double value. This means that in order to perform the addition, you must be converted into a Double. Using a "style", the double result will be converted back to the char. What is our first question is what processing is made to Char? In other words, it is assumed that a value is 29.7, we put it into a char, then the result value is 30 or 29? The answer can be obtained from the following example: //: castingnumbers.java // What happens when you get a float or double // TO AN INTEGRAL VALUE? Public class castingnumbers { Public static void main (String [] args) { Double ABOVE = 0.7, BELOW = 0.4; System.out.println ("Above:" Above); System.out.println ("BELOW: BELOW); System.out.println ( (int) Above: " (int) letter; System.out.println ("(int) below:" (int) below); System.out.println ( (CHAR) ('a' Above): " (CHAR) ('a' letter); System.out.println ( (CHAR) ('A' Below): " (Char) ('a' below); } } ///: ~ The output is as follows: ABOVE: 0.7 BELOW: 0.4 (INT) Above: 0 (int) BELOW: 0 (Char) ('a' Above): a (Char) ('a' below): a So the answer is: After a FLOAT or DOUBLE value is integrated into an integer value, it always "cuts off" in the decimal part, does not make any carry processing. The second question is related to Math.random (). It produces a value between 0 and 1, but does it include value '1'? Expressed with orthodox mathematics language, it is (0, 1), [0, 1], (0, 1], or [0, 1) (square brackets "include", parentheses "not include" )? Similarly, a model program reveals the answer to us: //: randombounds.java // does math.random () Product 0.0 and 1.0? Public class randombons { Static void usage () { System.err.Println ("USAGE: / N / T" "RandomBounds Lower / N / T" "Randombounds upper"); System.exit (1); } Public static void main (String [] args) { IF (args.length! = 1) USAGE (); IF (Args [0]. Equals ("Lower")) { While (math.random ()! = 0.0) ; // Keep Trying System.out.println ("Produced 0.0!"); } Else IF (Args [0]. Equals ("Upper")) { While (math.random ()! = 1.0) ; // Keep Trying System.out.println ("Produced 1.0!"); } Else USAGE (); } } ///: ~