Skip to content

Commit 799f22b

Browse files
authored
Merge pull request #175 from RunestoneInteractive/ternary
Improvements to chapter 4
2 parents 0433911 + 982643d commit 799f22b

1 file changed

Lines changed: 36 additions & 26 deletions

File tree

source/ch4_conditionals.ptx

Lines changed: 36 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -162,17 +162,18 @@ public class ElseIf {
162162
<title>Using the <c>switch</c> Statement</title>
163163

164164
<p>
165-
Java also supports a <c>switch</c> statement that acts something like the <c>elif</c> statement of Python under certain conditions. To write the grade program using a <c>switch</c> statement we would use the following:
166-
</p>
165+
Java also supports a <c>switch</c> statement that acts something like the <c>elif</c> or Python <c>match</c> statement under certain conditions. To write the grade program using a <c>switch</c> statement we would use the following:
166+
</p
167167

168168
<note>
169169
<p>
170-
Depending on your knowledge and experience with Python you may be questioning why we are not using the <c>match</c> statement in our Python examples. The answer is that this book currently runs its active code examples using Python 3.7, which does not support the <c>match</c> statement which was introduced in Python 3.10. Below is an example of the <c>match</c> statement similar to our grade method.
170+
The <c>match - case</c> statement was introduced in Python 3.10, so doesn't run in earlier version of Python. Here is an example using Python's <c>match - case</c> structure.
171171
</p>
172172
<program xml:id="python-match" language="python">
173173
<title>Match Case Example</title>
174174
<code>
175175
grade = 85
176+
# Convert grade to a scale of 0-10 using integer division
176177
tempgrade = grade // 10
177178
def grading(tempgrade):
178179
match grade:
@@ -192,7 +193,7 @@ Java also supports a <c>switch</c> statement that acts something like the <c>eli
192193
</note>
193194

194195
<p><idx><c>switch</c></idx>
195-
The <c>switch</c> statement in Java provides a clean and efficient alternative to chaining multiple <c>if-else</c> conditions, especially when comparing a single variable against several constant values. It supports a variety of data types, including primitive types (<c>byte</c>, <c>short</c>, <c>char</c>, <c>int</c>), their wrapper classes, <c>enumerations</c>, and <c>String</c> (introduced in Java 7). Each <c>case</c> within a <c>switch</c> must be defined using a constant expression, and duplicate <c>case</c> values are not permitted. By default, control flow "<c>falls through</c>" from one <c>case</c> to the next unless a <c>break</c>, <c>return</c>, or <c>throw</c> statement is used to terminate execution.
196+
The <c>switch</c> statement in Java provides an alternative to chaining multiple <c>if-else</c> conditions, when comparing a single variable against several constant values. It supports a variety of data types, including primitive types (<c>byte</c>, <c>short</c>, <c>char</c>, <c>int</c>), their wrapper classes, <c>enumerations</c>, and <c>String</c> (introduced in Java 7). Each <c>case</c> within a <c>switch</c> must be defined using a constant expression, and duplicate <c>case</c> values are not permitted. By default, control flow "<c>falls through</c>" from one <c>case</c> to the next unless a <c>break</c>, <c>return</c>, or <c>throw</c> statement is used to terminate execution.
196197
</p>
197198

198199
<p>
@@ -204,8 +205,9 @@ Java also supports a <c>switch</c> statement that acts something like the <c>eli
204205
<program xml:id="java-switch-up" interactive="activecode" language="java">
205206
<code>
206207
public class SwitchUp {
207-
public static void main(String args[]) {
208+
public static void main(String args[]) {
208209
int grade = 85;
210+
// Convert grade to a scale of 0-10 using integer division
209211
int tempgrade = grade / 10;
210212
switch(tempgrade) {
211213
case 10:
@@ -224,14 +226,16 @@ Java also supports a <c>switch</c> statement that acts something like the <c>eli
224226
default:
225227
System.out.println('F');
226228
}
227-
}
229+
}
228230
}
229231
</code> <tests> </tests>
230232
</program>
231233

232234
<p>
233235
The <c>switch</c> statement is not used very often, and we recommend you do not use it. First, it is not as powerful as the <c>else if</c> model because the switch variable can only be compared for equality with an integer or enumerated constant. Second, it is very easy to forget to put in the <c>break</c> statement, so it is more error-prone. If the break statement is left out then then the next alternative will be automatically executed. For example, if the grade was 95 and the <c>break</c> was omitted from the <c>case 9:</c> alternative then the program would print(out both A and B.)
234236
</p>
237+
<p>
238+
Finally, the <c>switch</c> statement does not support relational expressions such as greater than or less than. So you cannot use it to completely replace the <c>elif</c>. Even with the new features of Java 14+ the <c>switch</c> statement is still limited to constant comparisons using equality.</p>
235239
</section>
236240

237241
<section xml:id="exception-handling">
@@ -385,17 +389,15 @@ The <c>switch</c> statement is not used very often, and we recommend you do not
385389

386390
</section>
387391

388-
<section xml:id="boolean-operators">
389-
<title>Boolean Operators</title>
392+
<section xml:id="ternary-operator">
393+
<title>The Ternary Operator</title>
390394

391395
<p><idx>Boolean operators</idx> <idx>simple comparisons</idx> <idx>compound Boolean expressions</idx>
392396
The conditionals used in the if statement can be <term>Boolean variables</term>, <term>simple comparisons</term>, and <term>compound Boolean expressions</term>.
393397
</p>
394398

395399
<p><idx>ternary operator</idx>
396-
Java also supports the <c>boolean</c> expression using the ternary operator
397-
<c>condition ? trueValue : falseValue</c>. This operator tests a condition as part
398-
of an assignment statement. The following table summarizes how this works:
400+
Java also provides the ternary operator <c>condition ? valueIfTrue : valueIfFalse</c>, which lets you use a <c>boolean</c> test directly inside an assignment. If the condition is true, the first value is chosen; otherwise, the second value is used. The table below summarizes how it works:
399401
</p>
400402

401403
<table>
@@ -437,27 +439,35 @@ of an assignment statement. The following table summarizes how this works:
437439
</table>
438440

439441
<p>
440-
Using this operator can make code shorter and more readable in cases where a simple conditional assignment is needed.
442+
Using this operator can make code shorter and more readable in cases where a simple conditional assignment is needed. See the following as an example where we see the same logic implemented in two different ways.
441443
</p>
442-
<program xml:id="java-ternary" interactive ="activecode" language ="java">
444+
<program xml:id="java-ternary" interactive="activecode" language ="java">
443445
<code>
444-
class Main {
445-
public static void main(String[] args) {
446-
int a = 4;
447-
int x = 2;
448-
449-
// Using the ternary operator
450-
a = (a % 2 == 0) ? a * a : 3 * x - 1;
446+
public class Ternary {
447+
public static void main(String[] args) {
448+
int a = 4;
449+
int x = 2;
450+
int outp;
451+
452+
// ternary:
453+
outp = (a % 2 == 0) ? (a * a) : (3 * x - 1);
454+
System.out.println("ternary result: " + outp);
455+
456+
// Equivalent using if/else
457+
if (a % 2 == 0) {
458+
outp = a * a;
459+
} else {
460+
outp = 3 * x - 1;
461+
}
451462

452-
System.out.println("Result: " + a);
453-
}
454-
}
455-
463+
System.out.println("if/else result: " + outp);
464+
}
465+
}
456466
</code>
457467
</program>
458468

459469
<p>
460-
In this example we are using this ternary operator to assign a value to <c>a</c> based on whether <c>a</c> is even or odd. If <c>a</c> is even, it will be squared; if odd, it will be instead be calculated as <c>3 * x - 1</c>. This is a concise way to write conditional assignments in Java. However, it should be used reasonably, as it can make code less readable if overused or used in complex expressions.
470+
In this example we are using this ternary operator to assign a value to <c>a</c> based on whether <c>a</c> is even or odd. If <c>a</c> is even, it will be squared; if odd, it will be instead be calculated as <c>3 * x - 1</c>. This is a concise way to write conditional assignments in Java. However, you might want to use it sparingly, as it can make code less readable if overused or used with complex expressions.
461471
</p>
462472

463473

@@ -473,7 +483,7 @@ Using this operator can make code shorter and more readable in cases where a sim
473483
</li>
474484
<li>
475485
<p>
476-
Java's <c>switch</c> statement is similar to Python's <c>match</c> statement, but it only supports equality checks against constant values and does not evaluate relational expressions like greater than or less than.
486+
Java's <c>switch</c> statement is similar to Python's <c>match</c> statement, but it only supports equality checks against constant values and does not evaluate relational expressions like greater than or less than.
477487
</p>
478488

479489
</li>

0 commit comments

Comments
 (0)