Hello, welcome back, HAKUNA MATATA!!!
When it comes to operations, you may immediately think of four operations of addition, subtraction, multiplication, division and "99 multiplication table". It was a nightmare to recite the "99 multiplication table" back then! After many years, my heart is still aching. However, learning to use programming language to perform operations now is much more efficient than using formulas and "99 multiplication table", and it is also much easier, because the real operation process is handed over to the machine, and we only need to provide data and calculation rules.
Following the content of the last course, now we will learn how to calculate data in the Java language. With the same curiosity as children, see how Java calculates the results step by step.
The following are the main knowledge points of this article:
- Eighteen martial arts: operators in Java
- Arithmetic operation: first learn to dance a knife and get a gun
- Assignment operation: add a point to the skill
- Comparative calculation: it's a mule or a horse. Pull it out for a walk
- Logical operation: who is right and who is wrong, there must be a statement
- Binocular operation: the ultimate answer to selection difficulty
The first level 18 martial arts: operators in Java
The first step to program thinking is to learn to use computers, or write programs to help us process data, rather than ourselves. There are many methods of data operation in Java language, as mentioned above, including but not limited to arithmetic operation, comparison operation, logic operation, assignment operation, ternary operation, etc. Each operation method contains many operators. I vividly call these operators "eighteen kinds of martial arts". Learning operations in Java is to learn the use of these operators, that is, the process of cultivating the "eighteen kinds of martial arts".
Operators, as the name suggests, are symbols that operate on data (constants and variables). We connect the data with operators to form expressions that can operate. For example, 1 + 2, 3 * 4, etc. look at this line of code:
public class Test{ public static void main(String[] args) { int number = 1 + 2; // Use the plus sign (+) to connect constants 1 and 2 to form an addition expression, and assign the operation result to the variable number System.out.println(number); // Output the value of number } }
The above formula is to use the operator plus sign (+) to connect constants 1 and 2 to form an addition expression, and assign the operation result to the variable number. If nothing happens, the print result should be:
3
In fact, there may be many data involved in the operation, or variables, constants, etc. may be mixed together for operation, for example (follow the above code):
public class Test{ public static void main(String[] args) { int number = 1 + 2; // Use the plus sign (+) to connect constants 1 and 2 to form an addition expression, and assign the operation result to the variable number System.out.println(number); // Output the value of number int count = number + 10; // Variables and constants participate in the operation at the same time System.out.println(count); // Output calculation results } }
Print results:
13
In addition, there are many operation methods, such as addition, subtraction, remainder (modulo), comparison operation, etc., but they all have a common feature: each expression will have an operation result. We summarize and classify the types of expressions according to the data types of expression operation results, such as:
Integer expression: the operation result is an integer. For example: 1 + 2, 10 * 20, 5 - 3, their operation results are integers
Floating point expression: the operation result is a floating point number. For example: 3.14 * 2, 0.618 + 0.382, 3.0/1, their operation results are floating-point numbers
Boolean expression: the operation result is a Boolean value. For example: 2 > 1, (20-10) < 15, their operation results are Boolean: either true or false.
After practicing the basic skills of operators and expressions, now we can start learning real martial arts.
The second level of arithmetic operation (Part I): learn to dance a knife and get a gun
Let's start with a few simple moves and review our arithmetic operations in primary school. There are seven arithmetic operators in Java:
The first four operators are fairly common: +, -, *, /, Although the multiplication sign (*) and division sign (/) are different from what we have seen before, it is not difficult to understand. The percent sign (%) here means "remainder" and "modulus", that is, using the percent sign (%) can get the remainder of the number 7 divided by 3: 1. + +, and - - are unfamiliar. They represent "self increasing 1" and "self decreasing 1" respectively , this kind of operation is something we haven't seen before. Next, I'll teach you every move with my hands - the use of operators.
2.1 addition, subtraction, multiplication and division
First, learn how to dance a knife and get a gun - the usage of four operations. The above code:
public class Test{ public static void main(String[] args) { int num1 = 3; int num2 = 4; int num3 = 5; int num4 = 10; // 1. Addition operation int add = num1 + num2; // 2. Subtraction int subtract = num2 - num1; // 3. Multiplication int multiply = num2 * num3; // 4. Division operation int divide = num4 / num3; // Output operation results respectively System.out.println(add); // Output addition calculation results System.out.println(subtract); // Output subtraction calculation results System.out.println(multiply); // Output multiplication calculation results System.out.println(divide); // Output division calculation results } }
Output results:
7 1 20 2
The result of the operation is nothing new. If you replace the above data type with other types of integers, the result will not be unexpected - if you accidentally roll over, click Portal . But if you change to floating-point numbers, you may encounter a surprise - the floating-point number operation in Java is not accurate enough. Go and have a try to see if you can find the colored eggs!
There is one detail to note in the division operation: what if the two numbers divided are not divided completely? Guess what the following line of code will get:
System.out.println(7 / 3); // That is 7 / 3, what is the result, 2.333 Or 2, or 1
Look at the results:
public class Test{ public static void main(String[] args) { System.out.println(7 / 3); } }
The result was 2! Why is that?
Remember this: the division operator (/) obtains the quotient of the division of two data. In the Java language, the result of dividing an integer by an integer is still an integer. If the division is not complete, the remainder will be discarded. That is, the quotient of 7 / 3 is 2 and the remainder is 1, because the divisor and divisor involved in the operation are integers (int type), so the calculation result is still an integer. The remainder is discarded, and the result is 2.
Is there a feeling of sudden enlightenment. This is the first difference between the operation in Java and our previous cognition.
Test 1: arithmetic operators
What is the result of the following code?
public class Test{ public static void main(String[] args) { int int1 = 10; long lon1 = 20; System.out.println(lon1 + int1 * (int1 + lon1) / lon1); } }
A. 30
B. 45
C. 35
D. 300
Answer: C
Analysis: we still follow the rule - "multiply and divide first, then add and subtract, and calculate what is in parentheses first", so the answer is 35
2.2 mold taking, self increasing (+ +) and self decreasing (- -)
I'll teach you three advanced moves (%, + +, --):
public class Test{ public static void main(String[] args) { int num1 = 3; int num2 = 4; int num3 = 5; int num4 = 10; int remainder = num3 % num1; // Modulo / remainder operation, 5-to-3 modulo, the result is? System.out.println(remainder); // Output modulo operation results num2++; // num2 self increasing 1 num4--; // num4 minus 1 System.out.println(num2); // Output the operation result after self increment System.out.println(num4); // Output the operation result after self subtraction } }
Output results:
2 5 9
The percent sign (%) is a modular operation, also known as remainder operation. It is an extension of division operation, but the result of division operation is quotient, and the result of modular operation is remainder. If two numbers are modular operation, the result is 0, what does it mean? Yes, this is the effect of integer division, so modular operation (%) can be used to judge whether two numbers can be divided, that is, the divisor is a multiple of the divisor.
The addition (+ +) and subtraction (- -) operations allow variables to increase or decrease by themselves. Note that these two operators cannot be used directly on constants. For example, the following code is wrong:
1++; // Constant self increment or self decrement is not allowed
Think about it. Why? That's because the concept of constant stipulates that it cannot be modified. Therefore, if you want to get 2, you can directly use literal constant 2 without using another constant for operation. Another detail is that the above code can also put + + and -- in front of the variable, so the operation result is the same (the code before and after the variable cannot exist at the same time, otherwise the data will be operated twice):
Let's try to write + + and -- first
++num2; // num2 self increasing 1 --num4; // num4 minus 1
public class Test{ public static void main(String[] args) { int num1 = 3; int num2 = 4; int num3 = 5; int num4 = 10; int remainder = num3 % num1; // Modulo / remainder operation, 5-to-3 modulo, the result is? System.out.println(remainder); // Output modulo operation results // num2++; // num2 self increasing 1 // num4--; // num4 minus 1 ++num2; // num2 self increasing 1 --num4; // num4 minus 1 System.out.println(num2); // Output the operation result after self increment System.out.println(num4); // Output the operation result after self subtraction } }
The output results do not change:
5 9
Of course, addition (+) and subtraction (- -) can also assign the result to a new variable like other operators, like this:
public class Test{ public static void main(String[] args) { int num1 = 3; int num2 = 4; int num3 = 5; int num4 = 10; int num5 = num2++; // Conjecture: num2 increases by 1, and then assigned to the new variable num5 int num6 = num4--; // Conjecture: num4 subtracts 1, and then assigns a value to the new variable num6 System.out.println(num5); // Output the operation result after self increment System.out.println(num6); // Output the operation result after self subtraction } }
Output results:
4 10
Eh, why is it still the original value? Is there no operation?
It seems that our conjecture is incorrect
int num5 = num2++; // Conclusion: num2 is assigned to the new variable num5 first, and then the self increment operation is carried out int num6 = num4--; // Conclusion: num4 is assigned to the new variable num6 before self subtraction
I'll try adding (+) and subtracting (- -) in front of the variable:
public class Test{ public static void main(String[] args) { int num1 = 3; int num2 = 4; int num3 = 5; int num4 = 10; // int num5 = num2++; // Conclusion: num2 is assigned to the new variable num5 first, and then the self increment operation is carried out // int num6 = num4--; // Conclusion: num4 is assigned to the new variable num6 before self subtraction int num5 = ++num2; // Conjecture: num2 increases by 1, and then assigned to the new variable num5 int num6 = --num4; // Conjecture: num4 subtracts 1, and then assigns a value to the new variable num6 System.out.println(num5); // Output the operation result after self increment System.out.println(num6); // Output the operation result after self subtraction } }
Output results:
5 9
It finally became the right answer, which made me breathe a sigh of relief...
int num5 = ++num2; // Conclusion: num2 increases by 1, and then assigned to the new variable num5 int num6 = --num4; // Conclusion: num4 subtracts from 1, and then assigns a value to the new variable num6
But why? Why do the results of adding (+) and subtracting (- -) before and after the variable are different? Is there any operation on the data? Analyze these two methods:
- Use alone: the result is the same before or after the variable
- Participate in other operations:
Before the variable, increase (decrease) itself first, and then perform other operations
After the variable, other operations are performed with the original value first, and then self increase (self decrease)
Therefore, the first time you put + + and -- after the variable, you assign the original value of the variable to the new variable, The self increasing (or self decreasing) value is discarded, so the original value is printed; the second time + + and -- are placed in front of the variable to assign the calculated value to the new variable, so the calculated data is printed, which is addition (+) and subtraction (--) the underlying principle of these two operators. + + and -- are special operations, which is once again different from our previous cognition.
Let's compare them together:
public class Test{ public static void main(String[] args) { int num1 = 3; int num2 = 4; int num3 = 5; int num4 = 10; int remainder = num3 % num1; // Modulo / remainder operation, 5-to-3 modulo, the result is? System.out.println(remainder); // Output modulo operation results // num2++; // num2 self increasing 1 // num4--; // num4 minus 1 ++num2; // num2 self increasing 1 --num4; // num4 minus 1 System.out.println(num2); // Output the operation result after self increment System.out.println(num4); // Output the operation result after self subtraction // int num5 = num2++; // num2 is assigned to the new variable num5, and then incremented by 1 // int num6 = num4--; // num4 is assigned to the new variable num6, and then minus 1 int num5 = ++num2; // num2 is incremented by 1, and then assigned to the new variable num5 int num6 = --num4; // num4 subtracts 1 from itself, and then assigns a value to the new variable num6 System.out.println(num5); // Output the operation result after self increment System.out.println(num6); // Output the operation result after self subtraction } }
Test 1: modular operation
How to get a three digit ten? For example: 324.
answer:
public class Test{ public static void main(String[] args) { int number = 324; int noGeWei = number / 10; // Divided by 10, quotient 32 (integer divided by integer or integer in Java, the remainder is discarded) int shiWei = noGeWei % 10; // Then take the remainder of 10, quotient 3, and the remainder is 2, that is, ten digits System.out.println("324 The ten digits are:" + shiWei); } }
Test 1: self increasing (+ +) and self decreasing (- -) operations
What is the result of the following code?
public class Test{ public static void main(String[] args) { int a = 5; a++; int b = ++a; System.out.println("a: " + a); System.out.println("b: " + b); } }
A. 5,5
B. 5,6
C. 6,6
D. 6,7
E. 7,6
F. 7,7
Answer: F
Analysis: variable a increases twice, so it is 7
Variable b is assigned after the second self increment of variable a. because plus (+) is in front of the variable (the fourth line of code), b is also 7
The third level of arithmetic operation (Part 2): learn to write and write
3.1 arithmetic operation of character type (char)
The basic operation is too simple. Dare you play some advanced?
A wave of magic operation:
int ch = 'a' + '0'; // The result is?
Don't worry about the results. Can you understand the code above? To understand the above code, you must solve the following two problems:
- Why can character data be used for arithmetic operations?
- How does character data operate?
As we mentioned last time, Character data type (char) represents characters, numbers, special symbols, etc. of all countries and regions in the world. How are these character data stored in the computer? In fact, all data storage and operation in the computer are carried out in binary form. That is, the computer will convert all data into numerical values, and then store the numerical values in binary form On disk, therefore, the operation process is carried out in binary form. Do you want to know the operation process of binary data? Think well, I won't teach. Back to the above question, what you need to know is:
- Each character data is a numerical value in the computer, so it can perform arithmetic operations.
- Since the character data is numeric, take its corresponding numeric value for operation.
So the question is, what is the value corresponding to each character? Xiuyibo operation:
public class Test{ public static void main(String[] args) { System.out.println('a' + 0); // Any value + 0 = value itself System.out.println('0' * 1); // Any value * 1 = value itself } }
The addition and multiplication of arithmetic operators have special skills: any value + 0 = the value itself; Any value * 1 = the value itself. Therefore, the above output result is:
97 48
That is, the values of character literal constants' a 'and' 0 'stored in the computer are 97 and 48, respectively. Therefore, the result of adding these two characters is:
145
This is the arithmetic operation of character type (char). In the final analysis, it is to convert char type characters into int type values for operation.
If you have a table, you can check the common characters and corresponding values at any time!
American information exchange standard code comparison table (ASCII code comparison table, pronounced "as key"), which records the comparison relationship between common characters and corresponding values. Thank you for taking it away:
Too much to remember? It doesn't matter. The values corresponding to the commonly used characters' a '-'z', 'a' -'z 'and' 0 '-'9' are continuous. Just remember the values corresponding to their beginning and end characters:
How old fellow iron, is this service still in place?
So far, there are eight basic data types in the Java language, only boolean types are not involved. Do you think you want to talk about boolean types? No! Because:
In the Java language, boolean types do not participate in arithmetic operations.
Cough.
3.2 data type conversion
Welcome to the portal. I'm a robot, bang bang. What's your indication?
"The code overturned. You taught it. See for yourself:
"
"It's just a compilation error. I'm not afraid!
Let's analyze the error message:
Incompatible types. // Incompatible types Required: byte // byte type required Found: int // An int type was found
It looks like a type mismatch: the program needs a byte type, but it gets an int type. "
"But I don't use int type in my code at all. How is this fat four?"
"Well, byte and short will be converted into int before operation. The operation result is int. that's how the int type comes from."
"What now?"
"Data type conversion is required for the operation result. It is like this:
// Cast type conversion: convert the result of b2 - b1 from int type to byte type byte b3 = (byte)(b2 - b1);
"
This is the cast operation. Convert the result of b2 - b1 from int type to byte type. Because the range of int type is larger than byte type, it is called "forced type conversion" or "explicit type conversion"; Conversely, if you convert from byte type to int type, it is called "automatic type conversion" or "implicit type conversion", because this process occurs by default. For example, the following code is implicit type conversion:
byte x = 3; int y = x; // Assign the variable x of byte type to the variable y of int type, implicit type conversion
Implicit conversion occurs automatically and does not require us to do anything. Among the eight basic data types in the Java language, except that boolean types do not participate in arithmetic operations, the order of automatic conversion of the other seven types is as follows:
The reason for this order is that their respective representation ranges are different. From small to large, they are byte, short, char, int, long, float and double. Small type and large type operate together. Except byte, short and char, which are promoted to int type by default, other cases will automatically promote the small type to large type, and then carry out the operation. The operation result is also a large type. Look at this line of code:
public class Test{ public static void main(String[] args) { System.out.println(7 / 3.0); // In the division operation, the divisor is an integer and the divisor is a floating-point number. What is the result? What data type? } }
Output:
2.3333333333333335
The result is an infinite circular decimal, which is very interesting: first, the result is a floating point number; Second, the result is not 2, which is different from the previous situation; Third, if the last digit of the result is a rounded value, it should be 3 instead of 5. Solve these three problems: first, the number 7 is the int type by default, and 3.0 is the double type. According to the above automatic type conversion diagram, the operation process will convert the int type 7 into the double type, so the result is also the double type; Second, since the operation result is of double type, the divisible part, that is, the value after the decimal point, will not be discarded, so the result is not 2; Third, in the Java language, floating-point numbers participate in the operation, which is likely to cause the loss of accuracy. This is a defect of floating-point operation in the Java language, so the last value of the decimal point is unpredictable.
In addition, cast is not omnipotent, and even unexpected results may occur sometimes. For example, this Code:
public class Test{ public static void main(String[] args) { int first = 131; int second = 1; byte bys = (byte)(first - second); // Operate on two values of type int, and then force the result to the small type byte System.out.println(bys); // Output results } }
Output:
-126
How did this happen? Shouldn't it be 130? It's still a negative number?
That's because byte type can only represent data between - 128 and 127. Data beyond this range can only continue to count from - 128. Therefore, the operation process of converting 130 of int type into byte type is as follows:
127 + 1 = -128 // 130 = 127 + 3 -128 + 1 = -127 -127 + 1 = -126 // The final result is - 126.
The final result is - 126.
The advantages of a variety of different data types are that they can be selected according to the size of memory and calculation. The disadvantages are also obvious. Serious compatibility problems may occur when calculating different types of data. Java is a strongly typed language, which means two things: first, every data must have a very clear type; 2, The compatibility of different types of data must be guaranteed. Operations may be performed between different types of data, and these data have different value ranges and storage methods. Direct operation may cause data loss. Therefore, the conversion can be performed only when large type data can be converted to small type data (without precision loss). You need to know about data type conversion:
The forced type conversion operation is to convert the operation "result" into a small type instead of only converting variables, which is a common error in the operation. Therefore, when performing forced conversion, you must pay attention to the format:
Small type variable name = (small type) large type data;
Refer to complete code:
public class Test{ public static void main(String[] args) { byte b1 = 3; byte b2 = 4; // byte b3 = b2 - b1; // report errors // Cast type conversion: convert the result of b2 - b1 from int type to byte type byte b3 = (byte)(b2 - b1); System.out.println(b3); // Output results /* Implicit conversion */ byte x = 3; int y = x; // Assign the variable x of byte type to the variable y of int type, implicit type conversion /* Multiple data types participate in the operation. What is the result? What data type? */ System.out.println(7 / 3.0); // Division operation, the divisor is an integer, the divisor is a floating-point number, and the result is 2.3335 /* The data is too large for small types to receive */ int first = 131; int second = 1; byte bys = (byte)(first - second); // Operate on two values of type int, and then force the result to the small type byte System.out.println(bys); // Output result: - 126 } }
Test 1: forced type conversion
What is the result of the following code operation?
public class Test{ public static void main(String[] args) { short s1 = 20; short s2 = 30; short s3 = (short)s2 - s1; System.out.println(s3); } }
A. 20
B. 30
C. 10
D. Compilation error
Answer: D
Analysis: the strong conversion operation is only valid for the variable s2, so the result of (short)s2 - s1 is still of type int. it is directly assigned to s3 of type short, and an error is reported during compilation
3.3 operation of plus sign (+)
In addition to being an arithmetic operator, the plus sign (+) also has a vigorous skill, which is frequently used in development, that is, it is used as a string connector:
public class Test{ public static void main(String[] args) { int age = 10; String desc = "My age is"; System.out.println(desc + age); // Use the plus sign directly to connect strings and values } }
Output results:
My age is 10
The plus sign here plays the role of string splicing, so it is now a string connector. In addition to being used between two variables, constants are all inclusive:
public class Test{ public static void main(String[] args) { System.out.println("I am a" + "A small stone."); // Use the plus sign directly to connect the two strings } }
Output results:
I am a small stone.
But the question is, why can the previous arithmetic operation get a numerical result, but here it is a string?
This is the operation of the plus sign (+). The compiler will automatically identify the data types on both sides of the plus sign (+). If any data is of string type, the plus sign (+) is the string connector, otherwise it is the arithmetic operator, which is the root cause.
Test 1: special use of the plus sign (+)
What is the execution result of the following code?
public class Test{ public static void main(String[] args) { int a = 3; int b = 5; char c = '1'; String s = "A"; System.out.println(a - b + c + s + c + b); } }
Answer: 47A15
Resolution:
The first operation: a - b, arithmetic operation, the result is - 2;
The second operation: - 2 + c, arithmetic operation, obtain the ASCII code value 49 of character '1', and the result is 47;
The third operation: 47 + s, string splicing, so it is "47A";
The fourth operation: "47A" + c, string splicing, "47A1";
The fifth operation: "47A1" + b, string splicing, and the final result is 47A15
3.4 summary of arithmetic operation
Summarize arithmetic operators.
/: division operator to obtain the quotient of the division of two data.
Features: the result of dividing an integer by an integer in Java is still an integer.
%: modulo (remainder) operation to obtain the remainder of the division of two data.
Features: it can be used to judge whether two numbers can be divided.
- boolean types do not participate in arithmetic operations.
When there are numeric data on both sides of the plus sign, the addition operation is performed
When character type data such as' a 'and' 0 'participate in the operation, the numerical value represented by the character in the computer shall be used for the operation
- String splicing is performed when either side of the plus sign is a string.
++And --: self increasing 1 / self decreasing 1
Use alone:
The result is the same before or after the variable
- Participate in operation:
Before the variable, increase (decrease) itself first, and then perform other operations
After the variable, other operations are performed with the original value first, and then self increase (self decrease)
- Convert only if and only if large type data can be converted to small type data without precision loss. Pay attention to the fixed format of forced conversion.
The fourth level assignment operation: add a point to the skill
Before learning variables, we may not often use the term "assignment", and, We won't say the equal sign (=) is an assignment symbol. Yes, this word should be a proprietary vocabulary of computers. In the programming language, we call the equal sign (=) an "assignment symbol", which means to assign the data on the right to the variables on the left. The process of assignment is like adding points to skills when playing games. The original skills are not lit and points are added You can use this skill after (being assigned). If the original skill level is too low, you can also upgrade the skill by adding points (assigning a larger value). There are more than one assignment symbols. The most common is to combine the basic assignment operator (=) with the arithmetic operator, so as to obtain some extended operators, such as:
I won't be wordy about the usage of basic assignment operators. Let's see how to play the moves of extended assignment operator.
public class Test{ public static void main(String[] args) { int num = 10; num += 10; // Use + = assignment operator System.out.println(num); // Output the result after operation } }
Output:
20
Obviously, the value of the variable num becomes 20 through the operation of the addition and equal assignment operator (+ =). What's going on?
In fact, it is very simple. The extended assignment operator is equivalent to the combination of arithmetic operator and assignment operator, so these operators have the functions of both arithmetic operator and assignment operator, that is, the effect of the following two lines of code is the same:
// These two lines of code have the same effect num += 10; num = num + 10;
To put it bluntly, the extended assignment operator is nothing more than a short form.
Is that all that good about extending assignment operators? Of course not. Look at another code:
public class Test{ public static void main(String[] args) { short s = 1; // s = s + 1; // report errors s += 1; // Equivalent to s = (short)(s + 1); System.out.println("s:" + s); // s:2 } }
From the previous study, we know that if the constant 1 is directly added to the variable s of short type, it will become int type, so it looks like s = s + 1; Such a code will certainly report an error, but s += 1; However, there is no problem. This shows that the addition assignment operator (+ =) has been cast. This is the advantage of extending the assignment operator: the operation of cast is omitted.
Of course, the characteristics of other extended assignment operators are the same, which will not be repeated here.
The assignment operator is easy to understand. You can practice frequently in the future!
The third level of comparative operation: it's a mule or a horse. Pull it out for a walk
When I was young, I often heard my parents say: you are a brother / sister. You are older than your brothers and sisters. You should let your brothers and sisters. When I was young, I compared my age and size, and then compared my academic performance; When you grow up, you are better than your salary, your boyfriend / girlfriend, and then whose house is bigger and whose car is better; People begin to compare with children in middle age, and compare with their sons and grandchildren when they are old. Alas, in my life, I am more proud than I win, and more frustrated than I lose. It's everywhere. It's really hated and loved.
Comparison operator is also called relational operator. As the name suggests, it is used to compare the size relationship between two values. For example, the following code:
public class Test{ public static void main(String[] args) { System.out.println(5 > 3); // Is it true that 5 is greater than 3 when compared with 3 } }
Output results:
true
Obviously, 5 is greater than 3, so the result is true. On the contrary, if not, the result is false. Therefore, no matter who is big and who is small, who wins and who loses, there are only two comparison results: true and false. In other words, the operation results of comparison / relational operators are boolean, either true or false. Common relational operators:
Compare the size relationship between the two data in Java, When using the comparison operator (or relational operator), note that the double equal sign (= =) is used to compare whether the two data are equal, because in Java, an equal sign (=) means "assignment"; and the "not equal" symbol is an exclamation mark plus an equal sign (! =). Be sure to pay attention to their writing. Take a look at a piece of code:
public class Test{ public static void main(String[] args) { // Define three variables int a = 10; int b = 20; int c = 10; // ==: equal to System.out.println(a == b); // false System.out.println(a == c); // true System.out.println("-----------------------------"); // !=: Not equal to System.out.println(a != b); // true System.out.println(a != c); // false System.out.println("-----------------------------"); // >: greater than System.out.println(a > b); // false System.out.println(a > c); // false System.out.println("-----------------------------"); // >=: greater than or equal to System.out.println(a >= b); // false System.out.println(a >= c); // true System.out.println("-----------------------------"); } }
Comparison operators are as easy to understand as assignment operations. The only noteworthy point is the difference between double equal sign (= =) and single equal sign (=):
public class Test{ public static void main(String[] args) { // Define three variables int a = 10; int b = 20; int c = 10; //Note: = = is to judge whether it is equal, and = = means assignment System.out.println(a == b); //Judge whether the values of variable a and variable b are equal, false System.out.println(a = b); //Assign the value of variable b to variable a, and then print the result, 20 } }
Double equal sign means to compare equality, and single equal sign means to assign value. Remember.
Fourth, logical operation: there must be a statement about who is right and who is wrong
When we mention "logical operation", we often think of complex operation process. In fact, it is not. The logical operation introduced now is very simple: it is used to judge the logical relationships such as "and", "or" and "unless". Compared with the comparison operators introduced earlier, both logical operation and comparison operation seem to need judgment, so their operation result types are the same: boolean type. The more complex point of logical operation compared with comparison operation is that logical operation compares the logic between multiple results, while comparison operation generally only needs to compare one result between two data. It's a little windy. Take a chestnut:
public class Test{ public static void main(String[] args) { int a = 10, b = 20, c = 30; // Declare three variables System.out.println(a > b); // Comparison operation, comparing the size of two data, there is only one result System.out.println(a > b && b > c); // Logical operation, two comparison results participate in logical and (& &) operation } }
Output:
false false
Both outputs are false. In other words, the results of comparison operation and logical operation are of boolean type, but the two ends of logical operator are generally connected with Boolean relational expressions, while the two ends of comparison operation are connected with data. Common logical operators:
The above code uses the logical operator: & & (logical and, and). It means that when the expression results on both sides are true at the same time, the result of the logical operation is true. Conversely, as long as the result on either side is false, the result of the whole logical operation is false. Accordingly, logical or The meaning of (|) is: as long as either side is true, the result of logical operation is true. Logical non (!) means negative. Its meaning is: if the original result is true, add! The result is false. On the contrary, if the original result is false, add! The result is true.
Trinket likes to marry a daughter-in-law. He has three requirements: first, it is a woman; Second, be good-looking; Third, be in good shape. Here's a code:
public class Test{ public static void main(String[] args) { /* Case: Trinket looking for his daughter-in-law There are three requirements: First, women; Second, be good-looking; Third, be in good shape. */ int sex = -1; // Gender- 1-female, 1-male int rongMao = 1; // Looks. 0 - not good-looking, > 0 good-looking int shenCai = 0; // Figure. 0 - bad figure, 1 - good figure // At the beginning, I had a high vision. I was required to look good and have a good figure System.out.println(sex == -1); // Gender is female System.out.println(rongMao > 0 && shenCai == 1); // Good looks and good figure System.out.println("---------------------"); // Trinket found that such a daughter-in-law was hard to find, so he lowered the criteria for choosing a spouse, as long as he looked good or had a good figure System.out.println(sex == -1); // Gender is female System.out.println(rongMao > 0 || shenCai == 1); System.out.println("---------------------"); // Trinket found it difficult to find such a daughter-in-law, so he lowered the criteria for choosing a spouse, as long as it was not a man System.out.println(sex != 1); // Gender is not male System.out.println("---------------------"); } }
Output results:
true false --------------------- true true --------------------- true ---------------------
It's not easy to find a daughter-in-law. It's OK and cherish it.
Let's talk about the use of logical non (!). It means negative. If the original value is false, plus! Becomes true, that is, double negative means positive. When multiple logical non (!) appear in the code at the same time, you can directly remove the even number of logical non (!) because the result will not change:
public class Test{ public static void main(String[] args) { System.out.println(!!!!!!true); // 6 logical non, the result is true } }
Output:
true
Logic and (& &) and logic or (|) have twin brothers respectively. They are also logic and logic or, but they look bony and malnourished:
Logic and:&
Logical or:|
you 're right, We usually call these logical operators: double and (& &) and single and (&); double or (|) and single or (|). Although the twin brothers look thin, their functions have not shrunk. They (single and, or) still have the same logical processing functions as their brothers, but the difference is that both double and (& &) and double or (|) have "short circuit" The thin brothers did not:
public class Test{ public static void main(String[] args) { int a = 3, b = 5, c = 4; int d = 0; System.out.println(a > b && (d = b) > c); // Use double and for logical operation. The first condition is not true, and whether the second condition is executed System.out.println(d); // What is the value of d, 0 or 5? } }
If the first condition a > b is not true when double and is used for logical operation, will the second condition be executed? Is the variable D successfully assigned to the value of B?, Looking at the operation result, we know that the action of assigning value to variable D (d = b) is not successful, which means that when the condition in front of double and (& &) is not tenable (the result is false), the subsequent code will no longer be executed, which is the so-called "short circuit" effect. What about single and (&):
public class Test{ public static void main(String[] args) { int a = 3, b = 5, c = 4; int d = 0; System.out.println(a > b & (d = b) > c); // If a single and is used for logical operation, the first condition does not hold, and whether the second condition is executed System.out.println(d); // What is the value of d, 0 or 5? } }
Output results:
false 5
Obviously, single and (&) have no "short circuit" effect.
The execution logic of double or (|) is similar: if the previous condition result is true, it means that the whole logical expression must be true and all subsequent codes will not be executed; on the contrary, if the previous condition is false, judgment will still be made later, but single or (|) has no such effect. Let's look at the effect of double or (|):
public class Test{ public static void main(String[] args) { int a = 3, b = 5, c = 4; int d = 0; System.out.println(b > a || (d = b) > c); // Use double or for logical operation. The first condition is true and the second condition is executed System.out.println(d); // What is the value of d, 0 or 5? } }
Output:
true 0
Change to single or (|):
public class Test{ public static void main(String[] args) { int a = 3, b = 5, c = 4; int d = 0; System.out.println(b > a | (d = b) > c); // Use double or for logical operation. The first condition is true and the second condition is executed System.out.println(d); // What is the value of d, 0 or 5? } }
Output:
true 5
Generally speaking, the logical judgment ability of double and (& &) and single and (&) is the same, except that double and (& &) have the effect of short circuit, while single and (&) do not; the reason of double or (|) and single or (|) is the same.
Test 1: logical operators
What is the output of the following code?
public class Test{ public static void main(String[] args) { int x, y = 0, z = 1; boolean r1 = (x = 0) > y & (z = y) == 1; boolean r2 = y < z || (x = 2) > (z = z +1); System.out.println(r1 && r2); System.out.println(x); System.out.println(y); System.out.println(z); } }
A. true; x=0; y=0; z=0
B. true; x=2; y=0; z=1
C. false; x=2; y=0; z=1
D. false; x=0; y=0; z=2
Answer: C
Resolution:
Result of r1:
(x = 0) is the assignment action. At this time, x = y = 0, so the result of (x = 0) > y is false;
(z = y) is also an assignment action, which is z = y = 0, so the result of (z = y) == 1 is also false;
The logical order and (&) are executed on both sides, so the final result is: x = y = z = 0;
r1 is false & false, and the result is false;
Result of r2:
The result of Y < Z is false;
(x = 2) and (z = z + 1) are both assignment actions, so at this time, the expression result on the right of x = 2, z = 1, double or (|) is true;
r2 is: false | true, and the result is true
The final output: R1 & & R2 is equivalent to false & & true, and the result is false; x = 2, y = 0, z = 1
The fifth level of three eye operation: the ultimate answer to selection difficulties
What should you do when you face a dilemma? Now I'll teach you the ultimate answer: binocular operation.
Ternary operation, also known as ternary operation, is composed of three parts. The format is as follows:
Relational expression? Result 1: result 2
The ternary operator is separated by two special symbols, question mark (?) and colon (:):
Part one: relational expression, which represents the problem you are facing now
Part II: result 1, the first possible result, represents the first choice you face
Part III: result 2, the second possible result, represents the second choice you face
Things are changeable. Instead of being in a panic when facing choices, it's better to give the right of choice to the previous conditions. If the conditions are met, choose the first result, and if not, choose the second result. This is to respond to changes with constancy. Therefore, the execution process of the ternary operator is as follows:
If the result of the relational expression is true, the result after the operation is result 1
If the result of the relationship expression is false, the result after operation is result 2
For example, find the larger of two integers:
public class Test{ public static void main(String[] args) { // Define two integer variables int a = 100; int b = 20; int max = (a >= b) ? a : b ; // Calculate their larger values through ternary operators System.out.println("max: " + max); // Print results to console } }
The meaning of the code in the third line above is: when the condition of a > = b is true, the larger value is a, otherwise it is b. Obviously, the final output is the value of variable a:
100
What if there are three data? Very simply, the ternary operator can be nested:
public class Test{ public static void main(String[] args) { // Define two integer variables int a = 100; int b = 20; int c = 50; int max = (a >= b) ? (a > c ? a : c) : (b > c ? b : c) ; // Calculate their maximum value through the ternary operator System.out.println("max: " + max); // Print the maximum results to the console } }
The maximum is still 100:
100
Although the ternary operators can be nested, the readability of the code is obviously poor, so it is not recommended in development. You can take them apart and find the maximum step by step.
Test 1: three item operator
What is the result of the following code?
public class Test{ public static void main(String[] args) { int a = 3, b = 5; int c; int result = (c = b) > a ? c - a : c + a; System.out.println(result); } }
A. 2
B. 5
C. 8
D. Compilation error
Answer: A
Resolution:
(c = b) is the assignment operation, which is equivalent to b > A, and the result is true; At this time, a = 3, b = 5, c = 5;
Since the result to the left of the question mark (?) of the ternary operator is true, the result is c - a, that is, 2. c + a is not executed.
summary
Now, let's summarize the assignment operator, comparison operator, logical operator and ternary operator:
Assignment operator:
1. Common assignment operators: =, + =, * =, - =, / =,%=
2. Benefits of extending assignment operators: automatic strong conversion
3. be careful:
= indicates assignment operation, not equal
= = used to indicate equality
Comparison / relational operators:
1. Relational operators are used to describe whether the sizes of two variables are equal
2. Common relational operators: >, <, = =,! =, > =<=
3. Note: the difference between relational operator = = and assignment operator =
Logical operators:
1. Operators used to judge logical relationships such as "and", "or" and "unless"
2. A relational expression that connects two ends of a logical operator, or a logical expression
3. The operation result of logical operator is Boolean: true or false
4. Double and double or both have short circuit effect, single and single or none
5. Even logical non! The result remains unchanged
Ternary / ternary operator:
1. Format: relational expression? Result 1: result 2;
2. Execution process:
The result of relational expression is true, and the result of ternary operator is "result 1";
The result of relational expression is false, and the result of ternary operator is "result 2";
So many operators, what is their priority order?
A doggerel, please practice it well~~~
Monocular multiplication and division is the relationship, and logic is assigned after three items.
Monocular: monocular operator + – (negative number) + + -- etc
Multiplication and division: arithmetic unary operator * /% +-
Is: displacement monocular operator < < > (not mentioned at the moment)
Relation: relation unary operator > < > = < = = ==
Logic: logical unary operators & & | & |^
Ternary: ternary monocular operator a > b? X : Y
After: meaningless, just to make up the number of words
Assignment: assignment=