Java Learning Made Easy by Dheeraj Mehrotra - HTML preview

PLEASE NOTE: This is an HTML preview only and some elements such as links or page numbers may be incorrect.
Download the book in PDF, ePub, Kindle for a complete version.

Ternary Operator of JAVA

01698.jpg01699.jpg01700.jpg01701.jpg01702.jpg01703.jpg01704.jpg

This is an excellent substitute to the control statement like IF/THEN/ELSE

01705.jpg

of BASIC language. It is denoted by the combinational characters ?: and

01706.jpg

follows the usage with the following format/syntax :

01707.jpg01708.jpg01709.jpgvalue variable = (test expression) ? expression1 : expression2;

 

01710.jpg01711.jpg01712.jpg

which indicates that if the test expression is true then the transfer value

01713.jpg

for storage into the value variable is expression1 and if the test

01714.jpg

expression is false the transfer value becomes the expression2.

01715.jpg01716.jpg01717.jpgfor example:

 

01718.jpggrade = (total > 40) ? ‘P’ : ‘F’;

 

01719.jpg01720.jpg01721.jpg01722.jpg01723.jpg

In the above example grade refers to the value variable, total>40 is the

01724.jpg01725.jpg

test expression, ‘P’ is the expression1 and ‘F’ is the expression2. The ?

01726.jpg

character follows the true condition and : follows the false condition.

01727.jpg01728.jpg01729.jpgattention@computerscienceexpertise.com

 

01730.jpg01731.jpg01732.jpg01733.jpg01734.jpg01735.jpg01736.jpg01737.jpg01738.jpg01739.jpg01740.jpg01741.jpg01742.jpg01743.jpg01744.jpg01745.jpg01746.jpg01747.jpg01748.jpg