Page 167 - CA_Blue( J )_Class9
P. 167
Ternary Operator
The ternary operator, also known as the conditional operator, is a conditional statement. It is called ternary because
it has three parts: a condition, a value if true, and a value if false. It lets programmers write an if-else statement in
one line, making the code more concise.
Syntax:
Result = (Condition)? Statement1: Statement 2;
Here, satisfied condition will execute Statement 1, else will execute Statement 2.
Example:
int age=49;
String retired;
retired = (age>60) ? "yes" : "no";
System.out.println(" Your restirement Status :"+ retired);
Program 6 Input the name and marks of a student and print the student has passed or failed. Pass marks
is 40 and above.
1 import java.util.*;
2 class student_result
3 {
4 public static void main(String args[])
5 {
6 String name, result;
7 int M;
8 Scanner input = new Scanner(System.in);
9 System.out.print("Enter your name: ");
10 name = input.nextLine();
11 System.out.print("Enter your marks: ");
12 M = input.nextInt();
13 result=(M>40)? "Pass":"Fail";
14 System.out.println("Student's Name: "+name);
15 System.out.println("Result "+result);
16 }
17 }
You will get the following output:
Conditional Constructs in Java 165

