-
Notifications
You must be signed in to change notification settings - Fork 49
/
Copy paththinkjava.tex
12564 lines (8903 loc) · 445 KB
/
thinkjava.tex
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
\documentclass[12pt]{book}
\title{Think Java}
\author{Allen B. Downey and Chris Mayfield}
\newcommand{\thetitle}{Think Java}
\newcommand{\thesubtitle}{How to Think Like a Computer Scientist}
\newcommand{\theauthors}{Allen B. Downey and Chris Mayfield}
\newcommand{\theversion}{6.1.7}
%%%% Both LATEX and PLASTEX
\usepackage{graphicx}
\usepackage{hevea}
\usepackage{makeidx}
\usepackage{setspace}
\makeindex
% automatically index glossary terms
\newcommand{\term}[1]{%
\item[#1:]\index{#1}}
\usepackage{amsmath}
\usepackage{amsthm}
% format end of chapter excercises
\newtheoremstyle{exercise}
{12pt} % space above
{12pt} % space below
{} % body font
{} % indent amount
{\bfseries} % head font
{} % punctuation
{12pt} % head space
{} % custom head
\theoremstyle{exercise}
\newtheorem{exercise}{Exercise}[chapter]
\newif\ifplastex
\plastexfalse
%%%% PLASTEX ONLY
\ifplastex
\usepackage{localdef}
\usepackage{url}
\newcount\anchorcnt
\newcommand*{\Anchor}[1]{%
\@bsphack%
\Hy@GlobalStepCount\anchorcnt%
\edef\@currentHref{anchor.\the\anchorcnt}%
\Hy@raisedlink{\hyper@anchorstart{\@currentHref}\hyper@anchorend}%
\M@gettitle{}\label{#1}%
\@esphack%
}
% code listing environments:
% we don't need these for plastex because they get replaced
% by preprocess.py
%\newenvironment{code}{\begin{verbatim}}{\end{verbatim}}
%\newenvironment{stdout}{\begin{verbatim}}{\end{verbatim}}
% inline syntax formatting
\newcommand{\java}{\verb}%}
%%%% LATEX ONLY
\else
\input{latexonly}
\fi
%%%% END OF PREAMBLE
\begin{document}
\frontmatter
%%%% PLASTEX ONLY
\ifplastex
\maketitle
%%%% LATEX ONLY
\else
\begin{latexonly}
%--half title-------------------------------------------------
\thispagestyle{empty}
\begin{flushright}
\vspace*{2.0in}
\begin{spacing}{3}
{\huge \thetitle} \\
{\Large \thesubtitle}
\end{spacing}
\vspace{0.25in}
Version \theversion
\vfill
\end{flushright}
%--verso------------------------------------------------------
\newpage
\thispagestyle{empty}
\quad
%--title page-------------------------------------------------
\newpage
\thispagestyle{empty}
\begin{flushright}
\vspace*{2.0in}
\begin{spacing}{3}
{\huge \thetitle} \\
{\Large \thesubtitle}
\end{spacing}
\vspace{0.25in}
Version \theversion
\vspace{1in}
{\Large \theauthors}
\vspace{0.5in}
{\Large Green Tea Press}
{\small Needham, Massachusetts}
\vfill
\end{flushright}
%--copyright--------------------------------------------------
\newpage
\thispagestyle{empty}
Copyright \copyright ~2016 \theauthors.
\vspace{0.2in}
\begin{flushleft}
Green Tea Press \\
9 Washburn Ave \\
Needham, MA 02492
\end{flushleft}
Permission is granted to copy, distribute, and/or modify this work under the terms of the Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License, which is available at \url{http://creativecommons.org/licenses/by-nc-sa/3.0/}.
The original form of this book is \LaTeX\ source code.
Compiling this code has the effect of generating a device-independent representation of the book, which can be converted to other formats and printed.
The \LaTeX\ source for this book is available from \url{http://thinkjava.org}.
%--table of contents------------------------------------------
\cleardoublepage
\setcounter{tocdepth}{1}
\tableofcontents
\end{latexonly}
%--HTML title page--------------------------------------------
\begin{htmlonly}
\vspace{1em}
{\Large \thetitle: \thesubtitle}
{\large \theauthors}
Version \theversion
\vspace{1em}
Copyright \copyright ~2016 \theauthors.
Permission is granted to copy, distribute, and/or modify this work under the terms of the Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License, which is available at \url{http://creativecommons.org/licenses/by-nc-sa/3.0/}.
\vspace{1em}
\end{htmlonly}
%-------------------------------------------------------------
% END OF THE PART WE SKIP FOR PLASTEX
\fi
\chapter*{Preface}
\label{preface}
\markboth{PREFACE}{PREFACE}
\addcontentsline{toc}{chapter}{Preface}
{\it Think Java} is an introduction to computer science and programming intended for readers with little or no experience.
We start with the most basic concepts and are careful to define all terms when they are first used.
The book presents each new idea in a logical progression.
Larger topics, like recursion and object-oriented programming, are divided into smaller examples and introduced over the course of several chapters.
This book is intentionally concise.
Each chapter is 12--14 pages and covers the material for one week of a college course.
It is not meant to be a comprehensive presentation of Java, but rather, an initial exposure to programming constructs and techniques.
We begin with small problems and basic algorithms and work up to object-oriented design.
In the vocabulary of computer science pedagogy, this book uses the ``objects late'' approach.
\section*{The philosophy behind the book}
Here are the guiding principles that make the book the way it is:
\begin{itemize}
\item {\em One concept at a time.}
We break down topics that give beginners trouble into a series of small steps, so that they can exercise each new concept in isolation before continuing.
\item {\em Balance of Java and concepts.}
The book is not primarily about Java; it uses code examples to demonstrate computer science.
Most chapters start with language features and end with concepts.
\item {\em Conciseness.}
An important goal of the book is to be small enough so that students can read and understand the entire text in a one-semester college or AP course.
%Students can read 1--2 chapters per week, depending on the pace of the instruction.
\item {\em Emphasis on vocabulary.}
We try to introduce the minimum number of terms and define them carefully when they are first used.
We also organize them in glossaries at the end of each chapter.
\item {\em Program development.}
There are many strategies for writing programs, including bottom-up, top-down, and others.
We demonstrate multiple program development techniques, allowing readers to choose methods that work best for them.
\item {\em Multiple learning curves.}
To write a program, you have to understand the algorithm, know the programming language, and be able to debug errors.
We discuss these and other aspects throughout the book, and include an appendix that summarizes our advice.
%\item {\em Spiral approach.}
%Some concepts take time to sink in.
%The more difficult ideas in the book, like recursion, appear several times.
%By coming back to these topics, we give learners a chance to review and reinforce.
%\item {\em Keep it simple.}
%We use the minimum amount of Java to get the maximum amount of programming ability.
%The goal of this book is to teach fundamental ideas from computer science, not Java.
%We leave out some language features, like the \java{switch} statement, that are unnecessary, and we present only a few of the many classes in the Java libraries.
\end{itemize}
\section*{Object-oriented programming}
Some Java books introduce classes and objects immediately; others begin with procedural programming and transition to object-oriented more gradually.
Many of Java's object-oriented features are motivated by problems with previous languages, and their implementations are influenced by this history.
Some of these features are hard to explain when people aren't familiar with the problems they solve.
We get to object-oriented programming as quickly as possible, limited by the requirement that we introduce concepts one at a time, as clearly as possible, in a way that allows readers to practice each idea in isolation before moving on.
So it takes some time to get there.
But you can't write Java programs (even hello world) without encountering object-oriented features.
In some cases we explain a feature briefly when it first appears, and then explain it more deeply later on.
This book is well suited to prepare students for the AP Computer Science A exam, which includes object-oriented design and implementation.
(AP is a registered trademark of the College Board.)
We introduce nearly every topic in the ``AP Java subset'' with a few exceptions.
A mapping of {\it Think Java} section numbers to the current AP course description is available on our website: \url{http://thinkjava.org}.
\section*{Appendixes}
The chapters of this book are meant to be read in order, because each one builds on the previous one.
We also include three appendixes with material that can be read at any time:
\begin{description}
\item{\bf Appendix A: Development tools}
The steps for compiling, running, and debugging Java code depend on the details of the development environment and operating system.
We avoided putting these details in the main text, because they can be distracting.
Instead, we provide this appendix with a brief introduction to DrJava -- an interactive development environment (IDE) that is helpful for beginners -- and other development tools, including Checkstyle for code quality and JUnit for testing.
\item{\bf Appendix B: Java 2D graphics}
Java provides libraries for working with graphics and animation, and these topics can be engaging for students.
The libraries require object-oriented features that readers will not completely understand until after Chapter~\ref{classes}, but they can be used much earlier.
\item{\bf Appendix C: Debugging}
We provide debugging suggestions throughout the book, but we also collect our debugging advice in an appendix.
We recommend that readers review this appendix several times as they work through the book.
\end{description}
\section*{Using the code examples}
\label{code}
Most of the code examples in this book are available from a Git repository at \url{https://github.com/AllenDowney/ThinkJavaCode}.
Git is a ``version control system'' that allows you to keep track of the files that make up a project.
A collection of files under Git's control is called a ``repository''.
\index{repository}
\index{GitHub}
GitHub is a hosting service that provides storage for Git repositories and a convenient web interface.
It provides several ways to work with the code:
\begin{itemize}
\item You can create a copy of the repository on GitHub by pressing the {\sf Fork} button.
If you don't already have a GitHub account, you'll need to create one.
After forking, you'll have your own repository on GitHub that you can use to keep track of code you write.
Then you can ``clone'' the repository, which downloads a copy of the files to your computer.
\item Alternatively, you could clone the repository without forking.
If you choose this option, you don't need a GitHub account, but you won't be able to save your changes on GitHub.
\item If you don't want to use Git at all, you can download the code in a ZIP archive using the {\sf Download ZIP} button on the GitHub page, or this link: \url{http://tinyurl.com/ThinkJavaCodeZip}.
\end{itemize}
After you clone the repository or unzip the ZIP file, you should have a directory called {\tt ThinkJavaCode} with a subdirectory for each chapter in the book.
All examples in this book were developed and tested using Java SE Development Kit 8.
If you are using a more recent version, the examples in this book should still work.
If you are using an older version, some of them may not.
\section*{Contributors over the years}
%This list starts with the 4th Edition, so it omits many people who contributed to earlier versions.
Many people have sent corrections and suggestions, and we appreciate their valuable feedback!
\begin{itemize}
\item Ellen Hildreth used this book to teach Data Structures at Wellesley College and submitted a whole stack of corrections, along with some great suggestions.
\item Tania Passfield pointed out that some glossaries had leftover terms that no longer appeared in the text.
\item Elizabeth Wiethoff noticed that the series expansion of $\exp(-x^2)$ was wrong.
She has also worked on a Ruby version of the book.
\item Matt Crawford sent in a whole patch file full of corrections.
\item Chi-Yu Li pointed out a typo and an error in one of the code examples.
\item Doan Thanh Nam corrected an example.
\item Muhammad Saied translated the book into Arabic, and found several errors in the process.
\item Marius Margowski found an inconsistency in a code example.
\item Leslie Klein discovered another error in the series expansion of $\exp(-x^2)$, identified typos in the card array figures, and gave helpful suggestions to clarify several exercises.
\item Micah Lindstrom reported half a dozen typos and sent corrections.
\item James Riely ported the textbook source from LaTeX to Sphinx.
\\ \url{http://fpl.cs.depaul.edu/jriely/thinkapjava/}
\item Peter Knaggs ported the book to C\#.
\\ \url{http://www.rigwit.co.uk/think/sharp/}
\item Heidi Gentry-Kolen recorded several video lectures that follow the book.
\\ \url{https://www.youtube.com/user/digipipeline}
% ENDCONTRIB
\end{itemize}
We are especially grateful to our technical reviewers: Blythe Samuels, David Wisneski, and Stephen Rose.
They found errors, made many great suggestions, and helped make the book much better.
Additional contributors who found one or more typos: Stijn Debrouwere, Guy Driesen, Andai Velican, Chris Kuszmaul, Daniel Kurikesu, Josh Donath, Rens Findhammer, Elisa Abedrapo, Yousef BaAfif, Bruce Hill, Matt Underwood, Isaac Sultan, Dan Rice, Robert Beard, Daniel Pierce, Michael Giftthaler, Chris Fox, Min Zeng, Markus Geuss, and Waldo Ribeiro.
If you have additional comments or ideas about the text, please send them to: \href{mailto:[email protected]}{\tt [email protected]}.
\mainmatter
\chapter{The way of the program}
\label{theway}
The goal of this book is to teach you to think like a computer scientist.
This way of thinking combines some of the best features of mathematics, engineering, and natural science.
Like mathematicians, computer scientists use formal languages to denote ideas, specifically computations.
Like engineers, they design things, assembling components into systems and evaluating trade-offs among alternatives.
And like scientists, they observe the behavior of complex systems, form hypotheses, and test predictions.
\index{problem solving}
The single most important skill for a computer scientist is {\bf problem solving}.
It involves the ability to formulate problems, think creatively about solutions, and express solutions clearly and accurately.
As it turns out, the process of learning to program is an excellent opportunity to develop problem-solving skills.
That's why this chapter is called, ``The way of the program''.
On one level you will be learning to program, a useful skill by itself.
But on another level you will use programming as a means to an end.
As we go along, that end will become clearer.
%Learning how to think in terms of computation is much more valuable than just learning how to write code.
\section{What is programming?}
\index{program}
A {\bf program} is a sequence of instructions that specifies how to perform a computation.
%\footnote{This definition does not apply to all programming languages; for alternatives, see \url{https://en.wikipedia.org/wiki/Declarative_programming}.}
The computation might be something mathematical, like solving a system of equations or finding the roots of a polynomial.
It can also be a symbolic computation, like searching and replacing text in a document or (strangely enough) compiling a program.
The details look different in different languages, but a few basic instructions appear in just about every language.
\begin{description}
\item[input:] Get data from the keyboard, a file, a sensor, or some other device.
\item[output:] Display data on the screen, or send data to a file or other device.
\item[math:] Perform basic mathematical operations like addition and division.
\item[decisions:] Check for certain conditions and execute the appropriate code.
\item[repetition:] Perform some action repeatedly, usually with some variation.
\end{description}
\index{programming}
Believe it or not, that's pretty much all there is to it.
Every program you've ever used, no matter how complicated, is made up of small instructions that look much like these.
So you can think of {\bf programming} as the process of breaking down a large, complex task into smaller and smaller subtasks.
The process continues until the subtasks are simple enough to be performed with the basic instructions provided by the computer.
\section{What is computer science?}
One of the most interesting aspects of writing programs is deciding how to solve a particular problem, especially when there are multiple solutions.
For example, there are numerous ways to sort a list of numbers, and each way has its advantages.
%(see \url{http://www.sorting-algorithms.com/})
In order to determine which way is best for a given situation, we need techniques for describing and analyzing solutions formally.
%That is where computer science comes in.
\index{computer science}
\index{algorithm}
{\bf Computer science} is the science of algorithms, including their discovery and analysis.
An {\bf algorithm} is a sequence of steps that specifies how to solve a problem.
Some algorithms are faster than others, and some use less space in computer memory.
As you learn to develop algorithms for problems you haven't solved before, you also learn to think like a computer scientist.
%It's much more fun to discover new algorithms than to write the code for solutions that other people came up with!
\index{bug}
\index{debugging}
Designing algorithms and writing code is difficult and error-prone.
For historical reasons, programming errors are called {\bf bugs}, and the process of tracking them down and correcting them is called {\bf debugging}.
As you learn to debug your programs, you will develop new problem-solving skills.
You will need to think creatively when unexpected errors happen.
Although it can be frustrating, debugging is an intellectually rich, challenging, and interesting part of computer programming.
In some ways, debugging is like detective work.
You are confronted with clues, and you have to infer the processes and events that led to the results you see.
Thinking about how to correct programs and improve their performance sometimes even leads to the discovery of new algorithms.
\section{Programming languages}
\index{high-level language}
\index{language!high-level}
The programming language you will learn is Java, which is a {\bf high-level language}.
Other high-level languages you may have heard of include Python, C and C++, Ruby, and JavaScript.
\index{low-level language}
\index{language!low-level}
Before they can run, programs in high-level languages have to be translated into a {\bf low-level language}, also called ``machine language''.
This translation takes some time, which is a small disadvantage of high-level languages.
But high-level languages have two advantages:
\begin{itemize}
\item It is {\em much} easier to program in a high-level language.
Programs take less time to write, they are shorter and easier to read, and they are more likely to be correct.
\index{portable}
\item High-level languages are {\bf portable}, meaning they can run on different kinds of computers with few or no modifications.
Low-level programs can only run on one kind of computer, and have to be rewritten to run on another.
\end{itemize}
\index{interpret}
Two kinds of programs translate high-level languages into low-level languages: interpreters and compilers.
An {\bf interpreter} reads a high-level program and executes it, meaning that it does what the program says.
It processes the program a little at a time, alternately reading lines and performing computations.
Figure~\ref{fig.interpreter} shows the structure of an interpreter.
\begin{figure}[!ht]
\begin{center}
\includegraphics{figs/interpreter.pdf}
\caption{How interpreted languages are executed.}
\label{fig.interpreter}
\end{center}
\end{figure}
\index{compile}
\index{source code}
\index{object code}
\index{executable}
In contrast, a {\bf compiler} reads the entire program and translates it completely before the program starts running.
In this context, the high-level program is called the {\bf source code}, and the translated program is called the {\bf object code} or the {\bf executable}.
Once a program is compiled, you can execute it repeatedly without further translation.
As a result, compiled programs often run faster than interpreted programs.
% Figure 1.2 shows the structure of a compiler.
\index{byte code}
\index{virtual machine}
\index{JVM}
Java is {\em both} compiled and interpreted.
Instead of translating programs directly into machine language, the Java compiler generates {\bf byte code}.
Similar to machine language, byte code is easy and fast to interpret.
But it is also portable, so it is possible to compile a Java program on one machine, transfer the byte code to another machine, and run the byte code on the other machine.
The interpreter that runs byte code is called a ``Java Virtual Machine'' (JVM).
%This ability is an advantage of Java over some other high-level languages.
\begin{figure}[!ht]
\begin{center}
\includegraphics{figs/compiler.pdf}
\caption{The process of compiling and running a Java program.}
\label{fig.compiler}
\end{center}
\end{figure}
Figure~\ref{fig.compiler} shows the steps of this process.
Although it might seem complicated, these steps are automated for you in most program development environments.
Usually you only have to press a button or type a single command to compile and run your program.
On the other hand, it is important to know what steps are happening in the background, so if something goes wrong you can figure out what it is.
\section{The hello world program}
\label{hello}
\index{hello world}
Traditionally, the first program you write when learning a new programming language is called the hello world program.
All it does is display the words ``Hello, World!''\ on the screen.
In Java, it looks like this:
% NOTE(ABD): I changed a lot of ``print'' to ``display'', partly to be
% more precise, but also to reduce the number of times ``print'' appears,
% which is a lot!
% height = 130 + 15 * num_lines
\begin{trinket}[235]{Hello.java}
public class Hello {
public static void main(String[] args) {
// generate some simple output
System.out.println("Hello, World!");
}
}
\end{trinket}
When this program runs it displays:
\begin{stdout}
Hello, World!
\end{stdout}
Notice that the output does not include the quotation marks.
%\index{public}
%\index{static}
%The word \java{public} means the code can be accessed from other source files.
%The word \java{static} means that memory is allocated for the program in advance.
%Unfortunately, this simple example uses language features (like \java{public} and \java{static}) that are hard to explain.
%In fact, we won't be able to explain all of them for several more chapters.
%But we can start with the structure.
\index{class!definition}
\index{method!definition}
\index{statement}
\index{print statement}
Java programs are made up of {\em class} and {\em method} definitions, and methods are made up of {\em statements}.
A {\bf statement} is a line of code that performs a basic operation.
In the hello world program, this line is a {\bf print statement} that displays a message on the screen:
\begin{code}
System.out.println("Hello, World!");
\end{code}
\index{println}
\index{semicolon}
\java{System.out.println} displays results on the screen; the name \java{println} stands for ``print line''.
Confusingly, {\em print} can mean both ``display on the screen'' and ``send to the printer''.
In this book, we'll try to say ``display'' when we mean output to the screen.
Like most statements, the print statement ends with a semicolon (\java{;}).
\index{case-sensitive}
Java is ``case-sensitive'', which means that uppercase and lowercase are not the same.
In this example, \java{System} has to begin with an uppercase letter; \java{system} and \java{SYSTEM} won't work.
\index{method}
A {\bf method} is a named sequence of statements.
This program defines one method named \java{main}:
\begin{code}
public static void main(String[] args)
\end{code}
\index{main}
The name and format of \java{main} is special: when the program runs, it starts at the first statement in \java{main} and ends when it finishes the last statement.
Later, we will see programs that define more than one method.
\index{class}
A {\bf class} is a collection of methods.
This program defines a class named \java{Hello}.
You can give a class any name you like, but it is conventional to start with a capital letter.
The name of the class has to match the name of the file it is in, so this class has to be in a file named {\tt Hello.java}.
Java uses squiggly braces (\{ and \}) to group things together.
In {\tt Hello.java}, the outermost braces contain the class definition, and the inner braces contain the method definition.
\index{comment!inline}
\index{statement!comment}
The line that begins with two slashes (\java{//}) is a {\bf comment}, which is a bit of English text that explains the code.
When the compiler sees \java{//}, it ignores everything from there until the end of the line.
Comments have no effect on the execution of the program, but they make it easier for other programmers (and your future self) to understand what you meant to do.
\section{Displaying strings}
You can put as many statements as you like in \java{main}.
For example, to display more than one line of output:
\begin{trinket}[250]{Hello.java}
public class Hello {
public static void main(String[] args) {
// generate some simple output
System.out.println("Hello, World!"); // first line
System.out.println("How are you?"); // another line
}
}
\end{trinket}
As this example shows, you can put comments at the end of a line as well as on lines all by themselves.
\index{quote mark}
\index{string}
\index{type!String}
\index{char}
Phrases that appear in quotation marks are called {\bf strings}, because they contain a sequence of ``characters'' strung together.
Characters can be letters, numbers, punctuation marks, symbols, spaces, tabs, etc.
\index{newline}
\index{print}
\index{statement!print}
\java{System.out.println} appends a special character, called a {\bf newline}, that moves to the beginning of the next line.
If you don't want a newline at the end, you can use \java{print} instead of \java{println}:
\begin{trinket}[235]{Goodbye.java}
public class Goodbye {
public static void main(String[] args) {
System.out.print("Goodbye, ");
System.out.println("cruel world");
}
}
\end{trinket}
\label{goodbye}
In this example, the first statement does not add a newline, so the output appears on a single line as {\tt Goodbye, cruel world}.
Notice that there is a space at the end of the first string, which appears in the output.
\section{Escape sequences}
It is possible to display multiple lines of output in just one line of code.
You just have to tell Java where to put the line breaks.
\begin{trinket}[220]{Hello.java}
public class Hello {
public static void main(String[] args) {
System.out.print("Hello!\nHow are you doing?\n");
}
}
\end{trinket}
The output is two lines, each ending with a newline character:
\begin{stdout}
Hello!
How are you doing?
\end{stdout}
\index{escape sequence}
The \verb"\n" is an {\bf escape sequence}, which is a sequence of characters that represents a special character.
The backslash allows you to ``escape'' the string's literal interpretation.
Notice there is no space between \verb"\n" and \verb"How".
If you add a space there, there will be a space at the beginning of the second line.
\begin{table}[!ht]
\begin{center}
\begin{tabular}{|c|c|}
\hline
\verb"\n" & newline \\
\hline
\verb"\t" & tab \\
\hline
\verb'\"' & double quote \\
\hline
\verb"\\" & backslash \\
\hline
\end{tabular}
\caption{Common escape sequences}
\end{center}
\end{table}
\index{quote mark}
Another common use of escape sequences is to have quotation marks inside of strings.
Since double quotes indicate the beginning and end of strings, you need to escape them with a backslash.
\begin{code}
System.out.println("She said \"Hello!\" to me.");
\end{code}
The result is:
\begin{stdout}
She said "Hello!" to me.
\end{stdout}
\section{Formatting code}
\label{formatting}
In Java programs, some spaces are required.
For example, you need at least one space between words, so this program is not legal:
\begin{code}
publicclassGoodbye{
publicstaticvoidmain(String[] args) {
System.out.print("Goodbye, ");
System.out.println("cruel world");
}
}
\end{code}
But most other spaces are optional.
For example, this program is legal:
\begin{trinket}[220]{Goodbye.java}
public class Goodbye {
public static void main(String[] args) {
System.out.print("Goodbye, ");
System.out.println("cruel world");
}
}
\end{trinket}
The newlines are optional, too.
So we could just write:
\begin{trinket}[175]{Goodbye.java}
public class Goodbye { public static void main(String[] args)
{ System.out.print("Goodbye, "); System.out.println
("cruel world");}}
\end{trinket}
It still works, but the program is getting harder and harder to read.
Newlines and spaces are important for organizing your program visually, making it easier to understand the program and find errors when they occur.
Many editors will automatically format source code with consistent indenting and line breaks.
For example, in DrJava (see Appendix~\ref{development}) you can indent the code by selecting all text ({\sf Ctrl+A}) and pressing the {\sf Tab} key.
%\section{Style guidelines}
%\index{whitespace}
%
%As we saw in Section~\ref{formatting}, the compiler generally ignores spaces, tabs, and newlines.
%These characters, which are called {\bf whitespace}, affect the format of the code, but they don't affect its behavior.
%You have a lot of freedom in how you arrange your code.
%However, with that freedom comes responsibility, both to yourself (when you look at the code in the future) and others who will be reading, understanding, and debugging it.
\index{Google style}
Organizations that do a lot of software development usually have strict guidelines on how to format source code.
For example, Google publishes its Java coding standards for use in open-source projects: \url{http://google.github.io/styleguide/javaguide.html}.
%It is easier to understand a large codebase when all the source code is formatted consistently.
%Plus following style guidelines helps you to avoid common programming mistakes that are difficult to debug.
You might not understand these guidelines now, because they refer to language features we haven't yet seen.
But you might want to refer back to them periodically as you read this book.
%In the meantime, there are many software tools that help programmers find and correct style issues.
%One of the most popular is Checkstyle, which enforces most of Google's guidelines.
%Instructions for downloading and running Checkstyle are in Appendix~\ref{checkstyle}.
\section{Debugging code}
\label{sec:examples}
It is a good idea to read this book in front of a computer so you can try out the examples as you go.
You can run many of the examples directly in DrJava's Interactions Pane (see Appendix~\ref{development}).
But if you put the code in a source file, it will be easier to try out variations.
%For more information on working with DrJava, see Appendix~\ref{development}.
\index{error!message}
Whenever you are experimenting with a new feature, you should also try to make mistakes.
For example, in the hello world program, what happens if you leave out one of the quotation marks?
What if you leave out both?
What if you spell \java{println} wrong?
These kinds of experiments help you remember what you read.
They also help with debugging, because you learn what the error messages mean.
It is better to make mistakes now and on purpose than later on and accidentally.
\index{experimental debugging}
\index{debugging!experimental}
%\index{Holmes, Sherlock}
%\index{Doyle, Arthur Conan}
Debugging is like an experimental science: once you have an idea about what is going wrong, you modify your program and try again.
If your hypothesis was correct, then you can predict the result of the modification, and you take a step closer to a working program.
If your hypothesis was wrong, you have to come up with a new one.
%As Sherlock Holmes pointed out, ``When you have eliminated the impossible, whatever remains, however improbable, must be the truth.''
%(A.~Conan Doyle, {\em The Sign of Four}.)
Programming and debugging should go hand in hand.
Don't just write a bunch of code and then perform trial and error debugging until it all works.
Instead, start with a program that does {\em something} and make small modifications, debugging them as you go, until the program does what you want.
That way you will always have a working program, and it will be easier to isolate errors.
\index{Linux}
\index{Torvalds, Linus}
\index{Greenfield, Larry}
A great example of this principle is the Linux operating system, which contains millions of lines of code.
It started out as a simple program Linus Torvalds used to explore the Intel 80386 chip.
According to Larry Greenfield in {\it The Linux Users' Guide}, ``One of Linus's earlier projects was a program that would switch between printing AAAA and BBBB.
This later evolved to Linux.''
%Later chapters will make more suggestions about debugging and other programming practices.
Finally, programming sometimes brings out strong emotions.
If you are struggling with a difficult bug, you might feel angry, despondent, or embarrassed.
Remember that you are not alone, and most, if not all, programmers have had similar experiences.
Don't hesitate to reach out to a friend and ask questions!
\section{Vocabulary}
Throughout the book, we try to define each term the first time we use it.
At the end of each chapter, we include the new terms and their definitions in order of appearance.
If you spend some time learning this vocabulary, you will have an easier time reading the following chapters.
\begin{description}
\term{problem solving}
The process of formulating a problem, finding a solution, and expressing the solution.
\term{program}
A sequence of instructions that specifies how to perform tasks on a computer.
\term{programming}
The application of problem solving to creating executable computer programs.
\term{computer science}
The scientific and practical approach to computation and its applications.
\term{algorithm}
A procedure or formula for solving a problem, with or without a computer.
\term{bug}
An error in a program.
\term{debugging}
The process of finding and removing errors.
\term{high-level language}
A programming language that is designed to be easy for humans to read and write.
\term{low-level language}
A programming language that is designed to be easy for a computer to run.
Also called ``machine language'' or ``assembly language''.
\term{portable}
The ability of a program to run on more than one kind of computer.
\term{interpret}
To run a program in a high-level language by translating it one line at a time and immediately executing the corresponding instructions.
\term{compile}
To translate a program in a high-level language into a low-level language, all at once, in preparation for later execution.
\term{source code}
A program in a high-level language, before being compiled.
\term{object code}
The output of the compiler, after translating the program.
\term{executable}
Another name for object code that is ready to run on specific hardware.
\term{byte code}
A special kind of object code used for Java programs.
Byte code is similar to a low-level language, but it is portable like a high-level language.
\term{statement}
Part of a program that specifies one step of an algorithm.
\term{print statement}
A statement that causes output to be displayed on the screen.
\term{method}
A named sequence of statements.
\term{class}
For now, a collection of related methods.
(We will see later that there is more to it.)
\term{comment}
A part of a program that contains information about the program but has no effect when the program runs.
\term{string}
A sequence of characters; the primary data type for text.
\term{newline}
A special character signifying the end of a line of text.
Also known as line ending, end of line (EOL), or line break.
\term{escape sequence}
A sequence of code that represents a special character when used inside a string.
%\term{whitespace}
%Newlines, tab characters, and other spaces in a source program.
%Whitespace characters are used to separate words, but other than that, they don't affect the behavior of the program.
\end{description}
\section{Exercises}
At the end of each chapter, we include exercises you can do with the things you've learned.
We encourage you to at least attempt every problem.
You can't learn to program only by reading about it; you have to practice.
Before you can compile and run Java programs, you might have to download and install a few tools.
There are many good options, but we recommend DrJava, which is an ``integrated development environment'' (IDE) well suited for beginners.
Instructions for getting started are in Appendix~\ref{drjava}.
The code for this chapter is in the {\tt ch01} directory of {\tt ThinkJavaCode}.
See page~\pageref{code} for instructions on how to download the repository.
Before you start the exercises, we recommend that you compile and run the examples.
\begin{exercise}
Computer scientists have the annoying habit of using common English words to mean something other than their common English meaning.
For example, in English, statements and comments are the same thing, but in programs they are different.
\begin{enumerate}
\item In computer jargon, what's the difference between a statement and a comment?
\item What does it mean to say that a program is portable?
\item In common English, what does the word compile mean?
\item What is an executable? Why is that word used as a noun?
\end{enumerate}
The glossary at the end of each chapter is intended to highlight words and phrases that have special meanings in computer science.
When you see familiar words, don't assume that you know what they mean!