statements.xml 236 KB
Newer Older
Dr. Martin Goik's avatar
Dr. Martin Goik committed
1
<?xml version="1.0" encoding="UTF-8"?>
2 3 4 5 6 7 8 9 10 11
<chapter annotations="slide" version="5.1" xml:id="sd1_chap_Statements"
         xmlns="http://docbook.org/ns/docbook"
         xmlns:xlink="http://www.w3.org/1999/xlink"
         xmlns:xila="http://www.w3.org/2001/XInclude/local-attributes"
         xmlns:xi="http://www.w3.org/2001/XInclude"
         xmlns:svg="http://www.w3.org/2000/svg"
         xmlns:ns="http://docbook.org/ns/transclusion"
         xmlns:m="http://www.w3.org/1998/Math/MathML"
         xmlns:html="http://www.w3.org/1999/xhtml"
         xmlns:db="http://docbook.org/ns/docbook">
Dr. Martin Goik's avatar
Dr. Martin Goik committed
12 13
  <title>Statements</title>

Dr. Martin Goik's avatar
Dr. Martin Goik committed
14 15
  <figure xml:id="sd1_fig_StatementTypes">
    <title>Purposes of statements</title>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
16

Dr. Martin Goik's avatar
Dr. Martin Goik committed
17 18 19 20 21 22 23 24 25 26
    <itemizedlist>
      <listitem>
        <para>Declaring variables and assigning values.</para>
      </listitem>

      <listitem>
        <para>Creating output.</para>
      </listitem>

      <listitem>
27 28
        <para>Control <emphasis role="bold">whether</emphasis> code will be
        executed.</para>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
29 30 31
      </listitem>

      <listitem>
32 33
        <para>Control <emphasis role="bold">how often</emphasis> code will be
        executed.</para>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
34 35 36 37 38
      </listitem>
    </itemizedlist>
  </figure>

  <figure xml:id="sd1_fig_StatementEndSemicolon">
Dr. Martin Goik's avatar
Dr. Martin Goik committed
39
    <title>Statements: General syntax</title>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
40

Dr. Martin Goik's avatar
Dr. Martin Goik committed
41
    <para>Statement's body terminated by <quote>;</quote></para>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
42

43
    <programlisting language="none">{statement};</programlisting>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
44 45 46
  </figure>

  <figure xml:id="sd1_fig_StatementDeclareVariable">
47
    <title>Statement examples: Declaring and assigning variables</title>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
48

Dr. Martin Goik's avatar
Dr. Martin Goik committed
49
    <glosslist>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
50
      <glossentry>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
        <glossterm>Variable declaration:</glossterm>

        <glossdef>
          <programlisting language="java">int a;</programlisting>
        </glossdef>
      </glossentry>

      <glossentry>
        <glossterm>Value assignment:</glossterm>

        <glossdef>
          <programlisting language="java">a = 33;</programlisting>
        </glossdef>
      </glossentry>

      <glossentry>
        <glossterm>Combined declaration and assignment:</glossterm>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
68 69 70 71 72 73 74 75 76 77 78

        <glossdef>
          <programlisting language="java">int a = 33;</programlisting>
        </glossdef>
      </glossentry>
    </glosslist>
  </figure>

  <figure xml:id="sd1_fig_StatementVsExpression">
    <title>Expression <abbrev>vs.</abbrev> statement</title>

Dr. Martin Goik's avatar
Dr. Martin Goik committed
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
    <glosslist>
      <glossentry>
        <glossterm>Expression:</glossterm>

        <glossdef>
          <programlisting language="java">a - 4</programlisting>
        </glossdef>
      </glossentry>

      <glossentry>
        <glossterm>Statement:</glossterm>

        <glossdef>
          <programlisting language="java">b = a - 4;</programlisting>

          <para>Notice the trailing <quote><code>;</code></quote>.</para>
        </glossdef>
      </glossentry>
    </glosslist>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
98 99 100 101 102
  </figure>

  <figure xml:id="sd1_fig_MultiStmtPerLine">
    <title>Multiple statements per line</title>

103
    <programlisting language="java">a = b + 3; b = a - 4;</programlisting>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
104 105

    <para>Discouraged by good coding practices:</para>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
106 107 108

    <itemizedlist>
      <listitem>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
109
        <para>Poor readability</para>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
110 111 112
      </listitem>

      <listitem>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
113
        <para>Hampers debugging</para>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
114 115
      </listitem>
    </itemizedlist>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
116 117 118 119 120 121 122
  </figure>

  <figure xml:id="sd1_fig_DebugMultiStmtPerLine">
    <title>Debugging multiple statements per line</title>

    <mediaobject>
      <imageobject>
123
        <imagedata fileref="Ref/Statements/multipleStatementPerLine.svg"/>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
124 125 126 127 128 129 130 131
      </imageobject>
    </mediaobject>
  </figure>

  <figure xml:id="sd1_fig_Blocks">
    <title>Blocks</title>

    <programlisting language="java">double initialAmount = 34;
Dr. Martin Goik's avatar
Dr. Martin Goik committed
132
{ <emphasis role="red">// first block</emphasis>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
133 134
  final double interestRate = 1.2; // 1.2%
  System.out.println("Interest:" + initialAmount * interestRate / 100);
Dr. Martin Goik's avatar
Dr. Martin Goik committed
135
}
Dr. Martin Goik's avatar
Dr. Martin Goik committed
136
{ <emphasis role="red">// second block</emphasis>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
137 138
  final double interestRate = 0.8; // 0.8%
  System.out.println("Interest:" + initialAmount * interestRate / 100);
Dr. Martin Goik's avatar
Dr. Martin Goik committed
139
}</programlisting>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154

    <informaltable border="1">
      <tr>
        <td><itemizedlist>
            <listitem>
              <para>Defining scopes</para>
            </listitem>

            <listitem>
              <para>Unit of work</para>
            </listitem>
          </itemizedlist></td>

        <td><itemizedlist>
            <listitem>
155 156
              <para><code language="java">if</code>: Conditional block
              execution.</para>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
157 158 159
            </listitem>

            <listitem>
160 161
              <para><code language="java">for</code> / <code
              language="java">while</code>: Repeated block execution.</para>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
162 163 164 165 166 167 168
            </listitem>
          </itemizedlist></td>
      </tr>
    </informaltable>
  </figure>

  <section xml:id="sd1_sect_statements_if">
Dr. Martin Goik's avatar
Dr. Martin Goik committed
169
    <title>The if conditional statement</title>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
170 171

    <figure xml:id="sd1_fig_if">
Dr. Martin Goik's avatar
Dr. Martin Goik committed
172
      <title>Conditional block execution</title>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
173

Dr. Martin Goik's avatar
Dr. Martin Goik committed
174 175
      <informaltable border="1">
        <tr>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
176
          <td valign="top"><programlisting language="java">double saving = 320.00;
Dr. Martin Goik's avatar
Dr. Martin Goik committed
177

Dr. Martin Goik's avatar
Dr. Martin Goik committed
178
if (1000 &lt;= saving) {
Dr. Martin Goik's avatar
Dr. Martin Goik committed
179
  // Rich customer, 1,2% interest rate
Dr. Martin Goik's avatar
Dr. Martin Goik committed
180
  System.out.println(
Dr. Martin Goik's avatar
Dr. Martin Goik committed
181
    "Interest:" + 1.2 * saving / 100);
Dr. Martin Goik's avatar
Dr. Martin Goik committed
182
}
183
System.out.println("Done!");</programlisting></td>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
184

185
          <td rowspan="2" valign="top"><mediaobject>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
186 187 188 189 190
              <imageobject>
                <imagedata fileref="Ref/Statements/if.svg"/>
              </imageobject>
            </mediaobject></td>
        </tr>
191 192

        <tr>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
193
          <td><screen>Done!</screen></td>
194
        </tr>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
195 196 197
      </informaltable>
    </figure>

198
    <figure xml:id="sd1_fig_ifSyntax">
Dr. Martin Goik's avatar
Dr. Martin Goik committed
199
      <title><code language="java">if</code> syntax</title>
200

Dr. Martin Goik's avatar
Dr. Martin Goik committed
201
      <programlisting language="java">if (booleanExpression)
202 203 204
  (block | statement)</programlisting>
    </figure>

205 206
    <section xml:id="sd1_sect_else">
      <title>if-then-<code>else</code></title>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
207

208 209
      <figure xml:id="sd1_fig_ifElse">
        <title><code language="java">if</code> ... <code
Dr. Martin Goik's avatar
Dr. Martin Goik committed
210
        language="java">else</code></title>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
211

212 213 214
        <informaltable border="1">
          <tr>
            <td valign="top"><programlisting language="java">double saving = 320.00;
Dr. Martin Goik's avatar
Dr. Martin Goik committed
215 216

if (1000 &lt;= saving <co linkends="sd1_fig_ifElse-1"
217 218
                  xml:id="sd1_fig_ifElse-1-co"/>)  { <co
                  linkends="sd1_fig_ifElse-2" xml:id="sd1_fig_ifElse-2-co"/>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
219 220
  // Rich customer, 1,2% interest rate
  System.out.println(
Dr. Martin Goik's avatar
Dr. Martin Goik committed
221
     "Interest:" + 1.2 * saving / 100);
Dr. Martin Goik's avatar
Dr. Martin Goik committed
222
} <co linkends="sd1_fig_ifElse-3" xml:id="sd1_fig_ifElse-3-co"/> else { <co
223
                  linkends="sd1_fig_ifElse-4" xml:id="sd1_fig_ifElse-4-co"/>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
224 225
  // Joe customer, 0.8%
  // standard interest rate
Dr. Martin Goik's avatar
Dr. Martin Goik committed
226
  System.out.println(
Dr. Martin Goik's avatar
Dr. Martin Goik committed
227
    "Interest:" + 0.8 * saving / 100);
Dr. Martin Goik's avatar
Dr. Martin Goik committed
228
}
Dr. Martin Goik's avatar
Dr. Martin Goik committed
229
System.out.println("Done!");</programlisting><screen>Interest:2.56
Dr. Martin Goik's avatar
Dr. Martin Goik committed
230
Done!</screen></td>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
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
            <td valign="top"><mediaobject>
                <imageobject>
                  <imagedata fileref="Ref/Statements/ifElse.svg"/>
                </imageobject>
              </mediaobject></td>
          </tr>
        </informaltable>

        <calloutlist role="slideExclude">
          <callout arearefs="sd1_fig_ifElse-1-co" xml:id="sd1_fig_ifElse-1">
            <para>Decision on boolean expression.</para>
          </callout>

          <callout arearefs="sd1_fig_ifElse-2-co" xml:id="sd1_fig_ifElse-2">
            <para>Conditional execution of on block or single
            statement.</para>
          </callout>

          <callout arearefs="sd1_fig_ifElse-3-co" xml:id="sd1_fig_ifElse-3">
            <para>Required branch being executed in case of boolean expression
            being true.</para>
          </callout>

          <callout arearefs="sd1_fig_ifElse-4-co" xml:id="sd1_fig_ifElse-4">
            <para>Optional branch corresponding to boolean expression being
            false.</para>
          </callout>
        </calloutlist>
      </figure>

      <figure xml:id="sd1_fig_ifElseSyntax">
Dr. Martin Goik's avatar
Dr. Martin Goik committed
263
        <title><code language="java">if ... else</code> syntax</title>
264 265

        <programlisting language="java">if (booleanExpression)
266
   (block | statement)
Dr. Martin Goik's avatar
Dr. Martin Goik committed
267
[else
268
   (block | statement) ] <co linkends="sd1_fig_ifElseSyntax-1"
269
            xml:id="sd1_fig_ifElseSyntax-1-co"/></programlisting>
270

271 272 273 274 275
        <calloutlist role="slideExclude">
          <callout arearefs="sd1_fig_ifElseSyntax-1-co"
                   xml:id="sd1_fig_ifElseSyntax-1">
            <para>The <quote>[...]</quote> pair of braces denotes an optional
            clause that may or may not be present.</para>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
276

277 278 279 280 281 282
            <para>Thus only the first part <quote><code language="java">if
            (booleanExpression) (block | statement)</code></quote> is
            mandatory.</para>
          </callout>
        </calloutlist>
      </figure>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
283

284 285
      <figure xml:id="sd1_fig_bestPracticeCompareEquals">
        <title>Best practices comparing for equality</title>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
286

287
        <para>Use</para>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
288

289
        <programlisting language="java">if (4 == variable) ...</programlisting>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
290

291 292
        <para>in favour of:</para>

293 294 295
        <programlisting language="java">if (variable == 4) ... <co
            linkends="sd1_fig_bestPracticeCompareEquals-1"
            xml:id="sd1_fig_bestPracticeCompareEquals-1-co"/></programlisting>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
296

297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
        <calloutlist role="slideExclude">
          <callout arearefs="sd1_fig_bestPracticeCompareEquals-1-co"
                   xml:id="sd1_fig_bestPracticeCompareEquals-1">
            <para>Some programming languages allow for interpreting integer
            values as logical expressions. In »C / C++« for example an
            <code>int</code> value of zero is equivalent to <code>false</code>
            and nonzero values evaluate to <code>true</code>. Consider the
            following snippet:</para>

            <programlisting language="c">if (variable = 4) {...} /* Just a single "=" rather then "==" */</programlisting>

            <para>A <xref linkend="glo_Java"/> compiler will flag this as a
            compile time error. On contrary in »C / C++« this is perfectly
            correct code: The term <code>variable = 4</code> having a nonzero
            value of 4 evaluates to <code>true</code> which in real code would
            most likely be a bug. Subject to choosing compiler warning options
            the possible damage may be mitigated depending on the observer's
            degree of pedantry.</para>

            <para>Changing the order however even in »C / C++« results in a
            compile time error since we cannot assign a value to a
            literal:</para>

            <programlisting language="java">if (4 == variable) {...}</programlisting>

            <para>We are thus able to avoid this type of error in the first
            place.</para>
          </callout>
        </calloutlist>
326
      </figure>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
327

328 329
      <qandaset defaultlabel="qanda" xml:id="sd1_qanda_betterSimpleMath">
        <title>Providing better display</title>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
330

331 332 333 334 335
        <qandadiv>
          <qandaentry>
            <question>
              <para>We reconsider <xref
              linkend="sd1_qanda_simpleMath"/>:</para>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
336

337 338 339
              <informaltable border="0">
                <tr>
                  <th>Source code</th>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
340

341 342 343 344 345
                  <th>Output</th>
                </tr>

                <tr>
                  <td valign="top"><programlisting language="java">int a = -4,
Dr. Martin Goik's avatar
Dr. Martin Goik committed
346 347 348 349
    b = 100;

System.out.println(a + "+" + b+ "=" + (a + b));</programlisting></td>

350 351 352
                  <td valign="top"><screen>-4+100=96</screen></td>
                </tr>
              </informaltable>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
353

354 355
              <para>Unfortunately changing the two variables' values
              yields:</para>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
356

357 358 359
              <informaltable border="0">
                <tr>
                  <th>Source code</th>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
360

361 362
                  <th>Output</th>
                </tr>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
363

364 365
                <tr>
                  <td valign="top"><programlisting language="java">int a = 100,
Dr. Martin Goik's avatar
Dr. Martin Goik committed
366 367 368 369
    b = -4;

System.out.println(a + "+" + b + "=" + (a + b));</programlisting></td>

370 371 372
                  <td valign="top"><screen>100+-4=96</screen></td>
                </tr>
              </informaltable>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
373

374 375 376
              <para>This result looks awkward. Modify the code to see
              <code>100-4=96</code> in such cases.</para>
            </question>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
377

378 379
            <answer>
              <para>The following simple solution does not work:</para>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
380

381 382 383
              <informaltable border="0">
                <tr>
                  <th>Source code</th>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
384

385 386
                  <th>Output</th>
                </tr>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
387

388 389
                <tr>
                  <td valign="top"><programlisting language="java">int a = 100,
Dr. Martin Goik's avatar
Dr. Martin Goik committed
390 391 392 393 394 395 396 397
    b = -4;

if (b &lt; 0) {
    System.out.println(a + b + "=" + (a + b));
  } else {
    System.out.println(a + "+" + b + "=" + (a + b));
}</programlisting></td>

398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
                  <td valign="top"><screen>96=96</screen></td>
                </tr>
              </informaltable>

              <para>Since <code language="java">a</code> and <code
              language="java">b</code> are both variables of type <code
              language="java">int</code> they get added rather than string
              style concatenated. Resolving this issue may be effected by
              adding an empty string <coref
              linkend="sd1_qanda_betterSimpleMathEmptyString-1-co"/> forcing
              <xref linkend="glo_Java"/> to use the concatenation
              <quote>+</quote> operator in favour of the arithmetic
              one:</para>

              <informaltable border="0">
                <tr>
                  <th>Source code</th>

                  <th>Output</th>
                </tr>

                <tr>
                  <td valign="top"><programlisting language="java">int a = 100,
Dr. Martin Goik's avatar
Dr. Martin Goik committed
421 422 423 424
    b = -4;

if (b &lt; 0) {
    System.out.println(a + "" <co
425
                        xml:id="sd1_qanda_betterSimpleMathEmptyString-1-co"/> + b+ "=" + (a + b));
Dr. Martin Goik's avatar
Dr. Martin Goik committed
426 427 428 429
  } else {
    System.out.println(a + "+" + b + "=" + (a + b));
}</programlisting></td>

430 431 432 433 434 435 436
                  <td valign="top"><screen>100-4=96</screen></td>
                </tr>
              </informaltable>
            </answer>
          </qandaentry>
        </qandadiv>
      </qandaset>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
437

438 439
      <qandaset defaultlabel="qanda" xml:id="sd1_qanda_booleanEqual">
        <title>Comparing for equality</title>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
440

441 442 443 444 445
        <qandadiv>
          <qandaentry>
            <question>
              <para>Copy the following snippet into your <xref
              linkend="glo_IDE"/>:</para>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
446

447
              <programlisting language="java">int count = 1;
Dr. Martin Goik's avatar
Dr. Martin Goik committed
448 449 450 451 452

if (count = 4) { // is count equal to 4?
  System.out.println("count is o.K.");
}</programlisting>

453 454
              <para>The <xref linkend="glo_Java"/> compiler will indicate an
              error:</para>
455

456
              <screen>Incompatible types.
457 458 459
Required: <emphasis role="red">boolean</emphasis>
Found: <emphasis role="red">int</emphasis></screen>

Dr. Martin Goik's avatar
Dr. Martin Goik committed
460 461
              <para>Explain its cause in detail by examining the <code
              language="java">count = 4</code> expression.</para>
462

463 464 465 466 467 468 469
              <tip>
                <para><xref linkend="glo_Java"/> provides two similar looking
                operators <code language="java">=</code> and <code
                language="java">==</code> having (totally) different
                semantics.</para>
              </tip>
            </question>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
470

471
            <answer>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
472 473 474
              <para>The two operators <code language="java">=</code> and <code
              language="java">==</code> are <emphasis>completely</emphasis>
              unrelated:</para>
475

476 477 478
              <glosslist>
                <glossentry>
                  <glossterm><code language="java">=</code></glossterm>
479

480 481 482 483 484 485 486 487 488 489 490 491 492 493 494
                  <glossdef>
                    <para>This is being called the assignment operator. A
                    typical statement reads <code language="java">a =
                    34</code> assigning the <code language="java">int</code>
                    value <code language="java">34</code> to a variable <code
                    language="java">a</code>.</para>

                    <para>Note this operator's semantics being completely
                    different from even elementary math syntax.
                    Consider:</para>

                    <informalequation>
                      <m:math display="block">
                        <m:mrow>
                          <m:mi>x</m:mi>
495

496
                          <m:mo>=</m:mo>
497

498 499
                          <m:mi>y</m:mi>
                        </m:mrow>
500

501
                        <m:mo></m:mo>
502

503 504 505
                        <m:mrow>
                          <m:msup>
                            <m:mi>x</m:mi>
506

507 508
                            <m:mi>2</m:mi>
                          </m:msup>
509

510
                          <m:mo>=</m:mo>
511

512 513
                          <m:msup>
                            <m:mi>y</m:mi>
514

515 516 517 518 519
                            <m:mi>2</m:mi>
                          </m:msup>
                        </m:mrow>
                      </m:math>
                    </informalequation>
520

521 522 523
                    <para>In math <quote>=</quote> denotes the equality of
                    objects <abbrev>e.g.</abbrev> values, sets, functions and
                    so on.</para>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
524 525 526 527 528 529 530

                    <para>More formally the expression <code
                    language="java">count = 4</code> is of type <code
                    language="java">int</code> evaluating to 4 (surprise!).
                    However an <code language="java">if (...)</code> operates
                    on <code language="java">boolean</code> values only. We
                    thus must not supply expressions of any other type.</para>
531 532 533 534 535
                  </glossdef>
                </glossentry>

                <glossentry>
                  <glossterm><code language="java">==</code></glossterm>
536

537 538 539 540 541 542 543 544 545 546 547 548 549 550 551
                  <glossdef>
                    <para>The comparison operator matching the usual math
                    semantics comparing:</para>

                    <itemizedlist>
                      <listitem>
                        <para><xref linkend="glo_Java"/> primitive types for
                        equality of value.</para>
                      </listitem>

                      <listitem>
                        <para><xref linkend="glo_Java"/> objects for
                        identity.</para>
                      </listitem>
                    </itemizedlist>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
552 553 554 555 556

                    <para>In particular an expression like <code
                    language="java">count == 4</code> is of type boolean:
                    Either <code language="java">true</code> or <code
                    language="java">false</code>.</para>
557 558 559 560
                  </glossdef>
                </glossentry>
              </glosslist>

Dr. Martin Goik's avatar
Dr. Martin Goik committed
561
              <para>Thus <code language="java">count = 4</code> is an
562 563 564 565
              expression evaluating to 4. So the code in question may be
              re-written as:</para>

              <programlisting language="java">int count = 1;
Dr. Martin Goik's avatar
Dr. Martin Goik committed
566

Dr. Martin Goik's avatar
Dr. Martin Goik committed
567
int countAssignment = (count = 4); // Assigning expression count = 4 to variable countAssignment.
568

Dr. Martin Goik's avatar
Dr. Martin Goik committed
569
if (countAssignment) { <emphasis role="red">// Error: An int is not a boolean!</emphasis>
570 571 572
  System.out.println("count is o.K.");
}</programlisting>

573 574
              <para>Since the assignment operator is being evaluated from
              right to left we do not need braces:</para>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
575

576
              <programlisting language="java">...
Dr. Martin Goik's avatar
Dr. Martin Goik committed
577 578 579
int countAssignment = count = 4; // Assigning expression count = 4 to variable countAssignment
...</programlisting>

580 581 582 583 584 585
              <para>This code is equivalent to its counterpart with respect to
              compilation. The comment <quote>is count equal to 4?</quote> is
              thus misleading: The intended comparison requires using the
              <quote>==</quote> operator rather than an assignment operator
              <quote>=</quote>. Changing it the resulting expression is indeed
              of type <code language="java">boolean</code>:</para>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
586

587
              <programlisting language="java">int count = 4 + 3;
Dr. Martin Goik's avatar
Dr. Martin Goik committed
588 589 590
final boolean test = (count == 4); // Now using "==" (comparison) in favour of "=" (assignment)
System.out.println("test=" + test);</programlisting>

591
              <para>Again we may omit braces here:</para>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
592

593
              <programlisting language="java">...
Dr. Martin Goik's avatar
Dr. Martin Goik committed
594 595 596
final boolean test = count == 4; // Now using "==" (comparison) in favour of "=" (assignment)
...</programlisting>

597 598 599 600 601 602
              <para>The <code language="java">boolean</code> variable <code
              language="java">test</code> will receive a value of <code
              language="java">false</code> as expected. Thus our initial code
              just needs a tiny modification replacing the assignment operator
              «<code language="java">=</code>» by the comparison operator
              «<code language="java">==</code>»:</para>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
603

604
              <programlisting language="java">int count = 1;
Dr. Martin Goik's avatar
Dr. Martin Goik committed
605 606 607 608 609

if (count == 4) { // is count equal to 4?
  System.out.println("count is o.K.");
}</programlisting>

610 611 612 613
              <note xml:id="sd1_note_useLiteralEqualsVariable">
                <para>In contrast to <xref linkend="glo_Java"/> some
                programming languages like C and C++ allow for integer values
                in <code language="java">if (...)</code> conditionals:</para>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
614

615
                <programlisting language="c">#include &lt;stdio.h&gt;
Dr. Martin Goik's avatar
Dr. Martin Goik committed
616 617 618 619 620

int main(int argc, char **args) {

  int a = 3;
  if (a = 4) {
621
     printf("a has got a value of 4\n");
Dr. Martin Goik's avatar
Dr. Martin Goik committed
622 623 624
  }
}</programlisting>

625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681
                <para>The integer expression <code language="java">count =
                4</code> has got a value of 4. Integer values inside an <code
                language="java">if (...)</code> statement will be evaluated
                as:</para>

                <glosslist>
                  <glossentry>
                    <glossterm>true</glossterm>

                    <glossdef>
                      <para>if the expression's value differs from zero</para>
                    </glossdef>
                  </glossentry>

                  <glossentry>
                    <glossterm>false</glossterm>

                    <glossdef>
                      <para>if the expression's value equals zero</para>
                    </glossdef>
                  </glossentry>
                </glosslist>

                <para>Thus in C and C++ the expression <code
                language="java">if(count = 4)</code> will always evaluate to
                <code language="java">true</code> irrespective of the variable
                <code language="java">count</code>'s initial value. Most
                important: The C compiler will not issue an error or warning
                unless non-default, more restrictive compile time warning
                options are being activated. Consider this widely used
                «feature» to be dangerous at best.</para>

                <para>For this reason it is good practice always using <code
                language="java">if (4 == count)</code> rather than <code
                language="java">if (count == 4)</code>: Even in C you cannot
                assign a value to a constant literal. Thus an accidentally
                mistyped <code language="java">if (4 = count)</code> statement
                will definitively result in a compile time error most likely
                saving its author from tedious debugging.</para>
              </note>
            </answer>
          </qandaentry>
        </qandadiv>
      </qandaset>

      <qandaset defaultlabel="qanda" xml:id="sd1_qanda_replaceElseIf">
        <title>Replacing <code language="java">else if (...){...}</code> by
        nested <code language="java">if ... else</code> statements</title>

        <qandadiv>
          <qandaentry>
            <question>
              <para>A computer newbie did not yet read about the <code
              language="java">else if(...)</code> branch construct but
              nevertheless tries to implement the following logic:</para>

              <programlisting language="java">if (a &lt; 7) {
Dr. Martin Goik's avatar
Dr. Martin Goik committed
682 683 684 685 686 687 688
  System.out.println("o.K.");
} else if (b == 5) {
  System.out.println("Maybe");
} else {
  System.out.println("Wrong!");
}</programlisting>

689 690 691 692
              <para><code language="java">a</code> and <code
              language="java">b</code> are supposed to be <code
              language="java">int</code> variables. Please help our newbie
              using just <code language="java">if(...){...} else {...} </code>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
693 694
              avoiding <code language="java"><emphasis role="red">else
              if</emphasis>(...) {}</code> branch statements!</para>
695 696 697 698 699 700 701 702 703 704 705

              <tip>
                <para>As the title suggests you may want to nest an
                <quote>inner</quote> <code language="java">if(...)</code>
                inside an <quote>outer</quote> one.</para>
              </tip>
            </question>

            <answer>
              <para>The solution requires replacing the <code
              language="java">else if(...)</code> branch by a nested <code
Dr. Martin Goik's avatar
Dr. Martin Goik committed
706 707 708
              language="java">if(...){ ...} else {...}</code> statement by
              moving the final <code language="java">else</code> block into
              the nested one.</para>
709 710

              <programlisting language="java">if (a &lt; 7) {
Dr. Martin Goik's avatar
Dr. Martin Goik committed
711
    System.out.println("o.K.");
Dr. Martin Goik's avatar
Dr. Martin Goik committed
712
} else {
Dr. Martin Goik's avatar
Dr. Martin Goik committed
713 714 715 716
    if (b == 5) {
        System.out.println("Maybe");
    } else {
        System.out.println("Wrong!");
Dr. Martin Goik's avatar
Dr. Martin Goik committed
717 718
    }
}</programlisting>
719 720 721 722
            </answer>
          </qandaentry>
        </qandadiv>
      </qandaset>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
723

724 725
      <figure xml:id="sd1_fig_IfOmitBlocks">
        <title>Single statement branches</title>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
726

727
        <programlisting language="java">double initialAmount = 3200;
Dr. Martin Goik's avatar
Dr. Martin Goik committed
728

Dr. Martin Goik's avatar
Dr. Martin Goik committed
729
if (100000 &lt;= initialAmount)
Dr. Martin Goik's avatar
Dr. Martin Goik committed
730 731 732
  System.out.println("Interest:" + 1.2 * initialAmount / 100);
else if (1000 &lt;= initialAmount)
  System.out.println("Interest:" + 0.8 * initialAmount / 100);
Dr. Martin Goik's avatar
Dr. Martin Goik committed
733
else
Dr. Martin Goik's avatar
Dr. Martin Goik committed
734 735
  System.out.println("Interest:" + 0);</programlisting>

736 737 738
        <para>Branches containing exactly one statement don't require a block
        definition.</para>
      </figure>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
739

740 741
      <figure xml:id="sd1_fig_corporateSafety">
        <title>Aside: Corporate network security</title>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
742

743 744
        <para>Would you access your online bank account using <emphasis
        role="bold">Stuttgart Media University's</emphasis> network?</para>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
745

746 747 748 749
        <orderedlist>
          <listitem>
            <para>Yes</para>
          </listitem>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
750

751 752 753 754
          <listitem>
            <para>Only on private equipment (Smart phone, tablet, laptop,
            ...)</para>
          </listitem>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
755

756 757 758 759 760
          <listitem>
            <para>Never!</para>
          </listitem>
        </orderedlist>
      </figure>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
761

762 763
      <figure xml:id="sd1_fig_onlineBanking">
        <title>Online banking</title>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
764

765 766 767 768 769 770
        <mediaobject>
          <imageobject>
            <imagedata fileref="Ref/Statements/onlineBanking.svg"/>
          </imageobject>
        </mediaobject>
      </figure>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
771

772
      <figure xml:id="sd1_fig_ipSpoofing">
Dr. Martin Goik's avatar
Dr. Martin Goik committed
773
        <title><xref linkend="glo_DNS"/> Spoofing</title>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
774

775 776 777 778 779 780
        <mediaobject>
          <imageobject>
            <imagedata fileref="Ref/Statements/dns-spoofing.png"/>
          </imageobject>
        </mediaobject>
      </figure>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
781

782 783
      <figure xml:id="sd1_fig_getIpToDns">
        <title>Turn <xref linkend="glo_DNS"/> name into IP address</title>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
784

785
        <informaltable border="0">
Dr. Martin Goik's avatar
Dr. Martin Goik committed
786
          <col width="37%"/>
787

Dr. Martin Goik's avatar
Dr. Martin Goik committed
788
          <col width="63%"/>
789

790 791
          <tr>
            <td valign="top"><screen>~&gt; nslookup 
Dr. Martin Goik's avatar
Dr. Martin Goik committed
792
&gt; server <emphasis role="red">141.62.1.5</emphasis> <co
793 794
                  linkends="sd1_fig_getIpToDns-1"
                  xml:id="sd1_fig_getIpToDns-1-co"/>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
795 796 797
Address: 141.62.1.5#53
&gt; 
&gt; <emphasis role="red">meine.deutsche-bank.de</emphasis> <co
798 799
                  linkends="sd1_fig_getIpToDns-2"
                  xml:id="sd1_fig_getIpToDns-2-co"/>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
800 801 802 803 804 805
Server:    141.62.1.5
Address:   141.62.1.5#53

Non-authoritative answer:
Name:   meine.deutsche-bank.de
Address: <emphasis role="red">129.35.230.2</emphasis> <co
806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834
                  linkends="sd1_fig_getIpToDns-3"
                  xml:id="sd1_fig_getIpToDns-3-co"/></screen></td>

            <td valign="top"><calloutlist>
                <callout arearefs="sd1_fig_getIpToDns-1-co"
                         role="slideExclude" xml:id="sd1_fig_getIpToDns-1">
                  <para>Nameserver answering <xref linkend="glo_DNS"/>
                  queries.</para>
                </callout>

                <callout arearefs="sd1_fig_getIpToDns-2-co"
                         xml:id="sd1_fig_getIpToDns-2">
                  <para>Entering <xref linkend="glo_DNS"/> name.</para>
                </callout>

                <callout arearefs="sd1_fig_getIpToDns-3-co"
                         xml:id="sd1_fig_getIpToDns-3">
                  <para>IP address of <uri>meine.deutsche-bank.de</uri> is
                  <code>129.35.230.2</code>.</para>

                  <para>Caution: This IP value may become subject to
                  tampering.</para>
                </callout>
              </calloutlist></td>
          </tr>
        </informaltable>
      </figure>

      <figure xml:id="sd1_fig_SSLCertificateError">
Dr. Martin Goik's avatar
Dr. Martin Goik committed
835
        <title><xref linkend="glo_SSL"/> Certificate error</title>
836 837 838 839 840 841 842 843 844 845 846 847 848 849

        <mediaobject>
          <imageobject>
            <imagedata fileref="Ref/Statements/sslCertificateError.svg"/>
          </imageobject>
        </mediaobject>
      </figure>

      <figure xml:id="sd1_fig_IfOmitBewareIndent">
        <title>The <link
        xlink:href="https://nakedsecurity.sophos.com/2014/02/24/anatomy-of-a-goto-fail-apples-ssl-bug-explained-plus-an-unofficial-patch/">Apple
        <quote><code>goto fail</code></quote> SSL bug</link></title>

        <programlisting language="c">static OSStatus SSLVerifySignedServerKeyExchange(SSLContext *ctx, bool isRsa,
Dr. Martin Goik's avatar
Dr. Martin Goik committed
850
       SSLBuffer signedParams, uint8_t *signature, UInt16 signatureLen) {
851 852 853 854 855 856 857 858 859 860 861 862
  OSStatus        err;
  ...
  if ((err = SSLHashSHA1.update(&amp;hashCtx, &amp;serverRandom)) != 0)
    goto fail;
  if ((err = SSLHashSHA1.update(&amp;hashCtx, &amp;signedParams)) != 0)
    goto fail;
    goto fail;
  if ((err = SSLHashSHA1.final(&amp;hashCtx, &amp;hashOut)) != 0)
    goto fail;

  err = sslRawVerify(...);
  ...
Dr. Martin Goik's avatar
Dr. Martin Goik committed
863
fail:
864 865 866
  SSLFreeBuffer(&amp;signedHashes);
  SSLFreeBuffer(&amp;hashCtx);
  return err;                   }</programlisting>
867
      </figure>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
868

869 870
      <figure xml:id="sd1_fig_appleSslBugCodeReachability">
        <title>Static code analysis</title>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
871

872 873 874
        <informaltable border="0">
          <tr>
            <td><programlisting language="c">if ((err = SSLHashSHA1.update(...)) != 0)
Dr. Martin Goik's avatar
Dr. Martin Goik committed
875 876 877
  goto fail;
  goto fail;</programlisting></td>

878 879
            <td>Reachable code, <code>err</code> yet 0</td>
          </tr>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
880

881 882
          <tr>
            <td><programlisting language="c">if ((err = SSLHashSHA1.final(...)) != 0)
Dr. Martin Goik's avatar
Dr. Martin Goik committed
883 884
  goto fail;

885
err = sslRawVerify(...);  ...</programlisting></td>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
886

887 888 889
            <td>Unreachable code: Variable <code language="java">err</code>
            unchanged.</td>
          </tr>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
890

891 892
          <tr>
            <td><programlisting language="c">fail:
Dr. Martin Goik's avatar
Dr. Martin Goik committed
893 894
  SSLFreeBuffer(&amp;signedHashes);
  SSLFreeBuffer(&amp;hashCtx);
Dr. Martin Goik's avatar
Dr. Martin Goik committed
895
  return err;</programlisting></td>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
896

897 898 899 900
            <td>Reachable code, <code>err</code> possibly still 0</td>
          </tr>
        </informaltable>
      </figure>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
901

902 903 904 905
      <figure xml:id="sd1_fig_ifElseNested">
        <title>Nested <code language="java">if ... else</code></title>

        <informaltable border="1">
Dr. Martin Goik's avatar
Dr. Martin Goik committed
906 907 908 909
          <col width="40%"/>

          <col width="60%"/>

910 911
          <tr>
            <td valign="top"><programlisting language="java">if ('A' == grade || 'B' == grade) {
912 913 914 915 916 917 918 919 920 921 922 923 924
   result = "Excellent";
} else {
   if ('C' == grade) {
      result = "O.k.";
   } else {
      if ('D' == grade) {
         result = "Passed";
      } else {
         result = "Failed";
      }
   }
}</programlisting></td>

925 926 927 928 929 930 931 932 933 934 935 936 937 938
            <td valign="top"><mediaobject>
                <imageobject>
                  <imagedata fileref="Ref/Statements/if_elseIf_else.svg"/>
                </imageobject>
              </mediaobject></td>
          </tr>
        </informaltable>
      </figure>
    </section>

    <section xml:id="sd1_sect_elseif">
      <title>Using <code language="java">else if</code></title>

      <figure xml:id="sd1_fig_ifElse_else">
Dr. Martin Goik's avatar
Dr. Martin Goik committed
939
        <title>Enhanced readability: <code language="java">if ... else if ...
940 941 942
        else</code></title>

        <informaltable border="1">
Dr. Martin Goik's avatar
Dr. Martin Goik committed
943 944 945 946
          <col width="40%"/>

          <col width="60%"/>

947 948
          <tr>
            <td valign="top"><programlisting language="java">if ('A' == grade || 'B' == grade) {
949 950 951 952 953 954 955 956 957
   result = "Excellent";
} else if ('C' == grade) {
   result = "O.k.";
} else if ('D' == grade) {
   result = "Passed";
} else {
   result = "Failed";
}</programlisting></td>

958 959 960 961 962 963 964 965
            <td valign="top"><mediaobject>
                <imageobject>
                  <imagedata fileref="Ref/Statements/if_elseIf_else.svg"/>
                </imageobject>
              </mediaobject></td>
          </tr>
        </informaltable>
      </figure>
966

967 968 969
      <figure xml:id="sd1_fig_ifElse_elseSyntax">
        <title><code language="java">if ... else if ... else</code>
        syntax</title>
970

971
        <programlisting language="java">if (booleanExpression)
972
   (block | statement)
973 974
[else if (booleanExpression)
   (block | statement) ]* <co linkends="sd1_fig_ifElse_elseSyntax-1"
975
            xml:id="sd1_fig_ifElse_elseSyntax-1-co"/>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
976
[else
977
  (block | statement) ] <co linkends="sd1_fig_ifElse_elseSyntax-2"
978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003
            xml:id="sd1_fig_ifElse_elseSyntax-2-co"/></programlisting>

        <calloutlist role="slideExclude">
          <callout arearefs="sd1_fig_ifElse_elseSyntax-1-co"
                   xml:id="sd1_fig_ifElse_elseSyntax-1">
            <para>The pair of braces [...] indicates an optional clause. The
            asterisk <quote>*</quote> indicates an arbitrary number of
            repetitions (zero to infinity).</para>
          </callout>

          <callout arearefs="sd1_fig_ifElse_elseSyntax-2-co"
                   xml:id="sd1_fig_ifElse_elseSyntax-2">
            <para>The second pair of braces [...] again indicates an optional
            clause.</para>

            <para>Thus only the <quote><code language="java">if
            (booleanExpression) (block | statement)</code></quote> clause is
            mandatory.</para>
          </callout>
        </calloutlist>
      </figure>

      <figure xml:id="sd1_fig_useScannerClass">
        <title>User input recipe</title>

        <informaltable border="0">
Dr. Martin Goik's avatar
Dr. Martin Goik committed
1004
          <col width="64%"/>
1005

Dr. Martin Goik's avatar
Dr. Martin Goik committed
1006
          <col width="36%"/>
1007 1008 1009

          <tr>
            <td valign="top"><programlisting language="java">import java.util.Scanner;
1010 1011 1012 1013 1014
public class App {
  public static void main(String[] args){

    try (final Scanner scan = 
       new Scanner(System.in)) {
Dr. Martin Goik's avatar
Dr. Martin Goik committed
1015

1016
      System.out.print("Enter a value:");
Dr. Martin Goik's avatar
Dr. Martin Goik committed
1017

1018
      final int value = scan.nextInt();
Dr. Martin Goik's avatar
Dr. Martin Goik committed
1019

1020 1021 1022 1023 1024
      System.out.println(
         "You entered " + value);
    }
  }
}</programlisting></td>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
1025

1026
            <td valign="top"><screen>Enter a value:123
1027
You entered 123</screen><para>See <methodname
1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041
            xlink:href="https://docs.oracle.com/javase/10/docs/api/java/util/Scanner.html#nextBoolean()">nextBoolean()</methodname>,
            <methodname><link
            xlink:href="https://docs.oracle.com/javase/10/docs/api/java/util/Scanner.html#nextByte()">nextByte()</link></methodname>
            and friends.</para></td>
          </tr>
        </informaltable>
      </figure>

      <qandaset defaultlabel="qanda" xml:id="sw1QandaPostExamBonuspoints">
        <title>Post modifying an exam's marking</title>

        <qandadiv>
          <qandaentry>
            <question>
Dr. Martin Goik's avatar
Dr. Martin Goik committed
1042 1043 1044 1045 1046 1047
              <para>A lecturer marks an exam having a maximum of 12 reachable
              points:</para>

              <informaltable border="1" width="50%">
                <tr>
                  <th>Name</th>
1048

Dr. Martin Goik's avatar
Dr. Martin Goik committed
1049 1050 1051 1052 1053
                  <th>Mark</th>
                </tr>

                <tr>
                  <td>Aaron</td>
1054

Dr. Martin Goik's avatar
Dr. Martin Goik committed
1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121
                  <td>3</td>
                </tr>

                <tr>
                  <td>Maureen</td>

                  <td>11</td>
                </tr>

                <tr>
                  <td>Sally</td>

                  <td>1</td>
                </tr>

                <tr>
                  <td>...</td>

                  <td>...</td>
                </tr>
              </informaltable>

              <para>The lecturer is dissatisfied with the overall result. He
              wants to add 3 bonus points but still keeping the maximum of 12
              points to be reachable:</para>

              <informaltable border="1" width="50%">
                <tr>
                  <th>Name</th>

                  <th>Mark</th>

                  <th>3 bonus points augmented mark</th>
                </tr>

                <tr>
                  <td>Aaron</td>

                  <td>3</td>

                  <td>6</td>
                </tr>

                <tr>
                  <td>Maureen</td>

                  <td>11</td>

                  <td><emphasis role="red">12</emphasis></td>
                </tr>

                <tr>
                  <td>Sally</td>

                  <td>1</td>

                  <td>4</td>
                </tr>

                <tr>
                  <td>...</td>

                  <td>...</td>

                  <td>...</td>
                </tr>
              </informaltable>
1122 1123 1124 1125 1126 1127

              <para>Complete the following code by assigning this modified
              number of points to the variable <code
              language="java">newResult</code>.</para>

              <programlisting language="java">public static void main(String[] args) {
Dr. Martin Goik's avatar
Dr. Martin Goik committed
1128

Dr. Martin Goik's avatar
Dr. Martin Goik committed
1129 1130 1131 1132 1133
  int mark = 1;  // May range from 0 to 12 points


  final int maximumPoints = 12;
  final int pointsToAdd = 3;
Dr. Martin Goik's avatar
Dr. Martin Goik committed
1134

Dr. Martin Goik's avatar
Dr. Martin Goik committed
1135
  final int augmentedMark;
Dr. Martin Goik's avatar
Dr. Martin Goik committed
1136

Dr. Martin Goik's avatar
Dr. Martin Goik committed
1137
  // TODO: Assignment to variable augmentedMark
Dr. Martin Goik's avatar
Dr. Martin Goik committed
1138

Dr. Martin Goik's avatar
Dr. Martin Goik committed
1139
  System.out.println("New marking:" + augmentedMark);
1140
}</programlisting>
1141
            </question>
1142

1143 1144 1145 1146 1147
            <answer>
              <para>The basic task is to add up the values of <code
              language="java">pointsReached</code> and <code
              language="java">pointsToAdd</code>. When exceeding the limit we
              just assign the limit itself:</para>
1148

1149
              <programlisting language="java">public static void main(String[] args) {
Dr. Martin Goik's avatar
Dr. Martin Goik committed
1150

1151 1152 1153
  final int pointsReached = 1;
  final int maximumPoints = 12;
  final int pointsToAdd = 3;
Dr. Martin Goik's avatar
Dr. Martin Goik committed
1154

Dr. Martin Goik's avatar
Dr. Martin Goik committed
1155
  final int augmentedMark;
Dr. Martin Goik's avatar
Dr. Martin Goik committed
1156

1157
  if (maximumPoints &lt;= pointsReached + pointsToAdd) {
Dr. Martin Goik's avatar
Dr. Martin Goik committed
1158
    augmentedMark = maximumPoints;
1159
  } else {
Dr. Martin Goik's avatar
Dr. Martin Goik committed
1160
    augmentedMark = pointsReached + pointsToAdd;
1161
  }
Dr. Martin Goik's avatar
Dr. Martin Goik committed
1162

Dr. Martin Goik's avatar
Dr. Martin Goik committed
1163
  System.out.println("New marking:" + augmentedMark);
1164
}</programlisting>
1165

Dr. Martin Goik's avatar
Dr. Martin Goik committed
1166 1167 1168 1169
              <para>The augmented marks equal the minimum of <code
              language="java">(pointsReached + pointsToAdd</code>) and <code
              language="java">maximumPoints</code>. We may thus code as
              well:</para>
1170

1171
              <programlisting language="java">public static void main(String[] args) {
Dr. Martin Goik's avatar
Dr. Martin Goik committed
1172

1173 1174 1175
  final int pointsReached = 1;
  final int maximumPoints = 12;
  final int pointsToAdd = 3;
Dr. Martin Goik's avatar
Dr. Martin Goik committed
1176

Dr. Martin Goik's avatar
Dr. Martin Goik committed
1177
  final int augmentedMark = <link
1178
                  xlink:href="https://docs.oracle.com/javase/10/docs/api/java/lang/Math.html#min(int,int)">Math.min</link>(maximumPoints, pointsReached + pointsToAdd);