Scanner class Methods in Java

Java-Conditional Operator

Conditional Operator(?:)

Conditional operator is the only ternary operator in Java. It operates on three operands.The first operand is always an expression to be calculated and other two operands are the expected results of  first expression.

The conditional operators together form a conditional expression. The general notation of conditional expression is given below::

exp1 ?exp2 : exp3

here, we can replace expressions with our own logic.Lets understand it with an example.

Use of Conditional Operator(?:)

  1. It makes easy to calculate the result of expression.
  2. It makes program precise and understandable.
  3. It saves from writing a lot of lines of code.
  4. It consumes less time as the number of lines are not required to calculate expression and save result.

Example: 

Aakash has two variables "a" and "b" ,whose value is 5 and 7 respectively.He wants to make a program by which he can find out the greater number and print it on screen . If "a" is greater it will print 5 on screen else 7.

solution:  

Steps: 
  • First Aakash makes a logic using conditional operators ,where he will use relational greater than operator to check if "a" is greater than "b". 
a>b   //it is a relational expression
  • Now ,he wants to calculate the expression so he will write"?" after it ,which tells the compiler that  to calculate the expression and find the result.Adding brackets makes the code readable and easy to compute.
(a>b) ?
  • After the calculation finishes, if  "a" is greater then he wants the program to return value of "a" ,else to return "b".To write two expected results from which one will be returned.
(a>b) a:b
  • In the step 3, the statement is completed. First expression will evaluate the result  if the result is true it will return "a" else "b" 
Java Conditional Operator
Lets write a java program to calculate greater number using conditional operator, 

Java Conditional Operator ? : example


Output:

Java Conditional Operator ? : example

Experiment: Find the smallest number using conditional operator.

Try it Yourself!Happy Coding!

Comments