Ternary

Ternary conditional operator is simply a short hand way of writing simple conditionals. Its benefit is its simplicity and reduce the lines of code in your application. It's best used when a conditional is between two choices. Otherwise, it might be better to consider using else if or switch statements instead. The examples below will test to see if variable carCount is greater than 2 and will return yes if true and no if false. Finally, some languages such as Go, Kotlin and Matlab do not have ternary expression and instead must use if/else statements.

Select Languages

Examples

C

int carCount = 3;

char* result = (carCount > 2) ? "Yes" : "No";
printf("%s", result);

C#

int carCount = 3;

string result = (carCount > 2) ? "Yes" : "No";
Console.WriteLine(result);

C++

int carCount = 3;

string result = (carCount > 2) ? "Yes" : "No";
cout << result;

Go

// No Native Support or Implementation

Java

int carCount = 3;

String result = (carCount > 2) ? "Yes" : "No";
System.out.println(result);

JavaScript

const carCount = 3;

const result = (carCount > 2) ? "Yes" : "No";
console.log(result);

Kotlin

val carCount = 3;

val result = if (carCount > 2) "Yes" else "No";
println(result);

MatLab

// No Native Support or Implementation

PHP

$carCount = 3;

$result = $carCount > 2 ? "Yes" : "No";
echo $result;

Python

carCount = 3

result = "Yes" if carCount > 2 else "No"
print(result)

R

carCount <- 3

result = if(carCount > 2) "Yes" else "No"
print(result)

Ruby

carCount = 3
result = carCount > 2 ? "Yes" : "No"
puts result

Rust

let carCount = 3;

let result = if carCount  > 2 { "Yes" } else { "No" };
println!("{}", result);

Scala

val carCount = 3;

val result = if (carCount > 2) "Yes" else "No";
println(result);

Swift

let carCount = 3

let result = (carCount > 2) ? "Yes" : "No";
print(result);

TypeScript

const carCount:number = 3;

const result:string = 
  (carCount > 2) ? "Yes" : "No";
console.log(result);

Copyright 2025. All Rights Reserved. IronCodeMan.