Ternary operator is used to minimize the keystrokes and increase the readability of the code. The simple if else condition and ternary operator perform the same task. This simple program returns the greater number with the use of ternary operator.
Source Code
import java.util.Scanner; public class Toperator { public static void main(String[] args) { int a,b,c; Scanner input = new Scanner (System.in); System.out.print("\t \t \t LEP Tutorials \n \n "); System.out.print(" Enter Your Number : "); a = input.nextInt(); System.out.print(" Enter Your Number : "); b = input.nextInt(); c = (a > b) ? a : b; System.out.print(" Greater Number is : "+c); } }
int a = (i == 0) ? ten : 5;
ReplyDeletecan do assignment with if/else like this:
// invalid:
int a = if (i == 0) 10; else 5;
This is a decent reason to use the ternary operator. If you do not have AN assignment: