Ternary Operator in Java

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);
   
 }
 }

Output of the Program

Ternary Operator in Java

Share on Google Plus

About Asad

Asad Niazi is Software Engineer , Programmer, Web Developer and a young mentor of BloggersTown and PProgramming. Asad Love to writes about Technology, Programming, Blogging and make money online.

1 comments:

  1. int a = (i == 0) ? ten : 5;
    can 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:

    ReplyDelete