Repository navigation
Expand file tree
/
Copy pathch5_conditionals.ptx
More file actions
314 lines (274 loc) · 11.8 KB
/
Copy pathch5_conditionals.ptx
File metadata and controls
314 lines (274 loc) · 11.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
<?xml version="1.0"?>
<!-- Generated by Docutils 0.19 -->
<chapter xml:id="conditionals">
<title>Conditionals</title>
<section xml:id="simple-if">
<title>Using the Simple <c>if</c> Statement</title>
<p><idx>conditional statements</idx>
Conditional statements in Python and Java are very similar.
In Python we have three patterns:
</p>
<p>
In Python the simple <c>if</c> statement is written as:
</p>
<program interactive="activecode" language="python">
<code>
score = 95
if score >= 90:
print("Excellent work!")
</code>
</program>
<p>
In Java, this same pattern requires two changes: the condition must be in parentheses <c>()</c>, and the code block must be enclosed in curly braces <c>{}</c>.
</p>
<program interactive="activecode" language="java">
<code>
public class SimpleIfExample {
public static void main(String[] args) {
int score = 70;
if (score <= 70) {
System.out.println("Needs work!");
}
}
}
</code>
</program>
<p>
Once again you can see that in Java the curly braces define a block rather than indentation.
In Java the parenthesis around the condition are required because it is technically a function that evaluates to <c>True</c> or <c>False</c>.
</p>
</section>
<section xml:id="if-else">
<title>Using the <c>if</c> - <c>else</c> Statement</title>
<p>The Java equivalent follows the same syntactical rules as before.</p>
<program interactive="activecode" language="python">
<code>
age = 16
if age >= 18:
print("You can vote.")
else:
print("You are not yet eligible to vote.")
</code>
</program>
<program language="java">
<code>
public class IfElseExample {
public static void main(String[] args) {
int age = 16;
if (age >= 18) {
System.out.println("You can vote.");
} else {
System.out.println("You are not yet eligible to vote.");
}
}
}
</code>
</program>
</section>
<section xml:id="elif">
<title>Can we use <c>elif</c>?</title>
<p><idx><c>elif</c> statement</idx>
Java does not have an <c>elif</c> pattern like Python.
In Java you can get the functionality of an <c>elif</c> statement by nesting <c>if</c> and <c>else</c>.
Here is a simple example in both Python and Java.
</p>
<program interactive="activecode" language="python">
<code>
grade = int(input('enter a grade'))
if grade < 60:
print('F')
elif grade < 70:
print('D')
elif grade < 80:
print('C')
elif grade < 90:
print('B')
else:
print('A')
</code> <tests> </tests>
</program>
<p>
In Java we have a couple of ways to write this.
</p>
<program interactive="activecode" language="java">
<code>
public class ElseIf {
public static void main(String args[]) {
int grade = 85;
if (grade < 60) {
System.out.println('F');
} else {
if (grade < 70) {
System.out.println('D');
} else {
if (grade < 80) {
System.out.println('C');
} else {
if (grade < 90) {
System.out.println('B');
} else {
System.out.println('A');
}
}
}
}
}
}
</code> <tests> </tests>
</program>
<p>
We can get even closer to the <c>elif</c> statement by taking advantage of the Java rule that a single statement does not need to be enclosed in curly braces. Since the if is the only statement used in each else we can get away with the following.
</p>
<program interactive="activecode" language="java">
<code>
public class ElseIf {
public static void main(String args[]) {
int grade = 85;
if (grade < 60) {
System.out.println('F');
} else if (grade < 70) {
System.out.println('D');
} else if (grade < 80) {
System.out.println('C');
} else if (grade < 90) {
System.out.println('B');
} else System.out.println('A');
}
}
</code> <tests> </tests>
</program>
</section>
<section xml:id="switch">
<title>Using the <c>switch</c> Statement</title>
<p>
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:
</p>
<note>
<p>
Depending on your knowledge and experience with Python you may already be familiar and 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 on Python 3.7, which does not support the <c>match</c> statement. The <c>match</c> statement was introduced in Python 3.10. Below is an example of the <c>match</c> statement similar to our grade method.
</p>
<program language="python">
<title>Match Case Example</title>
<code>
grade = 100 // 10
def grading(grade):
match grade:
case 10 | 9:
return 'A'
case 8:
return 'B'
case 7:
return 'C'
case 6:
return 'D'
case _:
return 'F'
print(grading(grade))
</code>
</program>
</note>
<p><idx><c>switch</c></idx>
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.
</p>
<p><idx><c>switch</c> expressions</idx>
Java 14 introduced <c>switch</c> <term>expressions</term>, enhancing functionality by allowing the <c>switch</c> to return values and eliminating <c>fall-through</c> via the <c>-></c> arrow syntax. These expressions can even use <c>yield</c> within code blocks for more complex evaluations. It’s important to note that traditional <c>switch</c> statements do not support <c>null</c> values and will throw a <c>NullPointerException</c> if evaluated with <c>null</c>. As the language evolves, newer versions of Java continue to extend <c>switch</c> capabilities with features like <c>pattern matching</c> and enhanced <c>type handling</c>, making it a more powerful and expressive tool for decision-making in Java programs.
</p>
<program interactive="activecode" language="java">
<code>
public class SwitchUp {
public static void main(String args[]) {
int grade = 85;
int tempgrade = grade / 10;
switch(tempgrade) {
case 10:
case 9:
System.out.println('A');
break;
case 8:
System.out.println('B');
break;
case 7:
System.out.println('C');
break;
case 6:
System.out.println('A');
break;
default:
System.out.println('F');
}
}
}
</code> <tests> </tests>
</program>
<p>
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.)
</p>
</section>
<section xml:id="boolean-operators">
<title>Boolean Operators</title>
<p><idx>Boolean operators</idx>
The conditionals used in the if statement can be Boolean variables, simple comparisons, and compound Boolean expressions.
</p>
<p><idx>ternary operator</idx>
Java also supports the <c>boolean</c> expression using the ternary operator
<c>condition ? trueValue : falseValue</c>. This operator tests a condition as part
of an assignment statement. The following table summarizes how this works:
</p>
<table>
<title>Ternary Operator in Java</title>
<tabular>
<row>
<cell><term>Component</term></cell>
<cell><term>Description</term></cell>
</row>
<row>
<cell><c>condition</c></cell>
<cell>The Boolean expression that is evaluated (e.g., <c>a % 2 == 0</c>).</cell>
</row>
<row>
<cell><c>?</c></cell>
<cell> This is the ternary operator that separates the condition from the <c>trueValue</c>.</cell>
</row>
<row>
<cell><c>trueValue</c></cell>
<cell>The value assigned if the condition is true (e.g., <c>a * a</c>).</cell>
</row>
<row>
<cell><c>:</c></cell>
<cell> This is the ternary operator that separates the <c>trueValue</c> from the <c>falseValue</c>.</cell>
</row>
<row>
<cell><c>falseValue</c></cell>
<cell>The value assigned if the condition is false (e.g., <c>3 * x - 1</c>).</cell>
</row>
<row>
<cell>Example Usage</cell>
<cell><c>a = a % 2 == 0 ? a * a : 3 * x - 1</c></cell>
</row>
<row>
<cell>Equivalent if-else Code</cell>
<cell>Can also be written with a regular <c>if-else</c> statement, but the ternary form is more concise.</cell>
</row>
</tabular>
</table>
<p>
Using this operator can make code shorter and more readable in cases where a simple conditional assignment is needed.
</p>
<program interactive ="activecode" language ="java">
<code>
class Main {
public static void main(String[] args) {
int a = 4;
int x = 2;
// Using the ternary operator
a = (a % 2 == 0) ? a * a : 3 * x - 1;
System.out.println("Result: " + a);
}
}
</code>
</program>
<p>
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.
</p>
</section>
</chapter>