File tree Expand file tree Collapse file tree 1 file changed +68
-0
lines changed
Expand file tree Collapse file tree 1 file changed +68
-0
lines changed Original file line number Diff line number Diff line change 1+ In Java, ? appears only as part of the ternary conditional operator.
2+
3+ General form
4+
5+ condition ? value_if_true : value_if_false
6+
7+ It is a compact if–else expression that returns a value.
8+
9+ ⸻
10+
11+ Simple example
12+
13+ int a = 5;
14+ int b = 10;
15+
16+ int max = (a > b) ? a : b;
17+
18+ Equivalent to:
19+
20+ int max;
21+ if (a > b) {
22+ max = a;
23+ } else {
24+ max = b;
25+ }
26+
27+
28+ ⸻
29+
30+ In the context of the earlier discussion
31+
32+ There was no ternary operator used in the last Java code.
33+
34+ This line:
35+
36+ cost += (sDigit - tDigit + 10) % 10;
37+
38+ does not contain ?.
39+ It uses modulo arithmetic, not a conditional operator.
40+
41+ ⸻
42+
43+ When ? is typically used
44+ • Assigning values based on a condition
45+ • Returning one of two expressions
46+ • Compact logic where readability is preserved
47+
48+ Example:
49+
50+ String result = (x >= 0) ? "Positive" : "Negative";
51+
52+
53+ ⸻
54+
55+ When NOT to use ?
56+ • Complex nested logic
57+ • Multiple statements
58+ • Situations where clarity suffers
59+
60+ ⸻
61+
62+ Summary
63+ • ? is not a wildcard
64+ • ? is not optional
65+ • ? always pairs with :
66+ • Meaning: “if condition then this else that”
67+
68+ End.
You can’t perform that action at this time.
0 commit comments