Tuesday, 21 October 2014

Ternary Operator in Java

Structure of the Problem Requirements

In this problem we will learn how to use ternary operator in Java. Before this we upload ternary operator in C++. 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 return the greater number with the use of ternary operator. Here is the source code of this problem which help you in better understanding.

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
Ternary Operator in Java

Share it Please

About Author!

Asad Niazi is Software Engineer , Programmer, Web Developers and a young mentor of Tech Solutions Desk and Blogging Solutions . Asad Love to writes about Technology, Programming, Blogging and make money online.

2 comments: Post Yours! Read Comment Policy!▼
Important Note:
We have Zero Tolerance to Spam. Chessy Comments and Comments with Links will be deleted immediately upon our review.

  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:

  2. Is the Ternary Operator Just use for check Condition or doing something else ... ??
    what is difference checking condition while we using if else and ternary operator .. !!