//program to demonstrate conditional operator
Description
This program demonstrates the use of conditional operator in Java. Conditional operator is an expression of the form x=(condition)? true part: false part;. Where condition is the condition to be checked, such as a>b. If the condition is satisfied the true part will be executed and if the condition is not satisfied the false part will be executed and the values associated with true part or false part will be assigned to x accordingly.
In this program the conditional expression is int x=(a>b)? 1:0;. The value of a and b is read as input from the user. If a is greater than b then x will be assigned with the value 1 and if a is not greater than b then x will be assigned with the value 0.
import java.io.*; class Conditional { void operator(int a,int b) { int x=(a>b)? 1:0; if(x==1) System.out.println("\nBiggest is " +a); else System.out.println("\nBiggest is " +b); } public static void main(String s[])throws Exception { int a,b,y; BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); Conditional obj=new Conditional(); System.out.println("Enter the value for a and b"); a=Integer.parseInt(br.readLine()); b=Integer.parseInt(br.readLine()); obj.operator(a,b); } }
Output
conditional operator |