Format: Data type variable name = Boolean type expression? Result 1: Result 2
Operation principle:
The result of the Boolean type expression is true, and the overall result of the ternary operator is result 1, which is assigned to the variable.
The result of the Boolean expression is false, and the overall result of the ternary operator is result 2, which is assigned to the variable.
Recommended related video tutorials: java learning
Examples are as follows:
package test; public class Test { public static void main(String[] args) { // 方式一 Object o1 = true ? new Integer(1) : new Double(2.0); // 方式二 Object o2; if (true) o2 = new Integer(1); else o2 = new Double(2.0); System.out.println(o1); System.out.println(o2); // 方式三 Integer i = new Integer(1); if (i.equals(1)) i = null; Double d = new Double(2.0); Object o3 = true ? i : d; // 空指针异常 System.out.println(o3); } }
Operation results:
In my impression, the first and second methods should be equivalent, but the results obtained are different. It can be seen that the ternary operator will promote the type of the operand when necessary. Note: Only when needed, otherwise a null pointer exception will be thrown.
More related article recommendations:Introduction to java programming
The above is the detailed content of The operation principle of ternary operator in java. For more information, please follow other related articles on the PHP Chinese website!