Ternary operator in Java

output is small number

The ternary operator is a simple conditional branching statement. It returns a value based on condition.

int num = 54;
String str = num > 100 ? "big number" : "small number";

num > 100 ? is our condition.

"big number" the first value(before :) will be returned if a condition is true.

"small number" the second value(after :) will be returned if a condition is false. In our case, this value is returned because the condition is false.

Turnery operator can be used with any other data types as well.

public class Main {
public static void main(String[] args) {
boolean b = false;
int num = b ? 7 : 9;
System.out.println(num); // 9
}
}
public class Main {
public static void main(String[] args) {
double score = 75.0;
char grade = score >= 50&& score <= 100 ? 'A' : 'F';
System.out.println(grade); // A
}
}
public class Main {
public static void main(String[] args) {
int num = 1 > 2 ? 7 : 9 > 3 ? 0 : 3;
System.out.println(num); // 0
}
}

--

--

--

Software Developer, Java Instructor https://www.techleadacademy.io/

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

CS371p Fall 2021 blog 9: Zein Fakhreddine

Increase or Decrease the Size of Static Partition in Linux

Android runtime permission with lower version compatibility

Rust — Modules and Project Structure

Robinhood Portfolio — A view via Tableau

Nebulas Data Center API documentation released

Rant(Ep:02): Message to all bloggers who teach!

OpenTelemetry and Epsagon — a Love Story in Three Acts

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Beknazar

Beknazar

Software Developer, Java Instructor https://www.techleadacademy.io/

More from Medium

ArrayList or LinkedList? Choose correct one

Constructors in Java

Introduction to Sealed Classes

Pyramid Pattern of Numbers code in java