Java Ternary Operator Sample Code

The Ternary Operator is sometimes called the Conditional Operator or known by the symbols ? :, which is essentially a very short version of the if-else statement. The term Ternary just means composed of three operands or parts (condition, valueA, valueB)

Looking at the expression below, you see the three parts. The condition can be anything that results in either TRUE or FALSE. The two values can also be any value or operation that results in something. The variable result below could literally be any data type.

result = if(condition) ? valueA : valueB

If condition is TRUE, set result to valueA.

If condition is FALSE, set result to valueB.

Java Ternary Operator Source Code

package com.jcd.java.tutorials;

public class JavaTernaryOperator 
{

	public static void main(String[] args) 
	{
		int result;
		int valueA = 100;
		int valueB = 200;
		boolean condition;
		
		//Let's set condition to TRUE
		condition = true;
		
		result = (condition) ? valueA : valueB;
		 
		System.out.println("Condition = TRUE | Result = "+result);
		
		
		//Let's set condition to FALSE
		condition = false;
				
		result = (condition) ? valueA : valueB;
				
		System.out.println("Condition = FALSE | Result = "+result);
		
		System.out.println("\n------------------------------------------\n");
		
		String greeting;
		String valueA1 = "Hello";
		String valueB1 = "Hola";
		String language = "English";
		
		greeting = (language.equals("English")) ? valueA1 : valueB1;
		
		System.out.println("Language = English | Greeting = "+greeting);
		
		//Let's change language to Spanish
		language = "Spanish";
		
		greeting = (language.equals("English")) ? valueA1 : valueB1;
		
		System.out.println("Language != English | Greeting = "+greeting);

	}

}


Java Ternary Operator Output

Condition = TRUE | Result = 100
Condition = FALSE | Result = 200

------------------------------------------

Language = English | Greeting = Hello
Language != English | Greeting = Hola


I like the Ternary Operator because you pack a lot of conditional code and evaluation into a single line of code. I guess one could argue either way which is more readable or best coding practice between a if-then-else and the ternary operator.



Java References:

Add a Comment

Your email address will not be published. Required fields are marked *