In this example we will learn to use ternary operator in java with example
- Ternary Operator will be used instead of if else
- We can use this ternary operator to do null check
- we can use this to check numeric operations
Syntax
(conditon) ? true : false ;
Example with String
public class TernaryOperatorExample {
public static void main(String[] args) {
String s = null;
System.out.println((s == null) ? "String s is null" : "String s is not null");
}
}
Output
String s is not null
Example with numeric operations
public class TernaryOperatorWithNumeric {
public static void main(String[] args) {
int i = 10;
System.out.println((i > 10) ? true : false);
}
}
Output
false