The article directories

  • Ternary operator
    • 1. Basic grammar
    • 2. Example of TernaryOperator.java
    • 3. Details on the use of ternary operators
    • 4. Class exercises

Ternary operator

1. Basic grammar

  • Conditional expression? Expression 1: expression 2;
  • Operation rules:
  1. If the conditional expression is true, the result of the operation is expression 1;
  2. If the conditional expression is false, the result is expression 2.

    Formula:[Master Of One Lamp: Master of One Zhen]

2. Example of TernaryOperator.java

  • Analysis:bIt’s assigned and then subtracted, soresult = 99; And then b subtracts198
	int a = 10;
	int b = 99;
	/ / read
	// 1. A > b is false
	// 2. Return b--, first return the value of b, then return b-1
	// 3. The result is 99
	int result = a > b ? a++ : b--;
	System.out.println("result=" + result);
	System.out.println("a=" + a); 
	System.out.println("b=" + b);
Copy the code

  • If I put the top oneb--Instead of--b, is subtracting first and then assigning.result = 98bThat’s 98

3. Details on the use of ternary operators

  • TernaryOperatorDetail.java
  1. Expressions 1 and 2 must be types that can be assigned to the receiving variable (or can be converted automatically)
	// Expressions 1 and 2 must be types that can be assigned to receiving variables
	//(or can automatically convert/or cast)
	int a = 3;
	int b = 8;
	int c = a > b ? (int)1.1 : (int)3.4;/ / can
	double d = a > b ? a : b + 3;Int -> double
Copy the code
  1. The ternary operator can be converted toif--elsestatements
	int res = a > b ? a++ : --b;
	if ( a > b ) res = a++;
	else res = --b;
Copy the code

4. Class exercises

  • Example: Maximizing three numbers.
	// Example: Implement the maximum of three numbers
	int n1 = 553;
	int n2 = 33;
	int n3 = 123;
	/ / way of thinking
	//1. Get the largest number in n1 and n2 and save to max1
	//2. Then find the largest number in max1 and n3 and save to max2
	
	int max1 = n1 > n2 ? n1 : n2;
	int max2 = max1 > n3 ? max1 : n3;
	System.out.println("Maximum number =" + max2);
Copy the code

  • Implemented in a single statement, the above approach is recommended. The following is the substitution of max1 above, the result is the same
int max = (n1 > n2 ? n1 : n2) > n3 ? 
 		  (n1 > n2 ? n1 : n2) : n3;
 System.out.println("Maximum number =" + max);	 
Copy the code