How to use Nested Ternary Operator in Apex

String greeting ='';
Integer Hour = 10;
greeting = ((Hour<12) ?'Good Morning':'Good Afternoon') : ((Hour>12) ?'Good Morning':'Good Afternoon');
system.debug('Ternary Operator-->'+greeting);

I want to display Good Morning, if Hour is less than 12, I want to display Good Afternoon, if Hour is greater than 12,

But I want to use in single nested ternary operator in the apex but getting an error.

1 Answer

The ternary operator is just a condensed if. You don't need two of them here, since you have only one condition. Just do:

greeting = (Hour <= 12) ? 'Good Morning' : 'Good Afternoon';

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like