What does this " ?: " mean in java | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

What does this " ?: " mean in java

: or ?: or !: is it equal = ?

19th Apr 2019, 6:01 AM
Tzion
Tzion - avatar
7 Answers
+ 14
• The ternary operator:    condition ? value if true : value if false Here’s what you need to know: ➝ The "condition" is what you’re actually testing. The result of your condition should be 'true' or 'false' or at least coerce to either boolean value. ➝ A ' ? ' separates our conditional from our 'true' value. Anything between the ' ? ' and the ' : ' is what is executed if the "condition" evaluates to 'true'. ➝ Finally a ' : ' colon. If your condition evaluates to 'false', any code after the colon is executed.
19th Apr 2019, 7:07 AM
Danijel Ivanović
Danijel Ivanović - avatar
+ 12
▪The  ?:  operator in Java The value of a variable often depends on whether a particular boolean expression is or is not true and on nothing else. For instance one common operation is setting the value of a variable to the maximum of two quantities. In Java you might write:   if ( a > b ) {       max = a;   } else {       max = b;   } Setting a single variable to one of two states based on a single condition is such a common use of 'if-else' that a shortcut has been devised for it, the conditional operator ?: Using the conditional operator you can rewrite the above example in a single line like this:     max = ( a > b ) ? a : b; ( a > b ) ? a : b;  is an expression which returns one of two values, a or b.       The condition, ( a > b ), is tested.   • If it is 'true' the first value, a, is returned.   • If it is 'false' , the second value, b, is returned. Whichever value is returned is dependent on the conditional test, a > b. The condition can be any expression which returns a boolean value.
19th Apr 2019, 7:06 AM
Danijel Ivanović
Danijel Ivanović - avatar
+ 7
Does Java support the Elvis operator? https://en.m.wikipedia.org/wiki/Elvis_operator That's what `?:` is in C#. Based on this link, I suppose not. https://stackoverflow.com/questions/52285813/how-to-implement-the-elvis-operator-in-java-8 In that case, it's likely the ternary operator: (condition) ? (value if true) : (value if false)
19th Apr 2019, 6:35 AM
David Carroll
David Carroll - avatar
+ 2
It is the ternary operator
19th Apr 2019, 10:00 AM
Satyaki Ray
+ 1
David Carroll its hard for me O.O, can u explain in statement of If...else keyword?
19th Apr 2019, 6:58 AM
Tzion
Tzion - avatar
0
Jay Matthews can u create more examples,btw thank you so much
19th Apr 2019, 6:09 AM
Tzion
Tzion - avatar
0
Jay Matthews The tittle is min of 4 numbers mean minimum 4 numbers to do that? and what is the <<end1 mean in the code
19th Apr 2019, 6:18 AM
Tzion
Tzion - avatar