-
Notifications
You must be signed in to change notification settings - Fork 0
/
io-conditionals-strings.html
2064 lines (1945 loc) · 215 KB
/
io-conditionals-strings.html
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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
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
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
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
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en" data-theme="light">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="generator" content="Docutils 0.18.1: http://docutils.sourceforge.net/" />
<title>Module 2, Part 2: Console I/O, Conditionals, Strings — 02312 Introductory Programming — Fall 2024</title>
<script data-cfasync="false">
document.documentElement.dataset.mode = localStorage.getItem("mode") || "light";
document.documentElement.dataset.theme = localStorage.getItem("theme") || "light";
</script>
<!-- Loaded before other Sphinx assets -->
<link href="_static/styles/theme.css?digest=e353d410970836974a52" rel="stylesheet" />
<link href="_static/styles/bootstrap.css?digest=e353d410970836974a52" rel="stylesheet" />
<link href="_static/styles/pydata-sphinx-theme.css?digest=e353d410970836974a52" rel="stylesheet" />
<link href="_static/vendor/fontawesome/6.1.2/css/all.min.css?digest=e353d410970836974a52" rel="stylesheet" />
<link rel="preload" as="font" type="font/woff2" crossorigin href="_static/vendor/fontawesome/6.1.2/webfonts/fa-solid-900.woff2" />
<link rel="preload" as="font" type="font/woff2" crossorigin href="_static/vendor/fontawesome/6.1.2/webfonts/fa-brands-400.woff2" />
<link rel="preload" as="font" type="font/woff2" crossorigin href="_static/vendor/fontawesome/6.1.2/webfonts/fa-regular-400.woff2" />
<link rel="stylesheet" type="text/css" href="_static/pygments.css" />
<link rel="stylesheet" href="_static/styles/sphinx-book-theme.css?digest=14f4ca6b54d191a8c7657f6c759bf11a5fb86285" type="text/css" />
<link rel="stylesheet" type="text/css" href="_static/exercise.css" />
<link rel="stylesheet" type="text/css" href="_static/proof.css" />
<link rel="stylesheet" type="text/css" href="_static/copybutton.css" />
<link rel="stylesheet" type="text/css" href="_static/tabs.css" />
<link rel="stylesheet" type="text/css" href="_static/custom.css" />
<!-- Pre-loaded scripts that we'll load fully later -->
<link rel="preload" as="script" href="_static/scripts/bootstrap.js?digest=e353d410970836974a52" />
<link rel="preload" as="script" href="_static/scripts/pydata-sphinx-theme.js?digest=e353d410970836974a52" />
<script data-url_root="./" id="documentation_options" src="_static/documentation_options.js"></script>
<script src="_static/doctools.js"></script>
<script src="_static/sphinx_highlight.js"></script>
<script src="_static/clipboard.min.js"></script>
<script src="_static/copybutton.js"></script>
<script src="_static/scripts/sphinx-book-theme.js?digest=5a5c038af52cf7bc1a1ec88eea08e6366ee68824"></script>
<script src="_static/proof/proof.js"></script>
<script>window.MathJax = {"loader": {"load": ["[tex]/bussproofs"]}, "tex": {"packages": {"[+]": ["bussproofs"]}, "macros": {}}, "options": {"processHtmlClass": "tex2jax_process|mathjax_process|math|output_area"}}</script>
<script defer="defer" src="_static/mathjax/es5/tex-svg.js"></script>
<link rel="icon" href="_static/favicon.ico"/>
<link rel="index" title="Index" href="genindex.html" />
<link rel="search" title="Search" href="search.html" />
<link rel="next" title="Module 3, Part 1: Lab Day" href="lab-day-1.html" />
<link rel="prev" title="Module 2, Part 1: a First Taste of Java" href="java-first-taste.html" />
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<meta name="docsearch:language" content="en"/>
</head>
<body data-bs-spy="scroll" data-bs-target=".bd-toc-nav" data-offset="180" data-bs-root-margin="0px 0px -60%" data-default-mode="light">
<a class="skip-link" href="#main-content">Skip to main content</a>
<input type="checkbox"
class="sidebar-toggle"
name="__primary"
id="__primary"/>
<label class="overlay overlay-primary" for="__primary"></label>
<input type="checkbox"
class="sidebar-toggle"
name="__secondary"
id="__secondary"/>
<label class="overlay overlay-secondary" for="__secondary"></label>
<div class="search-button__wrapper">
<div class="search-button__overlay"></div>
<div class="search-button__search-container">
<form class="bd-search d-flex align-items-center"
action="search.html"
method="get">
<i class="fa-solid fa-magnifying-glass"></i>
<input type="search"
class="form-control"
name="q"
id="search-input"
placeholder="Search..."
aria-label="Search..."
autocomplete="off"
autocorrect="off"
autocapitalize="off"
spellcheck="false"/>
<span class="search-button__kbd-shortcut"><kbd class="kbd-shortcut__modifier">Ctrl</kbd>+<kbd>K</kbd></span>
</form></div>
</div>
<nav class="bd-header navbar navbar-expand-lg bd-navbar">
</nav>
<div class="bd-container">
<div class="bd-container__inner bd-page-width">
<div class="bd-sidebar-primary bd-sidebar">
<div class="sidebar-header-items sidebar-primary__section">
</div>
<div class="sidebar-primary-items__start sidebar-primary__section">
<div class="sidebar-primary-item">
<a class="navbar-brand logo" href="index.html">
<img src="_static/dtu.png" class="logo__image only-light" alt="Logo image"/>
<script>document.write(`<img src="_static/dtu.png" class="logo__image only-dark" alt="Logo image"/>`);</script>
</a></div>
<div class="sidebar-primary-item"><nav class="bd-links" id="bd-docs-nav" aria-label="Main">
<div class="bd-toc-item navbar-nav active">
<p aria-level="2" class="caption" role="heading"><span class="caption-text">Contents</span></p>
<ul class="current nav bd-sidenav">
<li class="toctree-l1"><a class="reference internal" href="overview.html">Module 0: Overview of the Course and Assessment</a></li>
<li class="toctree-l1"><a class="reference internal" href="basic-programming.html">Module 1: Basic Notions of Computing and Programming</a></li>
<li class="toctree-l1"><a class="reference internal" href="java-first-taste.html">Module 2, Part 1: a First Taste of Java</a></li>
<li class="toctree-l1 current active"><a class="current reference internal" href="#">Module 2, Part 2: Console I/O, Conditionals, Strings</a></li>
<li class="toctree-l1"><a class="reference internal" href="lab-day-1.html">Module 3, Part 1: Lab Day</a></li>
<li class="toctree-l1"><a class="reference internal" href="loops.html">Module 3, Part 2: Loops</a></li>
<li class="toctree-l1"><a class="reference internal" href="loops2.html">Module 4, Part 1: More About Loops</a></li>
<li class="toctree-l1"><a class="reference internal" href="structured.html">Module 4, Part 2: Structured Programming</a></li>
<li class="toctree-l1"><a class="reference internal" href="arrays.html">Module 5, Part 1: Arrays</a></li>
<li class="toctree-l1"><a class="reference internal" href="lab-day-2.html">Module 5, Part 2: Lab Day</a></li>
<li class="toctree-l1"><a class="reference internal" href="simple-classes.html">Module 6, Part 1: Simple Classes and Objects</a></li>
<li class="toctree-l1"><a class="reference internal" href="arrays-simple-classes-2.html">Module 6, Part 2: More About Arrays and Objects</a></li>
<li class="toctree-l1"><a class="reference internal" href="lab-day-3.html">Module 7, Part 1: Lab Day</a></li>
<li class="toctree-l1"><a class="reference internal" href="references-null.html">Module 7, Part 2: References, <code class="docutils literal notranslate"><span class="pre">null</span></code> values, and the <code class="docutils literal notranslate"><span class="pre">NullPointerException</span></code></a></li>
<li class="toctree-l1"><a class="reference internal" href="prog-interf-encapsulation.html">Module 8, Part 1: Programming Interfaces and Encapsulation</a></li>
<li class="toctree-l1"><a class="reference internal" href="interfaces.html">Module 8, Part 2: Java <code class="docutils literal notranslate"><span class="pre">interface</span></code>s</a></li>
<li class="toctree-l1"><a class="reference internal" href="lab-day-4.html">Module 9, Part 1: Lab Day</a></li>
<li class="toctree-l1"><a class="reference internal" href="inheritance-oo.html">Module 9, Part 2: Class Inheritance and Principles of Object-Oriented Programming</a></li>
<li class="toctree-l1"><a class="reference internal" href="inheritance-2.html">Module 10, part 1: More on Class Inheritance and <code class="docutils literal notranslate"><span class="pre">abstract</span> <span class="pre">class</span></code>es</a></li>
<li class="toctree-l1"><a class="reference internal" href="classes-polymorphism.html">Module 10, Part 2: More on Java Classes and Polymorphism</a></li>
<li class="toctree-l1"><a class="reference internal" href="lab-day-5.html">Module 11, Part 1: Lab Day</a></li>
<li class="toctree-l1"><a class="reference internal" href="errors.html">Module 11, Part 2: Error Handling with Exceptions</a></li>
<li class="toctree-l1"><a class="reference internal" href="files.html">Module 12, Part 1: File I/O</a></li>
<li class="toctree-l1"><a class="reference internal" href="projects.html">Module 12, Part 2: Managing Java Projects: Packages, JAR Files, Build Tools</a></li>
<li class="toctree-l1"><a class="reference internal" href="lab-day-6.html">Module 13, Part 1: Lab Day — Exam Simulation</a></li>
<li class="toctree-l1"><a class="reference internal" href="exam-qa-lab.html">Module 13, Part 2: Exam Q&A, Review, and Final Lab</a></li>
<li class="toctree-l1"><a class="reference internal" href="changelog.html">ChangeLog</a></li>
<li class="toctree-l1"><a class="reference internal" href="jgrader.html">Appendix: Information About JGrader</a></li>
</ul>
</div>
</nav></div>
</div>
<div class="sidebar-primary-items__end sidebar-primary__section">
<div class="sidebar-primary-item"><nav class="sidebar-indices-items">
<p class="sidebar-indices-items__title" role="heading" aria-level="1">Indices</p>
<ul class="indices-link">
<li class="toctree-l1">
<a class="reference internal"
href="genindex.html"
accesskey="I">General Index</a>
</li>
</ul>
</nav></div>
</div>
<div id="rtd-footer-container"></div>
</div>
<main id="main-content" class="bd-main">
<div class="sbt-scroll-pixel-helper"></div>
<div class="bd-content">
<div class="bd-article-container">
<div class="bd-header-article">
<div class="header-article-items header-article__inner">
<div class="header-article-items__start">
<div class="header-article-item"><label class="sidebar-toggle primary-toggle btn btn-sm" for="__primary" title="Toggle primary sidebar" data-bs-placement="bottom" data-bs-toggle="tooltip">
<span class="fa-solid fa-bars"></span>
</label></div>
</div>
<div class="header-article-items__end">
<div class="header-article-item">
<div class="article-header-buttons">
<button onclick="toggleFullScreen()"
class="btn btn-sm btn-fullscreen-button"
title="Fullscreen mode"
data-bs-placement="bottom" data-bs-toggle="tooltip"
>
<span class="btn__icon-container">
<i class="fas fa-expand"></i>
</span>
</button>
<script>
document.write(`
<button class="btn btn-sm navbar-btn search-button search-button__button" title="Search" aria-label="Search" data-bs-placement="bottom" data-bs-toggle="tooltip">
<i class="fa-solid fa-magnifying-glass"></i>
</button>
`);
</script>
<label class="sidebar-toggle secondary-toggle btn btn-sm" for="__secondary"title="Toggle secondary sidebar" data-bs-placement="bottom" data-bs-toggle="tooltip">
<span class="fa-solid fa-list"></span>
</label>
</div></div>
</div>
</div>
</div>
<div id="jb-print-docs-body" class="onlyprint">
<h1>Module 2, Part 2: Console I/O, Conditionals, Strings</h1>
<!-- Table of contents -->
<div id="print-main-content">
<div id="jb-print-toc">
<div>
<h2> Contents </h2>
</div>
<nav aria-label="Page">
<ul class="visible nav section-nav flex-column">
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#goal-an-interactive-program-that-computes-areas">Goal: an Interactive Program that Computes Areas</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#console-i-o">Console I/O</a><ul class="nav section-nav flex-column">
<li class="toc-h3 nav-item toc-entry"><a class="reference internal nav-link" href="#the-standard-input-and-output-streams">The Standard Input and Output Streams</a></li>
<li class="toc-h3 nav-item toc-entry"><a class="reference internal nav-link" href="#creating-and-using-a-scanner-for-reading-inputs">Creating and Using a Scanner for Reading Inputs</a></li>
</ul>
</li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#conditional-statements-and-expressions">Conditional Statements and Expressions</a><ul class="nav section-nav flex-column">
<li class="toc-h3 nav-item toc-entry"><a class="reference internal nav-link" href="#if-then-else-statement">If-Then-Else Statement</a></li>
<li class="toc-h3 nav-item toc-entry"><a class="reference internal nav-link" href="#if-then-statement">If-Then Statement</a></li>
<li class="toc-h3 nav-item toc-entry"><a class="reference internal nav-link" href="#boolean-expressions">Boolean Expressions</a></li>
<li class="toc-h3 nav-item toc-entry"><a class="reference internal nav-link" href="#conditional-expression">Conditional Expression</a></li>
<li class="toc-h3 nav-item toc-entry"><a class="reference internal nav-link" href="#switch-statement">Switch Statement</a></li>
<li class="toc-h3 nav-item toc-entry"><a class="reference internal nav-link" href="#switch-expression">Switch Expression</a></li>
</ul>
</li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#more-on-strings-in-java">More on Strings in Java</a><ul class="nav section-nav flex-column">
<li class="toc-h3 nav-item toc-entry"><a class="reference internal nav-link" href="#some-useful-string-methods">Some Useful String Methods</a></li>
<li class="toc-h3 nav-item toc-entry"><a class="reference internal nav-link" href="#comparing-strings-for-equality-or-alphabetically">Comparing <code class="docutils literal notranslate"><span class="pre">String</span></code>s for Equality or Alphabetically</a></li>
</ul>
</li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#concluding-remarks">Concluding Remarks</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#references-and-further-readings">References and Further Readings</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#exercises">Exercises</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#lab-and-weekly-assessments">Lab and Weekly Assessments</a><ul class="nav section-nav flex-column">
<li class="toc-h3 nav-item toc-entry"><a class="reference internal nav-link" href="#print-the-maximum">03 - Print the Maximum</a></li>
<li class="toc-h3 nav-item toc-entry"><a class="reference internal nav-link" href="#conversion-from-seconds">04 - Conversion from Seconds</a></li>
<li class="toc-h3 nav-item toc-entry"><a class="reference internal nav-link" href="#password-check">05 - Password Check</a></li>
<li class="toc-h3 nav-item toc-entry"><a class="reference internal nav-link" href="#line-point-distance">06 - Line-Point Distance</a></li>
</ul>
</li>
</ul>
</nav>
</div>
</div>
</div>
<div id="searchbox"></div>
<article class="bd-article" role="main">
<section class="tex2jax_ignore mathjax_ignore" id="module-2-part-2-console-i-o-conditionals-strings">
<span id="mod-io-cond-strings"></span><h1>Module 2, Part 2: Console I/O, Conditionals, Strings<a class="headerlink" href="#module-2-part-2-console-i-o-conditionals-strings" title="Permalink to this heading">#</a></h1>
<p>This is the second part of Module 2, and a follow-up to
<a class="reference internal" href="java-first-taste.html#mod-basic-programming-java"><span class="std std-ref">Module 2, Part 1: a First Taste of Java</span></a>. This second part introduces some more
elements of Java, allowing us to write more interesting and interactive
programs. We address three main topics:</p>
<ul class="simple">
<li><p>performing
<a class="reference internal" href="#sec-io-cond-strings-console-io"><span class="std std-ref">input and output (I/O) operations on the console</span></a>
(a.k.a. terminal);</p></li>
<li><p>performing
<a class="reference internal" href="#sec-io-cond-strings-conditions"><span class="std std-ref">computations depending on conditions</span></a>;</p></li>
<li><p>more details on <a class="reference internal" href="#sec-io-cond-strings-strings"><span class="std std-ref">using strings</span></a>.</p></li>
</ul>
<p>To introduce these topics, we consider a
<a class="reference internal" href="#sec-io-cond-strings-goal-prog"><span class="std std-ref">practical problem</span></a>: writing an
interactive program that computes the area of various geometric shapes.</p>
<section id="goal-an-interactive-program-that-computes-areas">
<span id="sec-io-cond-strings-goal-prog"></span><h2>Goal: an Interactive Program that Computes Areas<a class="headerlink" href="#goal-an-interactive-program-that-computes-areas" title="Permalink to this heading">#</a></h2>
<p>Our goal is to write a program that runs on the console (a.k.a. terminal) and
behaves as follows:</p>
<ol class="arabic simple">
<li><p>Asks the user to write their name;</p></li>
<li><p>Greets the user by using their name;</p></li>
<li><p>Asks the user to write the name of a geometric shape;</p></li>
<li><p>Checks what shape has been specified by the user:</p>
<ol class="arabic simple">
<li><p>if the shape is <code class="docutils literal notranslate"><span class="pre">"rectangle"</span></code>, the program asks the user to specify its
width and height (both having type <code class="docutils literal notranslate"><span class="pre">double</span></code>), and tells whether the
rectangle is a square (when width and height are equal). Then, the
program computes the area, and prints the result;</p></li>
<li><p>if the shape is <code class="docutils literal notranslate"><span class="pre">"circle"</span></code>, the program asks the user to specify its
radius (having type <code class="docutils literal notranslate"><span class="pre">double</span></code>), computes the area, and prints the result;</p></li>
<li><p>otherwise (i.e. if the shape is something else), the program displays an
error message.</p></li>
</ol>
</li>
<li><p>Finally, the program says goodbye and ends.</p></li>
</ol>
<p>This flowchart visualises the intended program behaviour:</p>
<p><img alt="Area calculator flowchart" src="_images/area-calculator.drawio.svg" /></p>
<p>Based on our <a class="reference internal" href="java-first-taste.html#mod-basic-programming-java"><span class="std std-ref">first taste of Java</span></a>,
we know how to address some parts of this program: displaying a greeting,
computing an area. However, we have <em>not</em> yet seen how to:</p>
<ul class="simple">
<li><p>receive user inputs from the console (points 1 and 3), and</p></li>
<li><p>execute either point 4.1, 4.2, or 4.3, depending on a condition (i.e. which
shape has been specified by the user). In other words, we do not yet know how
to write Java code to perform the rhombus-shaped steps in the flowchart.</p></li>
</ul>
<div class="proof example admonition" id="eg-area-calculator-solution">
<p class="admonition-title"><span class="caption-number">Example 12 </span> (An area calculator program)</p>
<section class="example-content" id="proof-content">
<p>The following Java program behaves according to the description above, and uses
some Java constructs that we have not yet seen. In the rest of this module we
discuss all these new constructs.</p>
<div class="admonition note">
<p class="admonition-title">Note</p>
<p>You can run the program below by copy&pasting it in a text editor (e.g. VS
Code), saving it in a file called <code class="docutils literal notranslate"><span class="pre">AreaCalculator.java</span></code>, and then running on a
terminal (in the same folder where you saved the file):</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>java AreaCalculator.java
</pre></div>
</div>
</div>
<div class="highlight-java notranslate"><div class="highlight"><pre><span></span><span class="linenos"> 1</span><span class="kd">class</span> <span class="nc">AreaCalculator</span><span class="w"> </span><span class="p">{</span>
<span class="linenos"> 2</span><span class="w"> </span><span class="kd">public</span><span class="w"> </span><span class="kd">static</span><span class="w"> </span><span class="kt">void</span><span class="w"> </span><span class="nf">main</span><span class="p">(</span><span class="n">String</span><span class="o">[]</span><span class="w"> </span><span class="n">args</span><span class="p">)</span><span class="w"> </span><span class="p">{</span>
<span class="linenos"> 3</span><span class="w"> </span><span class="kd">var</span><span class="w"> </span><span class="n">scanner</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="k">new</span><span class="w"> </span><span class="n">java</span><span class="p">.</span><span class="na">util</span><span class="p">.</span><span class="na">Scanner</span><span class="p">(</span><span class="n">System</span><span class="p">.</span><span class="na">in</span><span class="p">);</span>
<span class="linenos"> 4</span><span class="w"> </span><span class="n">scanner</span><span class="p">.</span><span class="na">useLocale</span><span class="p">(</span><span class="n">java</span><span class="p">.</span><span class="na">util</span><span class="p">.</span><span class="na">Locale</span><span class="p">.</span><span class="na">ENGLISH</span><span class="p">);</span>
<span class="linenos"> 5</span>
<span class="linenos"> 6</span><span class="w"> </span><span class="n">System</span><span class="p">.</span><span class="na">out</span><span class="p">.</span><span class="na">println</span><span class="p">(</span><span class="s">"Hello, human. What is your name?"</span><span class="p">);</span>
<span class="linenos"> 7</span>
<span class="linenos"> 8</span><span class="w"> </span><span class="kd">var</span><span class="w"> </span><span class="n">name</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">scanner</span><span class="p">.</span><span class="na">nextLine</span><span class="p">();</span>
<span class="linenos"> 9</span><span class="w"> </span><span class="n">System</span><span class="p">.</span><span class="na">out</span><span class="p">.</span><span class="na">println</span><span class="p">(</span><span class="s">"Nice to meet you, "</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="n">name</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="s">"!"</span><span class="p">);</span>
<span class="linenos">10</span><span class="w"> </span><span class="n">System</span><span class="p">.</span><span class="na">out</span><span class="p">.</span><span class="na">println</span><span class="p">(</span><span class="s">"Please write the name of a geometric shape:"</span><span class="p">);</span>
<span class="linenos">11</span>
<span class="linenos">12</span><span class="w"> </span><span class="kd">var</span><span class="w"> </span><span class="n">shape</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">scanner</span><span class="p">.</span><span class="na">nextLine</span><span class="p">();</span>
<span class="linenos">13</span><span class="w"> </span><span class="k">if</span><span class="w"> </span><span class="p">(</span><span class="n">shape</span><span class="p">.</span><span class="na">equals</span><span class="p">(</span><span class="s">"rectangle"</span><span class="p">))</span><span class="w"> </span><span class="p">{</span>
<span class="linenos">14</span><span class="w"> </span><span class="n">System</span><span class="p">.</span><span class="na">out</span><span class="p">.</span><span class="na">println</span><span class="p">(</span><span class="s">"What is the width?"</span><span class="p">);</span>
<span class="linenos">15</span><span class="w"> </span><span class="kd">var</span><span class="w"> </span><span class="n">width</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">scanner</span><span class="p">.</span><span class="na">nextDouble</span><span class="p">();</span>
<span class="linenos">16</span><span class="w"> </span><span class="n">System</span><span class="p">.</span><span class="na">out</span><span class="p">.</span><span class="na">println</span><span class="p">(</span><span class="s">"What is the height?"</span><span class="p">);</span>
<span class="linenos">17</span><span class="w"> </span><span class="kd">var</span><span class="w"> </span><span class="n">height</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">scanner</span><span class="p">.</span><span class="na">nextDouble</span><span class="p">();</span>
<span class="linenos">18</span>
<span class="linenos">19</span><span class="w"> </span><span class="k">if</span><span class="w"> </span><span class="p">(</span><span class="n">width</span><span class="w"> </span><span class="o">==</span><span class="w"> </span><span class="n">height</span><span class="p">)</span><span class="w"> </span><span class="p">{</span>
<span class="linenos">20</span><span class="w"> </span><span class="n">System</span><span class="p">.</span><span class="na">out</span><span class="p">.</span><span class="na">println</span><span class="p">(</span><span class="s">"The specified rectangle is a square"</span><span class="p">);</span>
<span class="linenos">21</span><span class="w"> </span><span class="p">}</span><span class="w"> </span><span class="k">else</span><span class="w"> </span><span class="p">{</span>
<span class="linenos">22</span><span class="w"> </span><span class="n">System</span><span class="p">.</span><span class="na">out</span><span class="p">.</span><span class="na">println</span><span class="p">(</span><span class="s">"The specified rectangle is not a square"</span><span class="p">);</span>
<span class="linenos">23</span><span class="w"> </span><span class="p">}</span>
<span class="linenos">24</span>
<span class="linenos">25</span><span class="w"> </span><span class="kd">var</span><span class="w"> </span><span class="n">area</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">width</span><span class="w"> </span><span class="o">*</span><span class="w"> </span><span class="n">height</span><span class="p">;</span>
<span class="linenos">26</span><span class="w"> </span><span class="n">System</span><span class="p">.</span><span class="na">out</span><span class="p">.</span><span class="na">println</span><span class="p">(</span><span class="s">"The area is: "</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="n">area</span><span class="p">);</span>
<span class="linenos">27</span><span class="w"> </span><span class="p">}</span><span class="w"> </span><span class="k">else</span><span class="w"> </span><span class="k">if</span><span class="w"> </span><span class="p">(</span><span class="n">shape</span><span class="p">.</span><span class="na">equals</span><span class="p">(</span><span class="s">"circle"</span><span class="p">))</span><span class="w"> </span><span class="p">{</span>
<span class="linenos">28</span><span class="w"> </span><span class="n">System</span><span class="p">.</span><span class="na">out</span><span class="p">.</span><span class="na">println</span><span class="p">(</span><span class="s">"What is the radius?"</span><span class="p">);</span>
<span class="linenos">29</span><span class="w"> </span><span class="kd">var</span><span class="w"> </span><span class="n">radius</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">scanner</span><span class="p">.</span><span class="na">nextDouble</span><span class="p">();</span>
<span class="linenos">30</span>
<span class="linenos">31</span><span class="w"> </span><span class="kd">var</span><span class="w"> </span><span class="n">area</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">radius</span><span class="w"> </span><span class="o">*</span><span class="w"> </span><span class="n">radius</span><span class="w"> </span><span class="o">*</span><span class="w"> </span><span class="n">Math</span><span class="p">.</span><span class="na">PI</span><span class="p">;</span>
<span class="linenos">32</span><span class="w"> </span><span class="n">System</span><span class="p">.</span><span class="na">out</span><span class="p">.</span><span class="na">println</span><span class="p">(</span><span class="s">"The area is: "</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="n">area</span><span class="p">);</span>
<span class="linenos">33</span><span class="w"> </span><span class="p">}</span><span class="w"> </span><span class="k">else</span><span class="w"> </span><span class="p">{</span>
<span class="linenos">34</span><span class="w"> </span><span class="n">System</span><span class="p">.</span><span class="na">out</span><span class="p">.</span><span class="na">println</span><span class="p">(</span><span class="s">"I don't know the shape '"</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="n">shape</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="s">"' :-("</span><span class="p">);</span>
<span class="linenos">35</span><span class="w"> </span><span class="p">}</span>
<span class="linenos">36</span>
<span class="linenos">37</span><span class="w"> </span><span class="n">scanner</span><span class="p">.</span><span class="na">close</span><span class="p">();</span>
<span class="linenos">38</span><span class="w"> </span><span class="n">System</span><span class="p">.</span><span class="na">out</span><span class="p">.</span><span class="na">println</span><span class="p">(</span><span class="s">"Goodbye!"</span><span class="p">);</span>
<span class="linenos">39</span><span class="w"> </span><span class="p">}</span>
<span class="linenos">40</span><span class="p">}</span>
</pre></div>
</div>
</section>
</div></section>
<section id="console-i-o">
<span id="sec-io-cond-strings-console-io"></span><h2>Console I/O<a class="headerlink" href="#console-i-o" title="Permalink to this heading">#</a></h2>
<p>In <a class="reference internal" href="java-first-taste.html#sec-basic-programming-java-first-program"><span class="std std-ref">our first Java program</span></a> we
displayed some console outputs, by using <code class="docutils literal notranslate"><span class="pre">System.out.println(...)</span></code>. We now
discuss the topic of console input and output in more detail — and this will
let us begin an exploration of the
<strong>Java Application Programmer Interface (API)</strong>, which is a library of
ready-to-use software components that we can utilise to develop our programs.</p>
<span class="target" id="index-0"></span><span class="target" id="index-1"></span><span class="target" id="index-2"></span><span class="target" id="index-3"></span><span class="target" id="index-4"></span><span class="target" id="index-5"></span><section id="the-standard-input-and-output-streams">
<span id="sec-io-cond-strings-console-io-system-in-out"></span><span id="index-6"></span><h3>The Standard Input and Output Streams<a class="headerlink" href="#the-standard-input-and-output-streams" title="Permalink to this heading">#</a></h3>
<p>Java programs can read inputs and display outputs by using two predefined
<strong>objects</strong> provided by the Java API:</p>
<ul class="simple">
<li><p><code class="docutils literal notranslate"><span class="pre">System.out</span></code> can be used to display outputs on the console. To produce an
output, we need to <strong>call</strong> (or <em>invoke</em>) one of the <strong>methods</strong> provided by
<code class="docutils literal notranslate"><span class="pre">System.out</span></code>: for example, the method <code class="docutils literal notranslate"><span class="pre">println</span></code> takes one argument, displays
its value on the console, and moves to the beginning of the next line on the
console. We have used this method in
<a class="reference internal" href="java-first-taste.html#sec-basic-programming-java-first-program"><span class="std std-ref">our first Java program</span></a>: we
wrote <code class="docutils literal notranslate"><span class="pre">System.out.println(message)</span></code> to display the value of the argument
<code class="docutils literal notranslate"><span class="pre">message</span></code>.</p></li>
<li><p><code class="docutils literal notranslate"><span class="pre">System.in</span></code> can be used to receive inputs from the console. This object
has a limited set of methods: it only supports reading sequences of bytes,
which makes the handling of inputs quite cumbersome. For this reason, we
create and use instead a more convenient
<a class="reference internal" href="#sec-io-cond-strings-console-io-scanner"><span class="std std-ref">Scanner object</span></a>.</p></li>
</ul>
<p>The objects <code class="docutils literal notranslate"><span class="pre">System.in</span></code> and <code class="docutils literal notranslate"><span class="pre">System.out</span></code> are called <strong>standard input
stream</strong> and <strong>standard output stream</strong>, respectively: you can imagine that they
carry “streams” of text characters — one flowing from the console keyboard to
the Java application (input), and another flowing from the Java application to
the console display (output), as shown in <a class="reference internal" href="#fig-stdin-stdout"><span class="std std-numref">Fig. 13</span></a> below. This
design descends from the <a class="reference internal" href="basic-programming.html#sec-basic-programming-interaction-human-computer"><span class="std std-ref">teleprinter and video terminals from the 1960s and 1970s</span></a>.</p>
<figure class="align-default" id="fig-stdin-stdout">
<img alt="Standard input and output" src="_images/stdin-stdout.png" />
<figcaption>
<p><span class="caption-number">Fig. 13 </span><span class="caption-text">A diagram of the standard input and output streams in Java. The standard input
(accessible via the object <code class="docutils literal notranslate"><span class="pre">System.in</span></code>) carries data from the console keyboard
to the running program; the standard output (accessible via the object
<code class="docutils literal notranslate"><span class="pre">System.out</span></code>) carries data from the program to the console display.</span><a class="headerlink" href="#fig-stdin-stdout" title="Permalink to this image">#</a></p>
</figcaption>
</figure>
<span class="target" id="index-7"></span><span class="target" id="index-8"></span><span class="target" id="index-9"></span><span class="target" id="index-10"></span><span class="target" id="index-11"></span></section>
<section id="creating-and-using-a-scanner-for-reading-inputs">
<span id="sec-io-cond-strings-console-io-scanner"></span><span id="index-12"></span><h3>Creating and Using a Scanner for Reading Inputs<a class="headerlink" href="#creating-and-using-a-scanner-for-reading-inputs" title="Permalink to this heading">#</a></h3>
<p>On the <a class="reference internal" href="java-first-taste.html#sec-basic-programming-java-jshell"><span class="std std-ref">Java shell</span></a>, we can create
a scanner object that reads inputs from the keyboard, as follows:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span><span class="hll">jshell> var s = new java.util.Scanner(System.in)
</span>scanner ==> java.util.Scanner[...]
| created variable s : Scanner
</pre></div>
</div>
<p>Let us examine this in detail:</p>
<ul class="simple">
<li><p>On the first line, we use the keyword <code class="docutils literal notranslate"><span class="pre">new</span></code> to construct (i.e., create) a new
object of a desired <strong>class</strong>;</p></li>
<li><p>In this example, we write <code class="docutils literal notranslate"><span class="pre">new</span> <span class="pre">java.util.Scanner(System.in)</span></code>, where:</p>
<ul>
<li><p><code class="docutils literal notranslate"><span class="pre">java.util.Scanner</span></code> is the <strong>class name</strong>, which is provided by the Java API;
(more specifically, <code class="docutils literal notranslate"><span class="pre">java.util</span></code> is the name of a <strong>Java package</strong> that,
among other things, contains a class called <code class="docutils literal notranslate"><span class="pre">Scanner</span></code>);</p></li>
<li><p>to construct the desired object of the class <code class="docutils literal notranslate"><span class="pre">java.util.Scanner</span></code>, we provide
an argument — and in this case, we provide <code class="docutils literal notranslate"><span class="pre">System.in</span></code>.</p></li>
</ul>
</li>
<li><p>We use the result of <code class="docutils literal notranslate"><span class="pre">new</span> <span class="pre">...</span></code> to declare a variable called <code class="docutils literal notranslate"><span class="pre">s</span></code>.
Correspondingly, on the 2nd line above, the Java shell tells us that variable
<code class="docutils literal notranslate"><span class="pre">s</span></code> now gives us access to the object constructed by <code class="docutils literal notranslate"><span class="pre">new</span> <span class="pre">...</span></code> (such an object
is represented as <code class="docutils literal notranslate"><span class="pre">java.util.Scanner[...]</span></code>).</p></li>
<li><p>The last line printed by the Java shell tells us that the variable <code class="docutils literal notranslate"><span class="pre">s</span></code> has
type <code class="docutils literal notranslate"><span class="pre">Scanner</span></code> (which is abbreviated from <code class="docutils literal notranslate"><span class="pre">java.util.Scanner</span></code>).</p></li>
</ul>
<p>We can now use the variable <code class="docutils literal notranslate"><span class="pre">s</span></code> to call the <strong>methods</strong> provided by the
object we have just created; moreover, since we constructed this <code class="docutils literal notranslate"><span class="pre">Scanner</span></code>
object by “attaching” it to <code class="docutils literal notranslate"><span class="pre">System.in</span></code> (which we provided as argument when
using <code class="docutils literal notranslate"><span class="pre">new</span> <span class="pre">...</span></code>), this <code class="docutils literal notranslate"><span class="pre">Scanner</span></code> object will allow us to receive inputs from the
console.</p>
<div class="proof remark admonition" id="remark-scanner-localisation">
<p class="admonition-title"><span class="caption-number">Remark 3 </span> (Configuring the localisation of the <code class="docutils literal notranslate"><span class="pre">Scanner</span></code> object)</p>
<section class="remark-content" id="proof-content">
<p>Before continuing, it is recommended to configure the <strong>localisation of the
<code class="docutils literal notranslate"><span class="pre">Scanner</span></code> object</strong>, i.e. the conventions used by the scanner e.g. to recognise
numbers with fractional parts. To do that, you can call the method <code class="docutils literal notranslate"><span class="pre">useLocale</span></code>,
and (for the lectures and exercises of this course) specify the English
localisation:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span><span class="hll">jshell> s.useLocale(java.util.Locale.ENGLISH)
</span></pre></div>
</div>
<p>This will ensure that the scanner will apply the English language standards and
recognise e.g. the input <code class="docutils literal notranslate"><span class="pre">3.14</span></code> as a number with fractional digits. If you don’t
configure the localisation, then the Scanner will apply your system defaults:
for instance, if your system language is set to Danish, the <code class="docutils literal notranslate"><span class="pre">Scanner</span></code> object
will <em>not</em> recognise <code class="docutils literal notranslate"><span class="pre">3.14</span></code> as a number, but it will recognise <code class="docutils literal notranslate"><span class="pre">3,14</span></code> instead.</p>
</section>
</div><p>For instance, we can use the <code class="docutils literal notranslate"><span class="pre">Scanner</span> <span class="pre">object</span></code> to read the next line of input
text and use it to declare a variable:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span><span class="hll">jshell> var inputLine = s.nextLine()
</span></pre></div>
</div>
<p>The method <code class="docutils literal notranslate"><span class="pre">s.nextLine()</span></code> is now waiting for us to write something and
press <code class="docutils literal notranslate"><span class="pre">⏎</span></code> (return key). For example, if we write <code class="docutils literal notranslate"><span class="pre">This</span> <span class="pre">is</span> <span class="pre">just</span> <span class="pre">a</span> <span class="pre">test</span></code> and
press <code class="docutils literal notranslate"><span class="pre">⏎</span></code>, the Java shell will then display:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>inputLine ==> "This is just a test"
| created variable inputLine : String
</pre></div>
</div>
<p>Therefore, the method <code class="docutils literal notranslate"><span class="pre">s.nextLine()</span></code> has read a whole line of console
input and has produced a corresponding <code class="docutils literal notranslate"><span class="pre">String</span></code>, which has been used to declare
the variable <code class="docutils literal notranslate"><span class="pre">inputLine</span></code>. From now on, we can use the variable <code class="docutils literal notranslate"><span class="pre">inputLine</span></code> to
access the text just received from the console. In fact, we can try:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span><span class="hll">jshell> System.out.println("The input was: '" + inputLine + "'")
</span>The input was: 'This is just a test'
</pre></div>
</div>
<p>The <code class="docutils literal notranslate"><span class="pre">Scanner</span></code> object also provides other convenience methods for reading
numbers. For example, you can try:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span><span class="hll">jshell> var width = s.nextDouble()
</span></pre></div>
</div>
<p>Again, the method waits for us to provide a number (possibly with decimal
digits). If we write e.g. <code class="docutils literal notranslate"><span class="pre">4.25</span></code> and press <code class="docutils literal notranslate"><span class="pre">⏎</span></code>, we will see:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>width ==> 4.25
| created variable width : double
</pre></div>
</div>
<p>Therefore, the method <code class="docutils literal notranslate"><span class="pre">s.nextDouble()</span></code> has read the console input and
returned the corresponding value 4.25 (of type <code class="docutils literal notranslate"><span class="pre">double</span></code>), which has been used to
declare the variable <code class="docutils literal notranslate"><span class="pre">width</span></code>.</p>
<p>Objects of class <code class="docutils literal notranslate"><span class="pre">Scanner</span></code> provide other similar convenience methods to read the
console input and return various types of values. For instance, we could use:</p>
<ul class="simple">
<li><p><code class="docutils literal notranslate"><span class="pre">s.nextInt()</span></code>, which produces a value of type <code class="docutils literal notranslate"><span class="pre">int</span></code>;</p></li>
<li><p><code class="docutils literal notranslate"><span class="pre">s.nextBoolean()</span></code>, which produces a value of type <code class="docutils literal notranslate"><span class="pre">boolean</span></code>.</p></li>
</ul>
<div class="proof remark admonition" id="remark-scanner-close">
<span id="index-13"></span><p class="admonition-title"><span class="caption-number">Remark 4 </span> (Closing a scanner)</p>
<section class="remark-content" id="proof-content">
<p>When we are done using a scanner <code class="docutils literal notranslate"><span class="pre">s</span></code>, we should close it, by calling the method
<code class="docutils literal notranslate"><span class="pre">s.close()</span></code> (the parentheses <code class="docutils literal notranslate"><span class="pre">()</span></code> mean that the method does not take any
argument). In <a class="reference internal" href="#eg-area-calculator-solution">Example 12</a> you can observe that a
<code class="docutils literal notranslate"><span class="pre">Scanner</span></code> object is created at the beginning of the program, and closed at the
end.</p>
<p>After being closed, a scanner instance object will report an error (as an
<strong>exception</strong>) if it is used to read further inputs.</p>
</section>
</div><div class="proof remark admonition" id="remark-scanner-errors">
<span id="index-14"></span><p class="admonition-title"><span class="caption-number">Remark 5 </span> (Errors when using <code class="docutils literal notranslate"><span class="pre">Scanner</span></code> objects)</p>
<section class="remark-content" id="proof-content">
<p>If a <code class="docutils literal notranslate"><span class="pre">Scanner</span></code> object receives an unexpected input, it will report an error
(as an <strong>exception</strong>) and stop working. For example, if you use
<code class="docutils literal notranslate"><span class="pre">s.nextInt()</span></code> on the Java shell, then type <code class="docutils literal notranslate"><span class="pre">Hello!</span></code> and press <code class="docutils literal notranslate"><span class="pre">⏎</span></code>, you
will see:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span><span class="hll">jshell> s.nextInt()
</span>Hello!
| Exception java.util.InputMismatchException
| at Scanner.throwFor (Scanner.java:939)
| at Scanner.next (Scanner.java:1594)
| at Scanner.nextInt (Scanner.java:2258)
| at Scanner.nextInt (Scanner.java:2212)
| at (#8:1)
</pre></div>
</div>
<p>After this, error, the <code class="docutils literal notranslate"><span class="pre">Scanner</span></code> object becomes unusable: any attempt to
read inputs using the variable <code class="docutils literal notranslate"><span class="pre">s</span></code> will cause an error. (We will see how to
handle errors later in the course)</p>
</section>
</div><div class="admonition note">
<p class="admonition-title">Note</p>
<p>The class <code class="docutils literal notranslate"><span class="pre">java.util.Scanner</span></code> is part of the Java API; if you are curious, you
can have a look at
<a class="reference external" href="https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/Scanner.html">its official documentation</a>.</p>
</div>
<span class="target" id="index-15"></span><span class="target" id="index-16"></span><span class="target" id="index-17"></span><div class="proof remark admonition" id="remark-classes-vs-types">
<span id="index-18"></span><p class="admonition-title"><span class="caption-number">Remark 6 </span> (Terminology: “value” or “object”? “Type” or “class”?)</p>
<section class="remark-content" id="proof-content">
<p>In the explanation above, we have said that <code class="docutils literal notranslate"><span class="pre">java.util.Scanner</span></code> is the <em>class</em>
of the <em>object</em> constructed with <code class="docutils literal notranslate"><span class="pre">new</span> <span class="pre">...</span></code>. Instead, in
<a class="reference internal" href="java-first-taste.html#sec-basic-programming-java-jshell-integer"><span class="std std-ref">previous examples</span></a>, we have
talked about the <em>type</em> of <em>values</em> (e.g. value <code class="docutils literal notranslate"><span class="pre">42</span></code> has type <code class="docutils literal notranslate"><span class="pre">int</span></code>).</p>
<p>So, what is the difference between “class” and “type,” and between
“object” and “value”?</p>
<ul class="simple">
<li><p>The term “type” can refer to both
<em><a class="reference internal" href="java-first-taste.html#table-primitive-data-types"><span class="std std-ref">primitive data types</span></a></em>
(<code class="docutils literal notranslate"><span class="pre">int</span></code>, <code class="docutils literal notranslate"><span class="pre">boolean</span></code>, <code class="docutils literal notranslate"><span class="pre">double</span></code>, …) and classes (such as <code class="docutils literal notranslate"><span class="pre">java.util.Scanner</span></code>).
In other words, <strong>a class is a specific kind of type</strong> with advanced features
that we will explore later in the course. Therefore, it is correct to say
either:</p>
<ul>
<li><p>the variable <code class="docutils literal notranslate"><span class="pre">s</span></code> has <em>type</em> <code class="docutils literal notranslate"><span class="pre">Scanner</span></code>; or</p></li>
<li><p>the variable <code class="docutils literal notranslate"><span class="pre">s</span></code> has <em>class</em> <code class="docutils literal notranslate"><span class="pre">Scanner</span></code>.</p></li>
</ul>
</li>
<li><p>In Java, the term “value” is often generically used to refer to two things:</p>
<ul>
<li><p>a <em>primitive value</em>, which is instance of a
<em><a class="reference internal" href="java-first-taste.html#table-primitive-data-types"><span class="std std-ref">primitive data types</span></a></em>
(e.g. <code class="docutils literal notranslate"><span class="pre">42</span></code> is an instance of <code class="docutils literal notranslate"><span class="pre">int</span></code>, <code class="docutils literal notranslate"><span class="pre">false</span></code> is an instance of <code class="docutils literal notranslate"><span class="pre">boolean</span></code>,
<code class="docutils literal notranslate"><span class="pre">3.14</span></code> is an instance of <code class="docutils literal notranslate"><span class="pre">double</span></code>, …); or</p></li>
<li><p>an <em>object</em>, which is an instance of a <em>class</em> (such as
<code class="docutils literal notranslate"><span class="pre">java.util.Scanner</span></code>).</p></li>
</ul>
</li>
</ul>
<p>We will see later in the course that primitive values and objects have
significantly different behaviours (and we will see the first signs of their
difference in this very Module, when we will discuss
<a class="reference internal" href="#sec-io-cond-strings-strings-comparison"><span class="std std-ref">how to compare strings</span></a>).</p>
</section>
</div><span class="target" id="index-19"></span><span class="target" id="index-20"></span><div class="proof remark admonition" id="remark-statements-vs-expressions">
<span id="index-21"></span><p class="admonition-title"><span class="caption-number">Remark 7 </span> (Terminology: statements vs. expressions)</p>
<section class="remark-content" id="proof-content">
<p>When talking about Java code constructs, we often use the terms “statement” and
“expression.” You can follow the intuition presented below:</p>
<ul>
<li><p><strong>Expressions compute and produce a result value</strong> (e.g. a number, or an
object). The act of computing the result of an expression is called
<strong>evaluation</strong>, and we often say that an expression <em>“evaluates to”</em> a result.
For instance:</p>
<ul class="simple">
<li><p><code class="docutils literal notranslate"><span class="pre">2</span></code> is an expression, because it produces the value 2 itself;</p></li>
<li><p><code class="docutils literal notranslate"><span class="pre">x</span></code> (i.e. the name of a variable) is an expression, because it produces the
value previously given to <code class="docutils literal notranslate"><span class="pre">x</span></code>;</p></li>
<li><p><code class="docutils literal notranslate"><span class="pre">2</span> <span class="pre">+</span> <span class="pre">3</span></code> is an expression that uses the operator <code class="docutils literal notranslate"><span class="pre">+</span></code> to compute and produce
the value 5; (or in other words, <code class="docutils literal notranslate"><span class="pre">2</span> <span class="pre">+</span> <span class="pre">3</span></code> evaluates to the result 5)</p></li>
<li><p><code class="docutils literal notranslate"><span class="pre">s.nextLine()</span></code> is an expression, because it produces a result (a <code class="docutils literal notranslate"><span class="pre">String</span></code>
with the input received from the console);</p></li>
<li><p><code class="docutils literal notranslate"><span class="pre">new</span> <span class="pre">java.util.Scanner(System.in)</span></code> is an expression, because it produces a
result: a newly-created object of the class <code class="docutils literal notranslate"><span class="pre">Scanner</span></code>. <em>(We will reprise the
exact behaviour of <code class="docutils literal notranslate"><span class="pre">new</span></code> later in the course.)</em></p></li>
</ul>
<p>Therefore, <strong>an expression can be written in any point of Java program where a
value is required</strong>: when the program runs, the required value is obtained by
computing the expression. For instance:</p>
<ul class="simple">
<li><p>the operator <code class="docutils literal notranslate"><span class="pre">+</span></code> requires two numerical values to compute a result (e.g.
<code class="docutils literal notranslate"><span class="pre">2</span> <span class="pre">+</span> <span class="pre">3</span></code> evaluates to the result 5). Therefore, we can use as arguments for <code class="docutils literal notranslate"><span class="pre">+</span></code>
any expression that produces a number. E.g. we can write <code class="docutils literal notranslate"><span class="pre">(2</span> <span class="pre">*</span> <span class="pre">3)</span> <span class="pre">+</span> <span class="pre">5</span></code>, and
the result will be computed by first computing the expression <code class="docutils literal notranslate"><span class="pre">2</span> <span class="pre">*</span> <span class="pre">3</span></code>, and
then adding its result to <code class="docutils literal notranslate"><span class="pre">5</span></code>;</p></li>
<li><p>to declare a variable, we write <code class="docutils literal notranslate"><span class="pre">var</span> <span class="pre">x</span> <span class="pre">=</span> <span class="pre">...</span></code>, and we need to provide a
value instead of <code class="docutils literal notranslate"><span class="pre">...</span></code>. Therefore, we can provide an expression
like <code class="docutils literal notranslate"><span class="pre">2</span> <span class="pre">+</span> <span class="pre">3</span></code> or <code class="docutils literal notranslate"><span class="pre">s.nextLine()</span></code> or <code class="docutils literal notranslate"><span class="pre">new</span> <span class="pre">java.util.Scanner(...)</span></code> — and the
result of the expression will become the value of <code class="docutils literal notranslate"><span class="pre">x</span></code>.</p></li>
</ul>
<div class="admonition note">
<p class="admonition-title">Note</p>
<p>For more details, see Section 2.4 (“Expressions”) of the
<a class="reference internal" href="overview.html#sec-book"><span class="std std-ref">reference book</span></a>.</p>
</div>
</li>
<li><p><strong>Statements do <em>not</em> produce a result value</strong>: their purpose is to have an
effect on the program and its execution. For instance:</p>
<ul class="simple">
<li><p><code class="docutils literal notranslate"><span class="pre">var</span> <span class="pre">x</span> <span class="pre">=</span> <span class="pre">2</span> <span class="pre">+</span> <span class="pre">3</span></code> is a statement that declares the variable <code class="docutils literal notranslate"><span class="pre">x</span></code>, which can be
used later in the program (but the statement itself does not produce any
result value);</p></li>
<li><p><code class="docutils literal notranslate"><span class="pre">if</span> <span class="pre">(x)</span> <span class="pre">{</span> <span class="pre">...</span> <span class="pre">}</span></code> (which we will discuss shortly) is a statement that checks
whether the expression <code class="docutils literal notranslate"><span class="pre">x</span></code> produces the value <code class="docutils literal notranslate"><span class="pre">true</span></code>, and if so, executes
the code in <code class="docutils literal notranslate"><span class="pre">...</span></code> (but the statement itself does not produce any result
value).</p></li>
</ul>
<p><strong>A Java program is essentially a sequence of statements delimited by
semicolons <code class="docutils literal notranslate"><span class="pre">;</span></code> and/or surrounded by curly brackets <code class="docutils literal notranslate"><span class="pre">{</span></code>…<code class="docutils literal notranslate"><span class="pre">}</span></code></strong>. When the
program runs, the statements are executed one after the other — and
executing a statement may require computing one or more expressions written
as part of the statement (e.g. to execute the statement <code class="docutils literal notranslate"><span class="pre">var</span> <span class="pre">x</span> <span class="pre">=</span> <span class="pre">2</span> <span class="pre">+</span> <span class="pre">3</span></code>, the
expression <code class="docutils literal notranslate"><span class="pre">2</span> <span class="pre">+</span> <span class="pre">3</span></code> is computed, and its result value <code class="docutils literal notranslate"><span class="pre">5</span></code> is finally used to
declare <code class="docutils literal notranslate"><span class="pre">x</span></code>).</p>
</li>
</ul>
<p>The distinction between expressions and statements will become clearer with
practice: the suggestion is to pay attention to how the terms “statement” and
“expression” are used in these lecture notes, and refer back to this remark in
case of doubts.</p>
</section>
</div></section>
</section>
<section id="conditional-statements-and-expressions">
<span id="sec-io-cond-strings-conditions"></span><span id="index-22"></span><h2>Conditional Statements and Expressions<a class="headerlink" href="#conditional-statements-and-expressions" title="Permalink to this heading">#</a></h2>
<p>The Java programming language provides various ways to regulate the <strong>control
flow</strong> of a program, i.e. the order in which different part of a program are
executed, depending whether a certain <em>condition</em> is true or false. In this
Module we address:</p>
<ul class="simple">
<li><p><a class="reference internal" href="#sec-io-cond-strings-conditions-if-then-else"><span class="std std-ref">If-Then-Else Statement</span></a></p></li>
<li><p><a class="reference internal" href="#sec-io-cond-strings-conditions-if-then"><span class="std std-ref">If-Then Statement</span></a></p></li>
<li><p>We also see in more detail how to write the conditions as
<a class="reference internal" href="#sec-io-cond-strings-conditions-bool-expr"><span class="std std-ref">Boolean Expressions</span></a></p></li>
</ul>
<p>In this Module we also address some other ways to control computations depending
on conditions: conditional expressions and <code class="docutils literal notranslate"><span class="pre">switch</span></code> constructs.</p>
<ul class="simple">
<li><p><a class="reference internal" href="#sec-io-cond-strings-conditions-conditional-expr"><span class="std std-ref">Conditional Expression</span></a></p></li>
<li><p><a class="reference internal" href="#sec-io-cond-strings-conditions-switch"><span class="std std-ref">Switch Statement</span></a></p></li>
<li><p><a class="reference internal" href="#sec-io-cond-strings-conditions-switch-expr"><span class="std std-ref">Switch Expression</span></a></p></li>
</ul>
<div class="admonition important">
<p class="admonition-title">Important</p>
<p>Conditional expressions and “switch” constructs are not strictly necessary for
writing beginner Java programs: every task that can be solved using them can
also be solved using if-then-else statements. Therefore, make sure you
understand how to use if-then-else before going further. With practice, you
will see that can contitional expressions and “switch” constructs can help you
write Java code that is simpler and easier to read and maintain.</p>
</div>
<section id="if-then-else-statement">
<span id="sec-io-cond-strings-conditions-if-then-else"></span><span id="index-23"></span><h3>If-Then-Else Statement<a class="headerlink" href="#if-then-else-statement" title="Permalink to this heading">#</a></h3>
<p>The <strong>if-then-else statement</strong> has the following syntax:</p>
<div class="highlight-java notranslate"><div class="highlight"><pre><span></span><span class="linenos">1</span><span class="k">if</span><span class="w"> </span><span class="p">(</span><span class="n">bool_expr</span><span class="p">)</span><span class="w"> </span><span class="p">{</span>
<span class="linenos">2</span><span class="w"> </span><span class="c1">// Statements that are executed when the result of 'bool_expr' is 'true'</span>
<span class="linenos">3</span><span class="p">}</span><span class="w"> </span><span class="k">else</span><span class="w"> </span><span class="p">{</span>
<span class="linenos">4</span><span class="w"> </span><span class="c1">// Statements that are executed when the result of 'bool_expr' is 'false'</span>
<span class="linenos">5</span><span class="p">}</span>
<span class="linenos">6</span><span class="c1">// Other statements can follow (optionally)</span>
</pre></div>
</div>
<p>where <code class="docutils literal notranslate"><span class="pre">bool_expr</span></code> can be any expression of type <code class="docutils literal notranslate"><span class="pre">boolean</span></code>. When an if-then-else
statement is executed, the following happens:</p>
<ul class="simple">
<li><p>first, the expression <code class="docutils literal notranslate"><span class="pre">bool_expr</span></code> is evaluated, and its result is checked.
Subsequently,</p>
<ul>
<li><p>if the result of <code class="docutils literal notranslate"><span class="pre">bool_expr</span></code> is the value <code class="docutils literal notranslate"><span class="pre">true</span></code>, the statements inside the
first pair of curly brackets <code class="docutils literal notranslate"><span class="pre">{</span></code>…<code class="docutils literal notranslate"><span class="pre">}</span></code> (lines 1–3) are executed;</p></li>
<li><p>otherwise (i.e. if the result of <code class="docutils literal notranslate"><span class="pre">bool_expr</span></code> is the value <code class="docutils literal notranslate"><span class="pre">false</span></code>), the
statements inside the pair of curly brackets <code class="docutils literal notranslate"><span class="pre">{</span></code>…<code class="docutils literal notranslate"><span class="pre">}</span></code> after <code class="docutils literal notranslate"><span class="pre">else</span></code>
(lines 3–5) are executed;</p></li>
</ul>
</li>
<li><p>finally, the execution continues with the statements (if any) that follow the
whole if-then-else statement (line 6).</p></li>
</ul>
<p>When represented as a flowchart, the if-then-else statement looks as follows —
and whenever we spot the following pattern in a flowchart, we should consider
using an if-then-else statement when writing the corresponding Java program.</p>
<p><img alt="Flowchart for if-then-else" src="_images/if-else.drawio.svg" /></p>
<div class="admonition note">
<p class="admonition-title">Note</p>
<p>Conceptually, the if-then-else statement serves the same purpose of
conditional jumps in <a class="reference internal" href="basic-programming.html#sec-basic-programming-blinkenbits"><span class="std std-ref">BlinkenBits</span></a>: it
checks whether a condition (written as a <code class="docutils literal notranslate"><span class="pre">boolean</span></code> expression) produces the
result <code class="docutils literal notranslate"><span class="pre">true</span></code> or <code class="docutils literal notranslate"><span class="pre">false</span></code>, and depending on this, it makes the execution “jump”
to a certain part of the code. Indeed, behind the scenes, Java translates
if-then-else into “jump” machine instructions.</p>
<p>The key difference is that if-then-else statements in Java are considerably
easier to write and read than assembly jumps, because we do not need to worry
about registers for computing the condition, nor memory addresses for jumping:
we just need to structure our code depending on what we need to be executed
when the condition is true or false.</p>
</div>
<div class="proof example admonition" id="eg-if-then-else-java-shell">
<p class="admonition-title"><span class="caption-number">Example 13 </span> (Using if-then-else on the Java shell)</p>
<section class="example-content" id="proof-content">
<p>We can experiment with the if-then-else statement on the Java shell. Let us
first declare two variables (<code class="docutils literal notranslate"><span class="pre">a</span></code> and <code class="docutils literal notranslate"><span class="pre">b</span></code>):</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span><span class="hll">jshell> var a = 10; var b = 42
</span>a ==> 10
| created variable a : int
b ==> 42
| created variable b : int
</pre></div>
</div>
<p>Now, let us create a variable that contains the result of a comparison between
<code class="docutils literal notranslate"><span class="pre">a</span></code> and <code class="docutils literal notranslate"><span class="pre">b</span></code>: let us call this variable <code class="docutils literal notranslate"><span class="pre">isAGreaterThanB</span></code> (notice below that its
type is <code class="docutils literal notranslate"><span class="pre">boolean</span></code> and its value is <code class="docutils literal notranslate"><span class="pre">false</span></code>).</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span><span class="hll">jshell> var isAGreaterThanB = a > b;
</span>isAGreaterThanB ==> false
| created variable isAGreaterThanB : boolean
</pre></div>
</div>
<p>Then, copy&paste the following Java code on the Java shell, and press <code class="docutils literal notranslate"><span class="pre">⏎</span></code>:</p>
<div class="highlight-java notranslate"><div class="highlight"><pre><span></span><span class="linenos">1</span><span class="k">if</span><span class="w"> </span><span class="p">(</span><span class="n">isAGreaterThanB</span><span class="p">)</span><span class="w"> </span><span class="p">{</span>
<span class="linenos">2</span><span class="w"> </span><span class="n">System</span><span class="p">.</span><span class="na">out</span><span class="p">.</span><span class="na">println</span><span class="p">(</span><span class="s">"'"</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="s">" > "</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="n">b</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="s">"' is TRUE :-)"</span><span class="p">);</span>
<span class="linenos">3</span><span class="p">}</span><span class="w"> </span><span class="k">else</span><span class="w"> </span><span class="p">{</span>
<span class="linenos">4</span><span class="w"> </span><span class="n">System</span><span class="p">.</span><span class="na">out</span><span class="p">.</span><span class="na">println</span><span class="p">(</span><span class="s">"'"</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="s">" > "</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="n">b</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="s">"' is FALSE :-("</span><span class="p">);</span>
<span class="linenos">5</span><span class="p">}</span>
<span class="linenos">6</span><span class="n">System</span><span class="p">.</span><span class="na">out</span><span class="p">.</span><span class="na">println</span><span class="p">(</span><span class="s">"We got past the if-then-else statement"</span><span class="p">);</span>
</pre></div>
</div>
<p>What will happen is:</p>
<ul class="simple">
<li><p>on line 1, the if-then-else statement checks whether the conditional expression
(in this case, the variable <code class="docutils literal notranslate"><span class="pre">isAGreaterThanB</span></code>) has the value <code class="docutils literal notranslate"><span class="pre">true</span></code> or <code class="docutils literal notranslate"><span class="pre">false</span></code>.
Since its value is <code class="docutils literal notranslate"><span class="pre">false</span></code>, the execution “jump” to the block of code under
the <code class="docutils literal notranslate"><span class="pre">else</span></code> (line 4) — which displays the string <code class="docutils literal notranslate"><span class="pre">"...</span> <span class="pre">is</span> <span class="pre">FALSE</span> <span class="pre">:-("</span></code>;</p></li>
<li><p>finally, the execution continues with the code that follows the whole
if-then-else statement, which displays the string <code class="docutils literal notranslate"><span class="pre">"We</span> <span class="pre">got</span> <span class="pre">past..."</span></code>.</p></li>
</ul>
<p>Therefore, we will see the following output on the Java shell:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>'10 > 42' is false :-(
We got past the if-then-else statement
</pre></div>
</div>
<p>We can revise the example above by writing the condition expression <em>directly</em>
in the if-then-else statement, so we do not have to create the variable
<code class="docutils literal notranslate"><span class="pre">isAGreaterThanB</span></code>. In fact, we can write:</p>
<div class="highlight-java notranslate"><div class="highlight"><pre><span></span><span class="linenos">1</span><span class="k">if</span><span class="w"> </span><span class="p">(</span><span class="n">a</span><span class="w"> </span><span class="o">></span><span class="w"> </span><span class="n">b</span><span class="p">)</span><span class="w"> </span><span class="p">{</span>
<span class="linenos">2</span><span class="w"> </span><span class="n">System</span><span class="p">.</span><span class="na">out</span><span class="p">.</span><span class="na">println</span><span class="p">(</span><span class="s">"'"</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="s">" > "</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="n">b</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="s">"' is TRUE :-)"</span><span class="p">);</span>
<span class="linenos">3</span><span class="p">}</span><span class="w"> </span><span class="k">else</span><span class="w"> </span><span class="p">{</span>
<span class="linenos">4</span><span class="w"> </span><span class="n">System</span><span class="p">.</span><span class="na">out</span><span class="p">.</span><span class="na">println</span><span class="p">(</span><span class="s">"'"</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="s">" > "</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="n">b</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="s">"' is FALSE :-("</span><span class="p">);</span>
<span class="linenos">5</span><span class="p">}</span>
<span class="linenos">6</span><span class="n">System</span><span class="p">.</span><span class="na">out</span><span class="p">.</span><span class="na">println</span><span class="p">(</span><span class="s">"We got past the if-then-else statement"</span><span class="p">);</span>
</pre></div>
</div>
<p>Java executes this if-then-else by first computing the expression <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">></span> <span class="pre">b</span></code> (line
1); since its result is <code class="docutils literal notranslate"><span class="pre">false</span></code>, the execution “jumps” to the block of code
under the <code class="docutils literal notranslate"><span class="pre">else</span></code>, and produces the same output we have seen before. <em>(Try it on
the Java shell!)</em></p>
<p>To see a different outcome, you can now try the following:</p>
<ol class="arabic">
<li><p>assign to variable <code class="docutils literal notranslate"><span class="pre">a</span></code> a different value that is bigger than <code class="docutils literal notranslate"><span class="pre">b</span></code>, e.g.:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span><span class="hll">jshell> a = b * 2
</span>a ==> 84
| assigned to a : int
</pre></div>
</div>
</li>
<li><p>Then, copy&paste again the second if-then-else example above (the one
containing the condition expression <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">></span> <span class="pre">b</span></code>) on the Java shell, and
execute it. Observe that now the output is:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>'84 > 42' is TRUE :-)
We got past the if-then-else statement
</pre></div>
</div>
<div class="admonition tip">
<p class="admonition-title">Tip</p>
<p>On the Java shell, instead of copy&pasting code snippets that have been
already used, you can press the upwards arrow key <code class="docutils literal notranslate"><span class="pre">↑</span></code> to navigate the history
of previous code snippets, and press <code class="docutils literal notranslate"><span class="pre">⏎</span></code> to execute the one you select.</p>
</div>
</li>
</ol>
</section>
</div><div class="proof remark admonition" id="remark-reassigning-vars">
<span id="index-24"></span><p class="admonition-title"><span class="caption-number">Remark 8 </span> (Changing (re-assigning) a variable)</p>
<section class="remark-content" id="proof-content">
<p>As you can see in the <a class="reference internal" href="#eg-if-then-else-java-shell">Example 13</a> above, in Java it is
possible to declare a variable (e.g. <code class="docutils literal notranslate"><span class="pre">var</span> <span class="pre">a</span> <span class="pre">=</span> <span class="pre">10</span></code>) and later <strong>change that
variable</strong> with a new <strong>assignment</strong> (e.g. by writing <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">=</span> <span class="pre">b</span> <span class="pre">*</span> <span class="pre">2</span></code>). You can even
assign a new value to a variable by using <em>its own previous value</em>: for
instance, if <code class="docutils literal notranslate"><span class="pre">a</span></code> has value 10, and you write <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">=</span> <span class="pre">a</span> <span class="pre">+</span> <span class="pre">3</span></code>, the following happens:</p>
<ul class="simple">
<li><p>first, the expression <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">+</span> <span class="pre">3</span></code> is computed using the <em>current</em> value of <code class="docutils literal notranslate"><span class="pre">a</span></code>,
that is 10. Therefore, <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">+</span> <span class="pre">3</span></code> evaluates to 13;</p></li>
<li><p>then, the value 13 is assigned to <code class="docutils literal notranslate"><span class="pre">a</span></code>. Therefore, from now on, <code class="docutils literal notranslate"><span class="pre">a</span></code> has value
13; if you execute <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">=</span> <span class="pre">a</span> <span class="pre">+</span> <span class="pre">3</span></code> again, then <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">+</span> <span class="pre">3</span></code> will produce the result 16,
hence <code class="docutils literal notranslate"><span class="pre">a</span></code> will get the value 16.</p></li>
</ul>
<p>This may appear odd if you are used to mathematical terminology, where variables
are declared once and cannot be changed afterwards. However, we have seen
something very similar happen in
<a class="reference internal" href="basic-programming.html#sec-basic-programming-blinkenbits"><span class="std std-ref">BlinkenBits</span></a>, e.g. when we write
<span class="asm">r0 <- r0 + r1</span> to change the value contained in the register <code class="docutils literal notranslate"><span class="pre">r0</span></code> with the
result of the sum of the current value in <code class="docutils literal notranslate"><span class="pre">r0</span></code> plus the value in <code class="docutils literal notranslate"><span class="pre">r1</span></code>.</p>
<p>Indeed, the intuition here is that
<strong>in Java, a “variable” works like a register (or a memory location)</strong>: it
contains a value that <strong>can be changed</strong> while the program runs.
To do that in Java, we just write an assignment; therefore, when e.g.
<code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">=</span> <span class="pre">b</span> <span class="pre">*</span> <span class="pre">2</span></code> is executed, the old value that was contained in <code class="docutils literal notranslate"><span class="pre">a</span></code> is
overwritten with the result of the expression <code class="docutils literal notranslate"><span class="pre">b</span> <span class="pre">*</span> <span class="pre">2</span></code> (so, if <code class="docutils literal notranslate"><span class="pre">b</span></code> has value 42,
the variable <code class="docutils literal notranslate"><span class="pre">a</span></code> gets the new value 84).</p>
<p>Note that, when a variable is reassigned, then <strong>its type must be respected</strong>:
e.g. if the variable has type <code class="docutils literal notranslate"><span class="pre">int</span></code>, then we can only reassign a new value of
type <code class="docutils literal notranslate"><span class="pre">int</span></code>.</p>
</section>
</div></section>
<section id="if-then-statement">
<span id="sec-io-cond-strings-conditions-if-then"></span><span id="index-25"></span><h3>If-Then Statement<a class="headerlink" href="#if-then-statement" title="Permalink to this heading">#</a></h3>
<p>We can also write an <strong>if-then statement</strong> without the “else” part:</p>
<div class="highlight-java notranslate"><div class="highlight"><pre><span></span><span class="linenos">1</span><span class="k">if</span><span class="w"> </span><span class="p">(</span><span class="n">bool_expr</span><span class="p">)</span><span class="w"> </span><span class="p">{</span>
<span class="linenos">2</span><span class="w"> </span><span class="c1">// Statements that are executed when the result of 'bool_expr' is 'true'</span>
<span class="linenos">3</span><span class="p">}</span>
<span class="linenos">4</span><span class="c1">// Other statements can follow (optionally)</span>
</pre></div>
</div>
<p>which is just shorthand for:</p>
<div class="highlight-java notranslate"><div class="highlight"><pre><span></span><span class="linenos">1</span><span class="k">if</span><span class="w"> </span><span class="p">(</span><span class="n">bool_expr</span><span class="p">)</span><span class="w"> </span><span class="p">{</span>
<span class="linenos">2</span><span class="w"> </span><span class="c1">// Statements that are executed when the result of 'bool_expr' is 'true'</span>
<span class="linenos">3</span><span class="p">}</span><span class="w"> </span><span class="k">else</span><span class="w"> </span><span class="p">{</span>
<span class="linenos">4</span><span class="p">}</span>
<span class="linenos">5</span><span class="c1">// Other statements can follow (optionally)</span>
</pre></div>
</div>
<p>In other words, when <code class="docutils literal notranslate"><span class="pre">bool_expr</span></code> gives the result <code class="docutils literal notranslate"><span class="pre">false</span></code>, then the <code class="docutils literal notranslate"><span class="pre">else</span></code> code
block is executed (lines 3–4) — but since that block is empty, the program
just continues its execution with the statements that follow on line 5.</p>
<p>When represented in a flowchart, the if-then statement looks as follows —
and whenever we spot the following pattern in a flowchart, we should consider
using an if-then statement when writing the corresponding Java program.</p>
<p><img alt="Flowchart for if-then" src="_images/if-no-else.drawio.svg" /></p>
<div class="proof example admonition" id="eg-if-then-java-shell">
<p class="admonition-title"><span class="caption-number">Example 14 </span> (Using if-then on the Java shell)</p>
<section class="example-content" id="proof-content">
<p>Using the “if-then” statement, we can write an example similar to the one
in <a class="reference internal" href="#eg-if-then-else-java-shell">Example 13</a>, as follows:</p>
<div class="highlight-java notranslate"><div class="highlight"><pre><span></span><span class="linenos">1</span><span class="kd">var</span><span class="w"> </span><span class="n">message</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s">"FALSE :-("</span><span class="p">;</span>
<span class="linenos">2</span><span class="k">if</span><span class="w"> </span><span class="p">(</span><span class="n">a</span><span class="w"> </span><span class="o">></span><span class="w"> </span><span class="n">b</span><span class="p">)</span><span class="w"> </span><span class="p">{</span>
<span class="linenos">3</span><span class="w"> </span><span class="n">message</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s">"TRUE :-)"</span><span class="p">;</span>
<span class="linenos">4</span><span class="p">}</span>
<span class="linenos">5</span><span class="n">System</span><span class="p">.</span><span class="na">out</span><span class="p">.</span><span class="na">println</span><span class="p">(</span><span class="s">"'"</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="s">" > "</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="n">b</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="s">"' is "</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="n">message</span><span class="p">);</span>
</pre></div>
</div>
<p>When this code runs, the following happens:</p>
<ul class="simple">
<li><p>line 1 declares a variable <code class="docutils literal notranslate"><span class="pre">message</span></code> with the string <code class="docutils literal notranslate"><span class="pre">"FALSE</span> <span class="pre">:-("</span></code>;</p></li>
<li><p>line 2 checks the condition <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">></span> <span class="pre">b</span></code>:</p>
<ul>
<li><p>if the condition is true, then the block of code on lines 2–4 is executed.
Consequently, the value of the variable <code class="docutils literal notranslate"><span class="pre">message</span></code> is changed with the
string <code class="docutils literal notranslate"><span class="pre">"TRUE</span> <span class="pre">:-)"</span></code>. Then, the execution continues on line 5;</p></li>
<li><p>otherwise (i.e. if the condition on line 2 is false), the execution just
continues on line 5 — and consequently, the value of the variable
<code class="docutils literal notranslate"><span class="pre">message</span></code> is <em>not</em> changed and remains the string <code class="docutils literal notranslate"><span class="pre">"FALSE</span> <span class="pre">:-("</span></code>;</p></li>
</ul>
</li>
<li><p>finally, on line 5, a string with the current values of the variables <code class="docutils literal notranslate"><span class="pre">a</span></code>,
<code class="docutils literal notranslate"><span class="pre">b</span></code>, and <code class="docutils literal notranslate"><span class="pre">message</span></code> is displayed.</p></li>
</ul>
<p>You can experiment by running the code snippet above on the Java shell, using
different values of <code class="docutils literal notranslate"><span class="pre">a</span></code> and <code class="docutils literal notranslate"><span class="pre">b</span></code>. For example, if <code class="docutils literal notranslate"><span class="pre">a</span></code> is 10 and <code class="docutils literal notranslate"><span class="pre">b</span></code> is 42,
then the <code class="docutils literal notranslate"><span class="pre">System.out.println(...)</span></code> on line 5 displays:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>'10 > 42' is FALSE :-(
</pre></div>
</div>
<p>Otherwise, if e.g. <code class="docutils literal notranslate"><span class="pre">a</span></code> is 84 and <code class="docutils literal notranslate"><span class="pre">b</span></code> is 42, then the <code class="docutils literal notranslate"><span class="pre">System.out.println(...)</span></code>
on line 5 displays:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>'84 > 42' is TRUE :-)
</pre></div>
</div>
<div class="admonition note">
<p class="admonition-title">Note</p>
<p>While experimenting with the code snippet above, the Java
shell may display additional messages like:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>| modified variable message : String
| update overwrote variable message : String
</pre></div>
</div>
<p>The Java shell is just letting us know that a variable (in this case, <code class="docutils literal notranslate"><span class="pre">message</span></code>)
has been redeclared. This is not a problem for this examples.</p>
</div>
</section>
</div><span class="target" id="index-26"></span></section>
<section id="boolean-expressions">
<span id="sec-io-cond-strings-conditions-bool-expr"></span><span id="index-27"></span><h3>Boolean Expressions<a class="headerlink" href="#boolean-expressions" title="Permalink to this heading">#</a></h3>
<p>We have seen that, when writing
<a class="reference internal" href="#sec-io-cond-strings-conditions-if-then-else"><span class="std std-ref">if-then-else</span></a>
or <a class="reference internal" href="#sec-io-cond-strings-conditions-if-then"><span class="std std-ref">if-then</span></a> statements, or
<a class="reference internal" href="#sec-io-cond-strings-conditions-conditional-expr"><span class="std std-ref">conditional expressions</span></a>,
we need to provide an expression of type <code class="docutils literal notranslate"><span class="pre">boolean</span></code> that determines what is
computed and executed next (depending on whether the boolean expression
evaluates to <code class="docutils literal notranslate"><span class="pre">true</span></code> or <code class="docutils literal notranslate"><span class="pre">false</span></code>).</p>
<p>We have already seen
<a class="reference internal" href="java-first-taste.html#sec-basic-programming-java-jshell-booleans-strings"><span class="std std-ref">some expressions that produce boolean results by comparing two numbers</span></a>
using the <strong>relational operators</strong> <code class="docutils literal notranslate"><span class="pre"><</span></code> (“less than”), <code class="docutils literal notranslate"><span class="pre">></span></code> (“greater than”) or
<code class="docutils literal notranslate"><span class="pre">==</span></code> (“equal”); we have also used some of these operators in the
examples above. Java also provides the relational operators <code class="docutils literal notranslate"><span class="pre"><=</span></code> (“less than or
equal to”), <code class="docutils literal notranslate"><span class="pre">>=</span></code> (“greater than or equal to”), and <code class="docutils literal notranslate"><span class="pre">!=</span></code> (“not equal to”):
they also compare numbers and produce <code class="docutils literal notranslate"><span class="pre">true</span></code> or <code class="docutils literal notranslate"><span class="pre">false</span></code> as a result.</p>
<p>Java also allows to write expressions of type <code class="docutils literal notranslate"><span class="pre">boolean</span></code> using 3 <strong>logical
operators</strong> listed in <a class="reference internal" href="#table-logical-operators"><span class="std std-numref">Table 7</span></a> below.</p>
<table class="table" id="table-logical-operators">
<caption><span class="caption-number">Table 7 </span><span class="caption-text">Logical operators in Java</span><a class="headerlink" href="#table-logical-operators" title="Permalink to this table">#</a></caption>
<thead>
<tr class="row-odd"><th class="head"><p>Operator</p></th>
<th class="head"><p>Description</p></th>
<th class="head"><p>Example</p></th>
<th class="head"><p>Result</p></th>
</tr>
</thead>
<tbody>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">&&</span></code></p></td>
<td><p>Logical “and”</p></td>
<td><p><code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">&&</span> <span class="pre">b</span></code></p></td>
<td><p><code class="docutils literal notranslate"><span class="pre">true</span></code> if both <code class="docutils literal notranslate"><span class="pre">a</span></code> and <code class="docutils literal notranslate"><span class="pre">b</span></code> are <code class="docutils literal notranslate"><span class="pre">true</span></code>; <code class="docutils literal notranslate"><span class="pre">false</span></code> otherwise</p></td>
</tr>
<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">||</span></code></p></td>
<td><p>Logical “or”</p></td>
<td><p><code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">||</span> <span class="pre">b</span></code></p></td>
<td><p><code class="docutils literal notranslate"><span class="pre">false</span></code> if both <code class="docutils literal notranslate"><span class="pre">a</span></code> and <code class="docutils literal notranslate"><span class="pre">b</span></code> are <code class="docutils literal notranslate"><span class="pre">false</span></code>; <code class="docutils literal notranslate"><span class="pre">true</span></code> otherwise</p></td>
</tr>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">!</span></code></p></td>
<td><p>Logical “not”</p></td>
<td><p><code class="docutils literal notranslate"><span class="pre">!</span> <span class="pre">a</span></code></p></td>
<td><p><code class="docutils literal notranslate"><span class="pre">true</span></code> if <code class="docutils literal notranslate"><span class="pre">a</span></code> is <code class="docutils literal notranslate"><span class="pre">false</span></code>; <code class="docutils literal notranslate"><span class="pre">false</span></code> if <code class="docutils literal notranslate"><span class="pre">a</span></code> is <code class="docutils literal notranslate"><span class="pre">true</span></code></p></td>