Conditional Operator (Ternary Operator)

Conditional operator is also known as the ternary operator. Java includes a ternary (three-way) operator that can replace certain types of if-then-else statements. It has the following syntax:
expression1  ?  expression2  :  expression3

Here, expression1 can be any expression that evaluates to a boolean value. If expression1 is true, then expression2 is evaluated; otherwise, expression3 is evaluated. For example,
int a=10;
int b = (a != 1) ? 20: 30;

As shown in above example the condition a != 1 is true then b will have a value 20. The program for the use of conditional operator is given below.

PROGRAM
class ConditionalOpDemo {

 public static void main(String[] args) {
  
  int x = 25, y = 22;
  System.out.println("x = "+x);
  System.out.println("y = "+y);
  x = (y>25) ? y : 50;
  System.out.println("x = (y>25) ? y : 50");
  System.out.println("Now, x = "+x);
 }
}
OUTPUT
C:\javac ConditionalOpDemo.java
C:\java ConditionalOpDemo
x = 25
y = 22
x = (y>25) ? y : 50
Now, x = 50

Popular posts from this blog

Program to define a class 'employee' with data members as empid, name and salary. Accept data for 5 objects using Array of objects and print it.

Define a class Student with four data members such as name, roll no.,sub1, and sub2. Define appropriate methods to initialize and display the values of data members. Also calculate total marks and percentage scored by student.

Program to input age from user and throw user-defined exception if entered age is negative