Home > Java > JavaBase > body text

The operation principle of ternary operator in java

王林
Release: 2019-11-25 15:42:51
forward
3023 people have browsed it

The operation principle of ternary operator in java

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);
	}

}
Copy after login

Operation results:

The operation principle of ternary operator in java

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!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template