# Use Ternary Operator

# Description

This rule replaces if-statements by equivalent constructs using the ternary operator in cases where such a replacement is reasonable. For example, the statement 'x = condition ? 1 : 0;' is shorter and better readable than the equivalent construct using an if-statement.

# Benefits

Code can be made shorter.

# Tags

# Code Changes

# Transforming To Initializer With Ternary Expression

Pre

	int x;
	if (condition) {
		x = 1;
	} else {
		x = 0;
	}

Post

	int x = condition ? 1 : 0;

# Transforming To Assignment With Ternary Expression

Pre

	int x;
	System.out.println();
	if (condition) {
		x = 1;
	} else {
		x = 0;
	}

Post

	int x;
	System.out.println();
	x = condition ? 1 : 0;	

# Transforming To Return Of Ternary Expression

Pre

	if (condition) {
		return 1;
	} else {
		return 0;
	}

Post

	return condition ? 1 : 0;

# Return Immediately After If

Pre

	if (condition) {
		return 1;
	}
	return 0;

Post

	return condition ? 1 : 0;

🛠️ Auto-refactor Available

You can auto refactor this with jSparrow.
Drop this button to your Eclipse IDE workspace to install jSparrow for free:

Drag to your running Eclipse* workspace. *Requires Eclipse Marketplace Client

Need help? Check out our installation guide.

# Properties

Property Value
Rule ID UseTernaryOperator
First seen in jSparrow version 4.18.0
Minimum Java version 1.1
Remediation cost 5 min