Operators in Java
-
Concept: operators are symbols that tell programs to perform specific operations.
-
Java provides six types of operators, namely assignment operator, arithmetic operator, relational operator, logical operator, bit operator and conditional operator.
-
Learning objective: to realize the simulated lucky draw, the key steps are as follows:
- Get the membership card number entered by the keyboard.
- Store the membership card number in a variable.
- Use the operator to decompose the membership card number to obtain the numbers on each member.
- Add the decomposed numbers to judge whether they win the prize.
1, Assignment operator
-
Assignment operator = used to assign variable value to variable, and can be combined with arithmetic operator to form compound assignment operation.
-
Composite assignment operators mainly include + =, - =, * =, / =,% =.
-
Example:
int a = 10; int b = 20; a = a + b;// It can be replaced by a += b;
Analysis: it is recommended to use the compound assignment operator to assign a = a + b; Replace with a += b; It is convenient for program compilation and processing and has better performance.
2, Arithmetic operator
-
Arithmetic operators include +, -, *, /,%, + +, --. As follows:
operator meaning example result + Addition operator 5+3 8 - Subtraction operator 5-3 2 * Multiplication operator 5*3 15 / division operator 5/3 1 % Modulo (remainder) operator 5%3 2 ++ increment operator i=2;j=i++; i=3;j=2; -- decrement operator i=2;j=i--; i=1;j=2; -
be careful:
- Division operator: if both operands are integers and the result is an integer, the decimal part will be discarded; If one of the two operands is a floating-point number, automatic type conversion will be performed, and the result is also a floating-point number, keeping the decimal part.
- For modulo operators, if both operations are integers, the result is also an integer; If one of the two operands is a floating point number, the result is also a floating point number, and the decimal part is retained.
- The self increasing operator can only be used in i + + and + + i. their similarities are that they are equivalent to i = i + 1;, The difference is that i + + performs the expression operation first and then adds one, while + + i performs the expression operation again and again.
-
Example: use the / and% operators to obtain the numbers on the membership card and get the sum of the decomposed numbers.
Implementation steps:
- 4-digit membership card number and 10 can be calculated to obtain single digits.
- Divide the 4-digit membership card number by 10 and add 10 to get ten digits.
- Divide the 4-digit membership card number by 100 and add 10 to get a hundred digits.
- Divide the 4-digit membership card number by 1000 to get thousands of digits.
- Calculate the sum of you.
import java.util.Scanner; public class PB_Lucky { public static void main(String[] args) { Scanner input = new Scanner(System.in);// System.in stands for keyboard System.out.println("Please enter a 4-digit membership card number:"); int cardId = input.nextInt();// Get an integer input from the keyboard and assign it to the cardId variable // Use the "/" and '% "operators to obtain each number int gewei = cardId % 10; // Get bits by decomposition int shiwei = cardId / 10 % 10; // Decompose to get ten digits int baiwei = cardId / 100 % 10; // Decompose to get hundreds int qianwei = cardId / 1000; // Decomposition to obtain thousands System.out.println("******************************************"); // Use the + operator to calculate the sum of numbers int sum = gewei + shiwei + baiwei + qianwei; System.out.println("Membership card No.:" + cardId); System.out.println("thousands : " + qianwei); System.out.println("Hundreds : " + baiwei); System.out.println("Ten digits : " + shiwei); System.out.println("Single digit : " + gewei); System.out.println("Sum of you:" + sum); } }
Output results:
Please enter a 4-digit membership card number: 1437 ****************************************** Membership card No.: 1437 thousands : 1 Hundreds : 4 Ten digits : 3 Single digit : 7 Sum of you: 15
3, Relational operator
-
Relational operators, sometimes called comparison operators, are used to compare the size of two variables or constants.
-
The result of the operation is Boolean, true or false.
-
There are six relational operators in Java, namely: = =,! =, >, <, > =, < =. As follows:
operator meaning example result == be equal to 5==6 false != Not equal to 5!=6 true > greater than 5>6 false < less than 5<6 true >= Greater than or equal to 5>=6 false <= Less than or equal to 5<=6 true -
be careful:
- =Is the assignment operator and = = is the equals operator.
- >, <, > =, < = only numeric comparison is supported.
- ==,!= It supports the comparison of all data types, including numeric type, boolean type and reference type.
- The result of a relational expression is a Boolean value.
- >, <, > =, < = priority is higher than = =,! =.
-
Example: judge whether the user wins the prize according to the sum of the numbers on the membership card.
import java.util.Scanner; public class PB_Lucky { public static void main(String[] args) { Scanner input = new Scanner(System.in);// System.in stands for keyboard System.out.println("Please enter a 4-digit membership card number:"); int cardId = input.nextInt();// Get an integer input from the keyboard and assign it to the cardId variable // Use the "/" and '% "operators to obtain each number int gewei = cardId % 10; // Get bits by decomposition int shiwei = cardId / 10 % 10; // Get bits by decomposition int baiwei = cardId / 100 % 10; // Get bits by decomposition int qianwei = cardId / 1000; // Get bits by decomposition System.out.println("******************************************"); // Use the + operator to calculate the sum of numbers int sum = gewei + shiwei + baiwei + qianwei; System.out.println("Membership card No.:" + cardId); System.out.println("thousands : " + qianwei); System.out.println("Hundreds : " + baiwei); System.out.println("Ten digits : " + shiwei); System.out.println("Single digit : " + gewei); System.out.println("Sum of you:" + sum); // Judge whether to win the prize if (sum > 20) { System.out.println("Membership card number is" + cardId + "Member, you won the prize!"); } else { System.out.println("Membership card number is" + cardId + "You didn't win the prize."); } } }
Output results:
Please enter a 4-digit membership card number: 1234 ****************************************** Membership card No.: 1234 thousands : 1 Hundreds : 2 Ten digits : 3 Single digit : 4 Sum of you: 10 Member with membership card number 1234, you did not win the prize. -------------------------------------------------------------------------------------- Please enter a 4-digit membership card number: 7896 ****************************************** Membership card No.: 7896 thousands : 7 Hundreds : 8 Ten digits : 9 Single digit : 6 Sum of you: 30 Member with membership card No. 7896, you have won the prize!
If else type statements are called selection structures, which will be learned in later courses. Here, you can simply understand them.
4, Logical operator
-
Logical operators are used to operate on two Boolean operands. The result is also a Boolean. The logical operators are as follows:
operator meaning Operation rules & Logic and The result is true only if both operands are true | Logical or One of the two operands is true, and the result is true ^ Logical XOR The two operands are the same, and the result is false; The two operands are different and the result is true ! Logical inverse (logical non) The operand is true and the result is false; The operand is false and the result is true && Short circuit and The operation rules are the same as "&", but short circuit || Short circuit or The operation rules are the same as "|", but short circuit -
be careful:
- The operand type can only be Boolean, and the result of the operation is also Boolean.
- Priority level:! > & > ^ > | > & & > |.
- &The difference between & & and & & is that when the left side of & & is false, the expression on the right side will not be performed, that is, if the left side is false, it will be false; In any case, the expressions on & both sides will participate in the calculation.
- |The difference between and is similar to that between & and &.
5, Bitwise operator
-
Bit operators and operation rules are as follows:
operator meaning Operation rules & Bitwise AND Both operands are 1 and the result is 1 | Bitwise OR One of the two operands is 1 and the result is 1 ^ Bitwise XOR The two operands are the same, and the result is 0; The two operands are different and the result is 1 ~ Comfort non / negative The operand is 1 and the result is 0; The operand is 0 and the result is 1 << Shift left Fill 0 in the right space >> Shift right The left space is filled with the highest bit, that is, the sign bit >>> unsigned right shift Fill 0 in the left space -
Example:
public class Test { public static void main(String[] args) { /* Calculation 5 & 6 Convert to binary: 5=0000 0101 6=0000 0110 5&6 = 0000 0100 Convert decimal to 4 */ System.out.println("5&6=" + (5 & 6));// 4 /* Calculation 7|8 Convert to binary: 7=0000 0111 8=0000 1000 7|8 = 0000 1111 Convert decimal to 15 */ System.out.println("7|8=" + (7 | 8));// 15 /* Calculation 3 < < 3 Convert to binary: 3=0000 0011 3<<3 = 0001 1000 Convert decimal to 24 */ System.out.println("3<<3=" + (3 << 3));// 24 /* Calculation 16 > > 3 Convert to binary: 16=0001 0000 16>>3 = 0000 0010 Convert decimal to 2 */ System.out.println("16>>3=" + (16 >> 3));// 2 } }
-
Tips:
- Every time an integer moves one bit to the left, its value is doubled. Provided that the number of shifted digits does not contain significant digits.
- Every time an integer moves one bit to the right, its value is reduced by 1 / 2, provided that the overflow bits do not contain significant digits
- a=a*4, a = a < < 2 have the same effect and result, but using bitwise operators has faster speed.
- Bit operators operate on the number of operations in binary units.
- The operands of bit operations are integers, including int, short, long, byte and char.
- The result of bit operation is also an integer number, including int and long.
- If the operand is char, byte or short, its value will be automatically promoted to int before bit operation, and the operation result will also be int.
6, Conditional operator
-
Conditional operator is the only operator in Java that requires three operands, so it is also called ternary operator or ternary operator.
-
Syntax of conditional operators:
Conditions? Expression 1: expression 2
-
In Syntax:
-
First, judge the condition. If the result is true, return the value of expression 1. If the condition is false, return the value of expression 2.
-
If the condition result is false, the value of expression 2 is returned.
-
-
Example:
import java.util.Scanner; public class Test { public static void main(String[] args) { Scanner input = new Scanner(System.in); int score = input.nextInt();// Get keyboard input int // Three item operator to judge whether it is qualified or not String result = score >= 60 ? "pass" : "fail,"; // Output results System.out.println("achievement" + result); } }
Tip: the function of conditional expression is similar to if else selection structure, and can be transformed into if else statement.
Priority and Associativity
-
Various operators in Java have their own priority and associativity. The so-called priority is the operation order in the expression operation. The higher the priority, the higher the operation order in the expression.
-
Associativity can be understood as the direction of operation. Most operators operate from left to right, that is, from left to right.
-
The priorities of various operators are as follows. The priority ratio decreases from top to bottom.
priority operator Associativity 1 (),[] From left to right 2 !,~,++,-- Right to left 3 *,/,% From left to right 4 +,- From left to right 5 <<,>>,>>> From left to right 6 <,<=,>,>=,instanceof From left to right 7 ==,!= From left to right 8 & From left to right 9 ^ From left to right 10 | From left to right 11 && From left to right 12 || From left to right 13 ?: Right to left 14 =,+=,-=,*=,/=,%=,&=,|=,^=,~=,<<=,>>=,>>>= Right to left -
Tips:
- The assignment operator with the lowest priority is followed by the conditional operator.
- Unary operators include!, ~, + +, --, High priority.
- You can control the operation order of expressions through (), () has the highest priority.
- Overall, the order of precedence is: arithmetic operators > relational operators > logical operators.
- There are only assignment operators, ternary operators and unary operators (one operand) from right to left.