In this chapter you will learn:
- What is conditional or ternary operator in java
- Programming example
What is conditional or ternary operator in java?
Symbol of Ternary operator is (?:) and it is also known as ternary operator. This operator works on 3 operands and simply minify your code by removing if else clause.
Syntax of ternary operator:
variable x = (expression) ? value if true : value if false
Programming Example:
class TernaryOperator { public static void main(String[] args) { int num1, num2, num3; num1 = 5; num2 = 10; //Output will be 10 num3=(num1 == num2) ? num1 : num2; System.out.println(num3); //Output will be Hello String s; s=(num1 != num2) ? "Hello" : "Hi"; System.out.println(s); } }
Output
D:\JavaProgram>javac TernaryOperator.java
D:\JavaProgram>java TernaryOperator
10
Hello
D:\JavaProgram> __
Summary
In this chapter you have learned what conditional or ternary operator in Java is. You have also learned a programming example of conditional operator. In the next chapter you will learn about Bitwise Operator in Java.