- Ternary operator also known as conditional operator in java.
- Ternary operator used to evaluate boolean expression and it consists of three operands.
Ternary operator in java syntax:
- variable x = (expression) ? value if true : value if false
- Value of x will be decided based on the condition. if condition is true then it assigns first value to the variable
- If Expression is false then it assigns second value to the variable.
Java simple example program on ternary operator / conditional operator in java
- package operatorsinjava;
- public class TernaryOperator {
- /**
- * @ www.instanceofjava.com
- *
- */
- public static void main(String[] args) {
- // checking condition 2>3 and if true assign 3 else 3
- int x= (2>3)?3:2;
- System.out.println(x);
- // checking condition 5<4 if true assign 4 else 3
- int y= (5<4)?4:3;
- System.out.println(y);
- }
- }
- 2
- 3
Ternary operator in java for boolean:
Java simple example program on ternary operator / conditional operator for boolean
- package operatorsinjava;
- public class TernaryOperator {
- /**
- * @ www.instanceofjava.com
- *
- */
- public static void main(String[] args) {
- boolean x= true ? true: false;
- System.out.println(x);
- boolean y= false ? true : false;
- System.out.println(y);
- boolean z= false ? false : true;
- System.out.println(z);
- }
- }
- true
- false
- true
Ternary operator in java for Strings:
Java simple example program on ternary operator / conditional operator for String
- package operatorsinjava;
- public class TernaryOperatorForStrings{
- /**
- * @ www.instanceofjava.com
- *
- */
- public static void main(String[] args) {
- String str= "java".equals("java") ? "Java Questions" : "Java Programs";
- System.out.println(str);
- String str1= (1==3)? "its true" : "its false";
- System.out.println(str1);
- }
- }
- Java Questions
- its false
Ternary operator in java for null;
Java simple example program on ternary operator / conditional operator for null check
- package operatorsinjava;
- public class TernaryOperatorForStrings{
- /**
- * @ www.instanceofjava.com
- *
- */
- public static void main(String[] args) {
- String str= null;
- String str1= (str==null) ? "its true" : "its false";
- System.out.println(str1);
- String str2= (str1!=null) ? "its true" : "its false";
- System.out.println(str2);
- }
- }
- its true
- its true
Bagikan
Ternary operator in java
4/
5
Oleh
Kris Kimcil