Lecture 11: Ternary Operator Example
Ternary operator problem statement
Implement the ‘Ternary’ operator where ‘grade’ is 74 and ‘result’ is a String.
Print out ‘Pass’ if result >= 60 and ‘Fail’ otherwise.
Ternary operator solution
String result = (grade >= 60) ? “Pass” : “Fail”;
Ternary operator output
Pass
Hi there, This is Marius from AlefTav Coding. Today, I will look at Java's Ternary operator. It is a statement which includes conditions. In this lecture you will learn how to Implement the Ternary operator where grade is 74 and result is a String. Print out Pass if result >= 60 and Fail otherwise.
public class Lecture11 {
public static void main(String[] args) {
int grade = 74;
String result = (grade >= 60) ? “Pass” : “Fail”;
System.out.print(result);
}
}
You read this line, String result = (grade >= 60) ? “Pass” : “Fail”; as follows. If a student's grade is larger than or equal to 60, then the String, result holds a reference to the text, Pass. Otherwise, grade points to the text, Fail.
So, here I have a class, Lecture11 with a main() method. I declare grade as an int data type and set its value to 74. Then declaring result as a String and assign it to the value produced by the ternary operator. Either a Pass or a Fail. Then I do a printout of this result.
With my program complete, it can then be run. It produces the output, Pass, because the value, 74 is larger than the value, 60.
In today's lecture you learnt a somewhat advanced concept, the Ternary operator. Also, how to implement it in Java. Now, to practise your understanding of it, here is the coding exercise, for you to try as homework.
Ternary operator coding exercise:
Implement the Ternary operator where wages are 3700 and earnings are a String. Print out Exempt if earnings < 4500 and Taxable otherwise.
My name is Marius from AlefTav Coding. Till our next meeting, KEEP CODING.
Just a reminder, that, if you found this tutorial helpful, please upvote, subscribe, like and share. You can find me at the following links.
https://www.udemy.com/course/1435298/manage/basics/
https://d.tube/#!/c/mariusclaassen
https://steemit.com/@mariusclaassen