Logical operators only work with operands like boolean... All boolean operators with two operands combine two boolean values to form the resulting boolean value. Do not confuse with.
Boolean operator table in Java
Logical operators & , | , ^ apply to values of type boolean exactly the same as with respect to bits of integer values. Logical operator ! inverts (reverses) the boolean state: ! true == false and ! false == true.
Table. Logical Operator Results
A | B | A | B | A & b | A ^ B | ! A |
---|---|---|---|---|---|
false | false | false | false | false | true |
true | false | true | false | true | false |
false | true | true | false | true | true |
true | true | true | true | false | false |
Abbreviated Boolean Operators
In addition to standard operators AND (&) and OR (|) there are shorthand operators && and || .
If you look at the table, you can see that the result of executing the operator OR is equal to true true, regardless of the value of operand B. Similarly, the result of executing the operator AND is equal to false when the value of operand A is false, regardless of the value of operand B. It turns out that we do not need to calculate the value of the second operand, if the result can be determined already by the first operand. This becomes useful in cases where the value of the right operand depends on the value of the left one.
Consider the following example. Let's say we introduced a rule - to feed or not feed the cat, depending on the number of mice caught per week. Moreover, the number of mice depends on the weight of the cat. The larger the cat, the more he must catch mice.
The cat, who read the condition of the problem, was offended by me. He said that I was behind the times, and in the courtyard of the 21st century - mice can be caught with the help of mousetraps. I had to explain to him that this is just a task, and not an example from my personal life.
Int mouse; // number of mice int weight; // the weight of the cat in grams mouse = 5; weight = 4500; if (mouse! = 0 & weight / mouse< 1000) { mInfoTextView.setText("Можно кормить кота"); }
If you run the program, the example will work without problems - five mice per week is enough to pamper your cat with a delicious breakfast. If he catches four mice, then problems with the cat's nutrition will begin, but not with the program - it will work, it will simply not display a message about permission to feed the parasite.
Now let's take an edge case. The cat got lazy and didn't catch a single mouse. Variable value mouse will be equal to 0, and there is a division operator in the expression. And you cannot divide by 0 and our program will close with an error. It would seem that we have provided an option with 0, but Java evaluates both expressions mouse! = 0 and weight / mouse< 1000 , despite the fact that already in the first expression it returns false.
Let's rewrite the condition as follows (add just one symbol):
If (mouse! = 0 && weight / mouse< 1000) { mInfoTextView.setText("Можно кормить кота"); }
The program now runs without crashing. Once Java saw that the first expression was returning false, then the second division expression is simply ignored.
Abbreviated operator variants AND and OR usually used in situations where Boolean operators are required, and their one-character cousins are used for bitwise operations.
Ternary operator
The Java language also has a special ternary conditional operator that can replace certain types of operators. if-then-else is the operator ?:
The ternary operator uses three operands. The expression is written in the following form:
LogicalCondition? expression1: expression2
If logicalCondition equals true, then it is calculated expression1 and its result becomes the result of the execution of the entire statement. If logicalCondition equals false, then it is calculated expression2, and its value becomes the result of the operator's work. Both operands expression1 and expression2 must return a value of the same (or compatible) type.
Consider an example in which the variable absval the absolute value of the variable is assigned val.
Int absval, val; val = 5; absval = val< 0 ? -val: val; // выводим число mInfoTextView.setText("" + absval); val = -5; absval = val < 0 ? -val: val; mInfoTextView.setText("" + absval);
Variable absval the value of the variable will be assigned val if the value is greater than or equal to zero (second part of expression). If the value of the variable val is negative, then the variable absval the value of the variable is assigned, taken with a minus sign, as a result, minus by minus will give a plus, that is, a positive value. Let's rewrite the code using if-else:
If (val< 0) absval = -val; else absval = val;
You can look at another example with the ternary operator.
Most operations on primitive types are performed not using methods, but using special characters called operation sign.
Assignment operation
Assigning to a variable the value of a constant, another variable, or an expression (variables and / or constants separated by operation signs) is called assignment operation and is indicated by the sign " = ", for example: x = 3; y = x; z = x; In Java, it is permissible to reuse the assignment operation in one expression, for example: x1 = x2 = x3 = 0; This operation is performed from right to left, that is, first to the variable x3 is assigned the value 0, then the variable x2 is assigned the value of the variable x3 (0), and finally the variable x1 is assigned the value of the variable x2 (0). The signs of operations whose arguments are numbers fall into two categories: unary(unary) tokens for single-argument operations and binary(binary) with two arguments.Unary operations
The following unary operations are defined in Java:- unary minus "-" - changes the sign of a number or expression to the opposite;
- unary plus "+" - does not perform any action on a number or expression;
- bitwise complement "~" (only for integers) - inverts all bits of the number field (changes 0 to 1 and 1 to 0);
- increment "++" (only for integers) - increases the value of the variable by 1;
- decrement "-" (only for integers) - decreases the value of the variable by 1.
Arithmetic Binary Operations
Java defines the following arithmetic binary operations:- addition "+";
- subtraction "-";
- multiplication " * ";
- division "/";
- calculating the remainder of dividing integers "%" (returns the remainder of dividing the first number by the second, and the result will have the same sign as the dividend), for example, the result of operation 5% 3 will be 2, and the result of operation (-7) % (- 4) will be -3. In Java, the operation can also be used for real variables (such as float or double).
Bitwise operations
- Bitwise operations treat the original numeric values as bit fields and do the following on them:
- setting the bit to i-th position of the result field to 1, if both bits are in i-th positions of the operands are equal to 1, or to 0, otherwise - bitwise AND ("&");
- setting the bit to i-th position of the result field to 1, if at least one bit in i-th positions of the operands is equal to 1, or to 0, otherwise - bitwise OR ("|");
- setting the bit to i-th position of the result field to 1, if the bits in i-th positions of the operands are not equal to each other, or to 0, otherwise - bitwise exclusive OR ("^");
- left shift of the bits of the field of the first operand by the number of bits determined by the second operand (the sign bit of the number does not change in this case) - bitwise shift to the left, taking into account the sign "<< ";
- shift to the right of the bits of the field of the first operand by the number of bits determined by the second operand (the sign bit of the number does not change in this case) - bitwise shift to the right, taking into account the ">>" sign;
- shift to the right of the bits of the field of the first operand by the number of bits determined by the second operand (the sign bit of the number is also shifted in this case) - bitwise shift to the right without taking into account the ">>>" sign.
Bitwise AND
int x = 112; int y = 94; int z; z = x & y; // z = 80: 00000000 00000000 00000000 01010000Bitwise OR
int x = 112; // x: 00000000 00000000 00000000 01110000 int y = 94; // y: 00000000 00000000 00000000 01011110 int z; z = x | y; // z = 126: 00000000 00000000 00000000 01111110Bitwise exclusive OR
int x = 112; // x: 00000000 00000000 00000000 01110000 int y = 94; // y: 00000000 00000000 00000000 01011110 int z; z = x ^ y; // z = 46: 00000000 00000000 00000000 00101110Shift to the left, taking into account the sign
int x = 31, z; // x: 00000000 00000000 00000000 00011111 z = x<< 2 ; // z = 124: 00000000 00000000 00000000 01111100Shift to the right, taking into account the sign
int x = - 17, z; z = x >> 2; // z = -5: 11111111 11111111 11111111 11111011Shift to the right without regard to sign
int x = - 17, z; // x: 11111111 11111111 11111111 11101111 z = x >>> 2; // z = 1073741819 // z: 00111111 11111111 11111111 11111011
Combined operations
In Java, for binary arithmetic operations, you can use combined(compound) operation tokens: identifier operation = expression This is equivalent to the following operation: identifier = identifier operation expression Examples:- The expression x + = b means x = x + b.
- The expression x - = b means x = x - b.
- The expression x * = b means x = x * b.
- The expression x / = b means x = x / b.
- The expression x% = b means x = x% b.
- The expression x & = b means x = x & b.
- The expression x | = b means x = x | b.
- The expression x ^ = b means x = x ^ b.
- Expression x<<= b означает x = x << b .
- The expression x >> = b means x = x >> b.
- The expression x >>> = b means x = x >>> b.
Comparison operations
Java defines the following comparison operators:- "==" (equal), "! =" (not equal),
- ">" (greater than), "> =" (greater or equal),
- " < " (меньше) " <= " (меньше или равно)
Boolean operations
Boolean operations are executed on boolean variables and their result is also a value of type boolean... The following boolean operations are defined in Java:- negation "!" - replacing false with true, or vice versa;
- AND operation "&" - the result is true only if both operands are true, otherwise the result is false;
- OR operation "|" - the result is true only if at least one of the operands is true, otherwise the result is false.
- XOR operation "^" - the result is true only if the operands are not equal to each other, otherwise the result is false.
Conditional operation
A conditional operation is written in the form expression-1? Expression-2: expression-3. In this case, expression-1 is evaluated first, which should give a boolean value, and then, if expression-1 is true, expression-2 is evaluated and returned as the result of the operation, or (if expression-1 is false), and expression-3 is returned as the result of the operation. An example of a conditional operation: x = n> 1? 0: 1; The variable x will be assigned the value 0 if n> 1 (expression n> 1 evaluates to true) or 1 if n≤1 (expression n> 1 evaluates to false).Seniority of operations
Operations in expressions are performed from left to right, however, according to their priority. So multiplication operations in the expression y = x + z * 5; will be executed before the addition operation because the priority of the multiplication operation is higher than the priority of the addition operation. Operation priorities (in order of decreasing priority) in Java are shown in Table. one.Parentheses increase the precedence of the operations that are within them. So, if you insert parentheses into the above expression: y = (x + z) * 5; then the addition operation will be performed first, and then the multiplication operation. Sometimes parentheses are used simply to make the expression more readable, for example: (x> 1) && (x<= 5 ) ;
Type conversion and casting when performing operations
In assignment and arithmetic expressions, literals, variables and expressions of different types can be used, for example: double y; byte x; y = x + 5; This example adds the byte variable x to the literal 5 (int), and assigns the result to the double variable y. In Java, as in the C language, type conversions in the evaluation of expressions can be performed automatically, or using a cast operator. However, the casting rules are somewhat different from those of the C language, and in general are more strict than in the C language. When performing an assignment operation, the type conversion occurs automatically if widening transform(widening conversion) and the two types are compatible... Widening transformations are transformations byte® short® int® long® float® double... For widening conversions, numeric types, including integer and floating point, are compatible with each other. However, numeric types are not compatible with char and boolean types. The char and boolean types are not compatible with each other either. Java also performs automatic type conversion when storing a literal integer constant (which is of type int by default) in variables of type byte, short, or long (however, if the literal has a value outside the range of valid values for this type, an error message is displayed: possible loss of accuracy). If the conversion is a narrowing conversion, that is, byte ¬ short ¬ char ¬ int ¬ long ¬ float ¬ double is being performed, then such a conversion may result in loss of precision or distortion of the number. Therefore, with narrowing conversions, when the program is compiled, a diagnostic message about type incompatibility is displayed and class files are not created. This message will also be displayed when trying to convert expressions of type byte or short into a variable of type char. If it is nevertheless necessary to perform such conversions, a cast operation is used, which has the following format: ( conversion-type) meaning, where conversion-type defines the type to which the given should be converted meaning, for example, as a result of executing operators: byte x = 71; char symbol = (char) x; the symbol variable will be set to "G". If a floating-point value is assigned to an integer type, then (if the floating-point value has a fractional part), an explicit type conversion also occurs truncation(truncation) numbers. So, as a result of executing the operator int x = (int) 77.85; variable x will be set to 77. If the assigned value is out of range type-conversions , then the result of the conversion will be the remainder of dividing the value by the modulus of the range of the assigned type (for numbers of type byte, the modulus of the range will be 256, for short - 65536, for int - 4294967296, and for long - 18446744073709551616). For example, as a result of the statement byte x = (byte) 514; variable x will be set to 2. When converting integers or real numbers to data of type char, conversion to a character occurs if the original number is in the range from 0 to 127, otherwise the character gets the value "?". When performing arithmetic and bitwise conversions, all byte and short values, as well as char, are expanded to int, (while the numeric value of the character code is used in calculations for char) then, if at least one operand is of type long, the type of the integer expression is expanded to long. If one of the operands is of type float, then the type of the complete expression is expanded to float, and if one of the operands is of type double, then the type of the result will be double. So, if variables are declared byte a, c; short b; then in the expression a + b * c - 15 L + 1.5F + 1.08 - 10; first, before calculating a + b * c, the values of the variables will be expanded to int, then, since constant 15 is of type long, the result of the calculation will be increased to long before subtraction. After that, since literal 1.5 is of type float, the result of calculating a + b * c - 15L will be expanded to float before being added to this literal. Before performing the addition with the number 1.08, the result of the previous calculations will be expanded to double (since real constants are of type double by default) and, finally, before performing the last addition, literal 10 (by default int) will be expanded to double. Thus, the result of evaluating the expression will be of type double. Automatic type extensions (especially short and byte extensions to int) can cause poorly recognized compile-time errors. For example, in the operators: byte x = 30, y = 5; x = x + y; before the addition is performed, the value of the variables x and y will be expanded to int, and then an error message will be displayed when attempting to assign the result of a computation of type int to a variable of type byte. To avoid this it is necessary to use an explicit type conversion in the second operator: x = (byte) (x + y); You must enclose the expression x + y in parentheses because the priority of the cast enclosed in parentheses is higher than the priority of the addition operation. By the way, if you write the second operator as: x + = y; there will be no error message. Link to firstLast update: 30.10.2018
Most of the operations in Java are similar to those used in other C-like languages. There are unary operations (performed on one operand), binary operations on two operands, and ternary operations on three operands. An operand is a variable or value (for example, a number) involved in an operation. Let's consider all types of operations.
They participate in arithmetic operations by numbers. Java has binary arithmetic operations (performed on two operands) and unary (performed on one operand). Binary operations include the following:
the operation of adding two numbers:
Int a = 10; int b = 7; int c = a + b; // 17 int d = 4 + b; // eleven
operation of subtracting two numbers:
Int a = 10; int b = 7; int c = a - b; // 3 int d = 4 - a; // -6
the operation of multiplying two numbers
Int a = 10; int b = 7; int c = a * b; // 70 int d = b * 5; // 35
division operation of two numbers:
Int a = 20; int b = 5; int c = a / b; // 4 double d = 22.5 / 4.5; // 5.0
It is worth considering when dividing, since if two integers are involved in the operation, the result of the division will be rounded to an integer, even if the result is assigned to a float or double variable:
Double k = 10/4; // 2 System.out.println (k);
For the result to be a floating point number, one of the operands must also represent a floating point number:
Double k = 10.0 / 4; // 2.5 System.out.println (k);
getting the remainder from division of two numbers:
Int a = 33; int b = 5; int c = a% b; // 3 int d = 22% 4; // 2 (22 - 4 * 5 = 2)
There are also two unary arithmetic operations that are performed on the same number: ++ (increment) and - (decrement). Each of the operations has two types: prefix and postfix:
++ (prefix increment)
Assumes increasing the variable by one, for example, z = ++ y (first, the value of the variable y is increased by 1, and then its value is assigned to the variable z)
Int a = 8; int b = ++ a; System.out.println (a); // 9 System.out.println (b); // 9
++ (postfix increment)
Also represents an increase in a variable by one, for example, z = y ++ (first, the value of y is assigned to z, and then the value of y is increased by 1)
Int a = 8; int b = a ++; System.out.println (a); // 9 System.out.println (b); // eight
- (prefix decrement)
decreasing the variable by one, for example, z = - y (first, the value of the variable y is decreased by 1, and then its value is assigned to the variable z)
Int a = 8; int b = --a; System.out.println (a); // 7 System.out.println (b); // 7
- (postfix decrement)
z = y-- (first, the value of the variable y is assigned to the variable z, and then the value of the variable y is decreased by 1)
Int a = 8; int b = a--; System.out.println (a); // 7 System.out.println (b); // eight
Arithmetic priority
Some operations take precedence over others and are therefore performed first. Operations in decreasing order of priority:
++ (increment), - (decrement)
* (multiplication), / (division),% (remainder of division)
+ (addition), - (subtraction)
The priority of operations should be taken into account when executing a set of arithmetic expressions:
Int a = 8; int b = 7; int c = a + 5 * ++ b; System.out.println (c); // 48
First, the increment ++ b operation will be performed, which has a higher priority - it will increase the value of the variable b and return it as a result. Then the multiplication 5 * ++ b is performed, and only the last addition is a + 5 * ++ b
Brackets allow you to redefine the order of calculations:
Int a = 8; int b = 7; int c = (a + 5) * ++ b; System.out.println (c); // 104
Despite the fact that the addition operation has a lower priority, the addition will be performed first, and not the multiplication, since the addition operation is enclosed in parentheses.
Associativity of operations
In addition to the priority, operations are distinguished by such a concept as associativity... When operations have the same precedence, the order of evaluation is determined by the associativity of the operators. There are two types of operators depending on associativity:
Left associative operators that execute from left to right
Right associative operators that execute from right to left
For example, some operations, such as multiplication and division, have the same priority. What then will be the result in the expression:
Int x = 10/5 * 2;
Should we interpret this expression as (10/5) * 2 or as 10 / (5 * 2)? Indeed, depending on the interpretation, we will get different results.
Since all arithmetic operators (except for prefix increment and decrement) are left associative, that is, they are executed from left to right. Therefore, the expression 10/5 * 2 must be interpreted as (10/5) * 2, that is, the result will be 4.
Floating point operations
It should be noted that floating point numbers are not suitable for financial and other calculations where rounding errors can be critical. For instance:
Double d = 2.0 - 1.1; System.out.println (d);
In this case, the variable d will not be equal to 0.9, as one might initially assume, but 0.8999999999999999. Precision errors like this occur because the binary system is used at a low level to represent floating point numbers, but there is no binary representation for 0.1, as well as for other fractional values. Therefore, if in such cases, the BigDecimal class is usually used, which allows you to bypass such situations.
Java lecture notes. Session 4
(none) (none) ::(none)
(V. Fesyunov)
Java operators
Most Java operations are simple and intuitive. These are operations such as +, -, *, /,<,>and others. Operations have their own order of execution and priorities. So in the expression
the multiplication is performed first, and then the addition, since the multiplication has a higher priority than the addition. In the expression
first a + b is calculated, and then c is subtracted from the result, since the order of these operations is from left to right.
But Java operations have their own peculiarities. Without going into a detailed description of the simplest operations, let's dwell on the features.
Let's start with assignments... Unlike a number of other programming languages in Java, assignment is not an operator, but an operation. The semantics of this operation can be described as follows.
- The assignment operation is denoted by the "=" symbol. It calculates the value of its right-hand operand and assigns it to the left-hand operand, and returns the assigned value as a result. This value can be used by other operations. A sequence of several assignments is performed from right to left.
In the simplest case, everything looks as usual.
Here, exactly what we intuitively mean happens - the sum of a and b is calculated, the result is entered into x. But here are two other examples.
In the first, first 1 is entered into b, the result of the operation is 1, then this result is entered into a. In the second example, the sum of a and b is calculated and the result is lost. It's pointless, but syntactically valid.
Comparison operations
These are operations>,<, >=, <=, != и ==. Следует обратить внимание, что сравнение на равенство обозначается двумя знаками "=". Операндами этих операций могут быть арифметические данные, результат — типа boolean.
Increment, decrement operations
These are ++ and - operations. So y ++ (increment) is shorthand for y = y +1, similarly with the decrement (-) operation.
But there is one subtlety with these operations. They come in two forms, prefix (++ y) and postfix (y ++). The effect of these operations is the same - they increase (decrement operations - decrease) their operand by 1, but their result is different. The prefix form as a result gives the value of the operand already changed by 1, and the postfix form gives the value of the operand before the change.
A = 5; x = a ++; y = ++ a;
In this snippet, x will be set to 5 and y to 7.
Integer division operation
It should be borne in mind that dividing one whole by another produces a whole, and does not round, but discards the fractional part.
Remainder of division (modulo value)
Java has the% operator, which denotes the remainder of a division.
Extended assignment operations
In addition to the usual "=" operation in Java, there are operations + =, - =, * =, / =, etc. These are shorthand notations. So a + = b is completely equivalent to a = a + b. Similarly, with other such operations.
Logical operations
! - negation && - logical "and" || - logical "or"
The operands of these operations must be of type boolean, the result is boolean. && and || have one peculiarity - their right-hand operand may not be calculated if the result is already known from the left-hand operand. So, if the left operand of the && operation is false, then the right operand will not be calculated, since the result is still false.
This property must be taken into account, especially when the right-hand operand contains a call to some function.
Bitwise logical operations
These are operations
& - bitwise "and" | - bitwise "or" ^ - bitwise "exclusive or" ~ - bitwise negation
They are executed for each pair of bits of their operands.
Shift operations
<< — сдвиг влево >> - shift right >>> - unsigned shift right
These operations shift the value of their left operand by the number of bits specified by the right operand.
Conditional operation
This is the only ternary operation, i.e. an operation that has three operands. Accordingly, not one operation sign is used for it, but two.
<условие> ? <выражение1> : < выражение2>
If<условие>is true, the result is< выражение1>, otherwise< выражение2>.
For example, "a< b ? a: b" вычисляет минимум из a и b.
Casting operation
This is a very important operation. By default, all conversions that can lead to problems are prohibited in Java. So, you cannot assign a long value to an int operand. In cases where it is still necessary, you need to put an explicit type conversion.
For example, suppose the f (...) method returns long.
int x = (int) f (10);
Here (int) is a type conversion operation. A type conversion operation is indicated by the type name enclosed in parentheses.
This operation applies not only to base types, but also to classes. We'll take a closer look at this when we look at inheritance.
Literals (constants)
Arithmetic
Examples of arithmetic constants
10 - 010 is 8 - 0123 is 83 (1 * 64 + 2 * 8 + 3) - 0x10 is 16 - 0x123 is 291 (1 * 256 + 2 * 16 +3) - 1e5 is 100000 - 1.23 e-3 is 0.00123
To indicate the type of a constant, suffixes are used: l (or L) - long, f (or F) - float, d (or D) - double. For instance,
1L is one, but of type long.
Boolean literals
Boolean literals are true and false
String literals
Are written in double quotes, for example
"this is a string"
Character literals
They are written in apostrophes, for example "F", "w".
In string and character literals, there are rules for writing specials. characters. First, there is a set of predefined specials. characters. This
- "\ n" - end of line (line feed) - "\ r" - carriage return - "\ t" - tab
and a number of others.
Secondly, you can explicitly write the character code (you just need to know it). The code is usually written in the octal system: "\ 001" is a character with code 1, etc.
Statements
Operator - Expression
Syntax
<выражение>;
Such an operator consists of one expression, at the end is ";". Its action is to evaluate the expression, the value calculated by this expression is lost. Those. usually such an expression contains an assignment operator, although this is not required by syntax.
A = 0; x = (a> b? a: b); cnt ++;
Conditional statement (if)
Syntax
If (<условие>) <оператор1>
Here<условие>Is a logical expression, i.e. an expression that returns true or false. As you can see from the syntax, the else part is optional. There is one operator after the if and after the else. If you need to put several operators there, then you need to put block . Block starts with "(" and ends with ")".
In Java, it is customary to always put a block, even if there is one statement after the if or else.
If (a> b) (x = a;) else (x = b;) if (flag) (flag = false; init ();)
In the last example, flag is a boolean variable or field, init () is a method called if the flag is true (they say "if flag is set").
The return statement (already seen)
Loop operator by precondition (while)
Syntax
While (<условие>) <оператор>
As with the if statement, it is customary in Java<оператор>enclose in curly braces.
Int i = 0; while (more) (x / = 2; more = (++ i< 10); }
In this example, more should be a boolean variable or field, x some arithmetic variable or field. The cycle is performed 10 times.
Postcondition loop operator (do while)
Syntax
Do<оператор>while (<условие>);
The loop operator by postcondition differs from the loop operator by precondition only in that the loop iteration is always executed in it at least once, while in the precondition operator there may not be a single loop iteration (if the condition is immediately false).
Int i = 0; do (x \ = 2; more = (++ i< 10); } while (more);
Counter loop operator (for)
Syntax
For (<инициализация>; <условие>; <инкремент>) <оператор>
The header of such a cycle contains three expressions (in the simplest case). From the name of the operator, it can be understood that it serves to organize a cycle with a counter. Therefore the expression<инициализация>is executed once before the first iteration of the loop. After each iteration of the loop, the expression is executed<инкремент>and then the expression<условие>... The last expression must be logical and is used to set the condition for continuing the cycle. Those. as long as it is true, the loop will continue to loop.
For the convenience of composing loop operators with a counter, a lot of extensions have been introduced in this construction.
- <инициализация>may not be an expression, but a description with initialization of type "int i = 0".
- <инициализация>can be a comma-separated list of expressions, such as "i = 0, r = 1".
- <инкремент>can also be a list of expressions, for example, "i ++, r * = 2"
- All components (<инициализация>, <условие>and<инкремент>) are optional. To express<условие>this means that the condition is always considered true (i.e. the exit from the loop must be organized by some means inside the loop itself).
Those. let's say the following loop (infinite loop):
For (;;) (...)
For (int i = 0; i< 10; i++) x /=2;
This is the most "economical" loop implementation from the previous examples.
Break and continue statements
There are no goto statements in Java. As you know, goto leads to unstructured programs. The break and continue statements are structured analogs of goto.
They can be used in loops, and break can also be used in a switch statement. Execution of the break statement causes the loop to end immediately. The continue statement causes the end of the current iteration of the loop and the beginning of a new one. In this case, the condition check is still performed, so continue can cause the end of the loop as well.
For (int i = 0;; i ++) (if (oddOnly && i% 2 == 0) continue; y = (x + 1) / x; if (y - x< 0.001) break; x = y; }
Here oddOnly is a boolean variable. If it is set, then all loop iterations with even numbers are skipped using the continue statement;
The loop termination condition in this example is checked in the middle of the loop, and if it is satisfied, the loop is terminated using the break statement.
With nested loops, the break and continue statements can refer not only to the loop in which they are located, but also to the enclosing loop. To do this, the enclosing loop statement must be marked with a label, which must be specified in the break or continue statement. For instance,
Lbl: while (...) (... For (...) (... If (...) break lbl;)...)
Here, the break statement will cause both the for loop and the while loop to terminate.
Selection statement (switch)
Serves to organize a selection by some value of one of several branches of execution.
Syntax
Switch (<выражение>) (case<константа1>: <операторы1>case<константа2>: <операторы2> . . . }
The expression must return an integer or character value, and the constants must be of the same type as the value of this expression.
Case elements<константа>: "are jump labels, if the expression value coincides with a constant, then a jump to this label will be made. If the expression value does not match any of the constants, then everything depends on the presence of the default fragment. If it is, then the transition occurs to the default label if not, then the entire switch statement is skipped.
- In a switch statement, case fragments do not form any blocks. If after the last statement of this case-fragment there is the next case, then the execution will continue, starting from the first statement of this case-fragment.
- Because of this, a break statement is usually used in a switch statement. It is placed at the end of each case-fragment.
Example (SymbolTest.java file)
Consider a demo program that uses the for and switch statements.
This program generates randomly 100 characters of the Latin alphabet and classifies them as "vowels", "consonants" and "sometimes vowels". The last category includes the symbols "y" and "w".
Public class SymbolTest (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("гласная"); break; case "y": case "w": System.out.println("иногда гласная"); break; default: System.out.println("согласная"); } } } }
In this example, there are several elements that are new to us.
- The random () method of the Math class is used. Let's look at the documentation for the Math class and see what it does.
- In the statement char c = (char) (Math.random () * 26 + "a"); the arithmetic value is added to the symbol. With this addition in Java, the symbol is converted to a number that is equal to the code of this symbol.
- In the statement System.out.print (c + ":"); not println (...) is used, but print (...). The print (...) method differs from println (...) only in that it does not print to a new line, so that the next print (...) or println (...) statement will continue printing on the same line.
You should also pay attention to the case fragments. Formally, there are 7 such fragments, but 5 of them do not contain any operators. So, we can assume that there are 2 case fragments, but each of them has several case labels.
Homework
- 1 Change SymbolTest.java so that the number of generated symbols is specified by the program call parameter.
- 2 Write a program that takes two numbers as call parameters - the lengths of the legs of a right-angled triangle, and prints the angles in degrees as a result.
(none)