What does ? do in java | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 13

What does ? do in java

I have seen some code with a ? in a for loop and I don't know what the ? does. Can someone explain. Thanks.

23rd Feb 2019, 6:43 PM
J 12323123
J 12323123 - avatar
9 Answers
+ 15
?: is ternary oprator If you have some condition and you want find what is true or false Than use it ternary oprator For Example : a=10 ,b=5; If you use if else statment if(a > b) Print(true); else Print(false); And if you use ternary oprator Print(a>b?true:false);
27th Feb 2019, 8:28 AM
Sumit Programmer😎😎
Sumit Programmer😎😎 - avatar
+ 11
The conditional operator, ? : , is a shorthand for an if-then-else construction that does one of two different things depending upon the result of a boolean expression. The expression: variable = booleanExpr ? value1 : value2; has the same effect as: if (booleanExpr) { variable = value1; } else { variable = value2; } • The conditional operator is also sometimes called the 'ternary operator' or the 'question-colon operator'. For example, in the expression: isHungry() ? eat() : beMerry(); isHungry() will be evaluated first. If it evaluates to 'true' , eat() will be evaluated and beMerry() will not. Otherwise, beMerry() will be evaluated and eat() will not.
23rd Feb 2019, 7:32 PM
Danijel Ivanović
Danijel Ivanović - avatar
+ 9
J 12323123 ( ? )  Check the options where result equals "foo"   □  result = 2 > 4 ? "foo" : "bar";   □  result = 2 < 4 ? "foo" : "bar";   □  result = 2 > 4 ? "bar" : "foo";   ► NOTE: that Java, in a manner similar to C#, only evaluates the used expression and will not evaluate the unused expression.
27th Feb 2019, 7:34 AM
Danijel Ivanović
Danijel Ivanović - avatar
+ 8
? : is the ternary operator a = b ? c : d is equivalent to if(b) a = c; else a = d; x ? y : z ==> if x is true, do y, else z
23rd Feb 2019, 6:55 PM
Anna
Anna - avatar
23rd Feb 2019, 7:22 PM
Danijel Ivanović
Danijel Ivanović - avatar
+ 7
System.out.println(true?true:false); //is equivalent to if(true){System.out.println(true);} else{System.out.println(false);}
27th Feb 2019, 7:56 AM
D_Stark
D_Stark - avatar
+ 5
Speedy response!
23rd Feb 2019, 6:57 PM
J 12323123
J 12323123 - avatar
+ 3
int max(int x, int y) { return x>y ? x : y; }
23rd Feb 2019, 10:18 PM
Микола Федосєєв
Микола Федосєєв - avatar
+ 2
wao great reply
23rd Feb 2019, 6:57 PM
ShehzadaGulfam Educators
ShehzadaGulfam Educators - avatar