Java Ternary Operator examples
This example shows you how to write Java ternary operator. Here’s the syntax
condition ? get_this_if_true : get_this_if_false
Java ternary operator syntax
(n > 18) ? true : false;
(n == true) ? 1 : 0;
(n == null) ? n.getValue() : 0;
1. Java ternary operator
1.1 Java example without ternary operator.
JavaExample1.java
package com.mkyong.test;
public class JavaExample1 {
public static void main(String[] args) {
int age = 10;
String result = "";
if (age > 18) {
result = "Yes, you can vote!";
} else {
result = "No, you can't vote!";
}
System.out.println(result);
}
}
Output
No, you can't vote!
1.2 With ternary operator, code can be simplified like this:
JavaExample1_2.java
package com.mkyong.test;
public class JavaExample1_2 {
public static void main(String[] args) {
int age = 10;
String result = (age > 18) ? "Yes, you can vote!" : "No, you can't vote!";
System.out.println(result);
}
}
Output
No, you can't vote!
In short, It improves code readability.
2. Null Check
It’s common to use the ternary operator as null check.
JavaExample2.java
package com.mkyong.test;
import com.mkyong.customer.model.Customer;
public class JavaExample2 {
public static void main(String[] args) {
Customer obj = null;
int age = obj != null ? obj.getAge() : 0;
System.out.println(age);
}
}
Output
0
References
About Author
Comments
Subscribe
0 Comments