forked from AllenDowney/ThinkJava
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththinkjava.tex
More file actions
3509 lines (2548 loc) · 138 KB
/
Copy paththinkjava.tex
File metadata and controls
3509 lines (2548 loc) · 138 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
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}
\newcommand{\thetitle}{Think Java: How to Think Like a Computer Scientist}
\title{\thetitle}
\newcommand{\theauthors}{Allen Downey and Chris Mayfield}
\author{\theauthors}
\newcommand{\theversion}{Version 6.0 Draft -- \today}
\date{\theversion}
\usepackage{geometry}
\geometry{
width=5.5in,
height=8.5in,
hmarginratio=3:2,
vmarginratio=1:1,
includehead=true,
headheight=15pt
}
% paragraph spacing
\setlength{\parindent}{0pt} % 17.62482pt
\setlength{\parskip}{12pt plus 4pt minus 4pt} % 0.0pt plus 1.0pt
\linespread{1.05}
\def\arraystretch{1.5}
% list spacing
\setlength{\topsep}{5pt plus 2pt minus 3pt} % 10.0pt plus 4.0pt minus 6.0pt
\setlength{\partopsep}{-6pt plus 2pt minus 2pt} % 3.0pt plus 2.0pt minus 2.0pt
\setlength{\itemsep}{0pt} % 5.0pt plus 2.5pt minus 1.0pt
% these are copied from tex/latex/base/book.cls
% all I changed is afterskip
\makeatletter
\renewcommand{\section}{\@startsection {section}{1}{\z@}%
{-3.5ex \@plus -1ex \@minus -.2ex}%
{0.7ex \@plus.2ex}%
{\normalfont\Large\bfseries}}
\renewcommand\subsection{\@startsection{subsection}{2}{\z@}%
{-3.25ex\@plus -1ex \@minus -.2ex}%
{0.3ex \@plus .2ex}%
{\normalfont\large\bfseries}}
\renewcommand\subsubsection{\@startsection{subsubsection}{3}{\z@}%
{-3.25ex\@plus -1ex \@minus -.2ex}%
{0.3ex \@plus .2ex}%
{\normalfont\normalsize\bfseries}}
\makeatother
% table of contents vertical spacing
\usepackage{tocloft}
\setlength\cftparskip{8pt plus 4pt minus 4pt}
% The following line adds a little extra space to the column
% in which the Section numbers appear in the table of contents
\makeatletter
\renewcommand{\l@section}{\@dottedtocline{1}{1.5em}{3.0em}}
\makeatother
% customize page headers
\usepackage{fancyhdr}
\pagestyle{fancyplain}
\renewcommand{\chaptermark}[1]{\markboth{Chapter \thechapter ~~ #1}{}}
\renewcommand{\sectionmark}[1]{\markright{\thesection ~~ #1}}
\lhead[\fancyplain{}{\bfseries\thepage}]%
{\fancyplain{}{\bfseries\rightmark}}
\rhead[\fancyplain{}{\bfseries\leftmark}]%
{\fancyplain{}{\bfseries\thepage}}
\cfoot{}
%\rfoot{\textcolor{gray}{\tiny ThinkJava Draft \today}}
% balanced index with TOC entry
\usepackage{makeidx}
\makeindex
%\usepackage[totoc]{idxlayout}
% automatically index glossary terms
\newcommand{\term}[1]{%
\index{#1}
\item[#1:]}
% TODO: doesn't work with plastex
%\newcommand{\term}[1]{\item[#1:]}
% where to find graphics
\usepackage{graphicx}
%\graphicspath{{figs/}}
%% tweak spacing of figures and captions
%\usepackage{floatrow}
%\usepackage{caption}
%\captionsetup{
% font=small,
% labelformat=empty,
% justification=centering,
% skip=4pt
%}
% format end of chapter excercises
\usepackage{amsmath}
\usepackage{amsthm}
\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]
% colors for code listings and output
\usepackage{xcolor}
\definecolor{bgcolor}{HTML}{FAFAFA}
\definecolor{comment}{HTML}{007C00}
\definecolor{keyword}{HTML}{0000FF}
\definecolor{strings}{HTML}{B20000}
% syntax highlighting in code listings
\usepackage{textcomp}
\usepackage{listings}
\lstset{
language=java,
basicstyle=\ttfamily,
backgroundcolor=\color{bgcolor},
commentstyle=\color{comment},
keywordstyle=\color{keyword},
stringstyle=\color{strings},
columns=fullflexible,
keepspaces=true,
showstringspaces=false,
upquote=true,
aboveskip=\parskip,
belowskip=\parskip
}
% code listing environments
\lstnewenvironment{code}
{\minipage{\linewidth}}
{\endminipage}
\lstnewenvironment{stdout}
{\lstset{commentstyle=,keywordstyle=,stringstyle=}\minipage{\linewidth}}
{\endminipage}
% pdf hyperlinks, table of contents, and document properties
\usepackage[pdftex]{hyperref}
\hypersetup{%
pdftitle={\thetitle},
pdfauthor={\theauthors},
pdfsubject={\theversion},
pdfkeywords={},
bookmarksopen=false,
colorlinks=true,
citecolor=black,
filecolor=black,
linkcolor=black,
urlcolor=blue
}
% inline syntax formatting
\newcommand{\java}[1]{\lstinline{#1}} %\end{
%\newcommand{\java}[1]{\verb"#1"}
%\newcommand{\java}[1]{{\tt #1}}
\begin{document}
\frontmatter
%-half title--------------------------------------------------
%\thispagestyle{empty}
%
%\begin{flushright}
%\vspace*{2.0in}
%
%{\huge Think Java}
%
%\vspace{0.25in}
%{\LARGE How to Think Like a Computer Scientist}
%
%\vfill
%
%\end{flushright}
%--verso------------------------------------------------------
%\cleardoublepage
%\cleardoublepage
%--title page--------------------------------------------------
\pagebreak
\thispagestyle{empty}
\begin{flushright}
\vspace*{2.0in}
{\huge Think Java}
\vspace{0.25in}
{\LARGE How to Think Like a Computer Scientist}
\vspace{1in}
{\Large \theauthors}
\vspace{1in}
{\large \theversion}
\vfill
\end{flushright}
%--copyright--------------------------------------------------
\pagebreak
\thispagestyle{empty}
Copyright \copyright ~2016 Allen Downey and Chris Mayfield.
{\bf NOTE: This version of the book is a work in progress and won't be completed until February 2016.}
\vspace{0.25in}
Permission is granted to copy, distribute, transmit, and adapt this work under the Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License: \url{http://creativecommons.org/licenses/by-nc-sa/3.0/}
The original form of this book is \LaTeX\ source code.
Compiling the \LaTeX\ source 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}.
%-----------------------------------------------------------------
%\input{todo-tex/preface.tex}
% table of contents
\cleardoublepage
\setcounter{tocdepth}{1}
\tableofcontents
\mainmatter
\chapter{The way of the program}
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 simply 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{http://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 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 computer hardware.
\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}
Put simply, {\bf computer science} is the science of algorithms, including their discovery and analysis.
An {\bf algorithm} is a sequence of steps that specify exactly how to solve a problem.
Some algorithms are better than others in terms of low long they take or how much memory they use.
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.
%In the old days, computer scientists had to deal with real bugs flying into their systems.
%You probably won't have that problem, but you will need to think creatively when unexpected errors happen.
%\begin{figure}[!h]
%\begin{center}
%\includegraphics[height=2.2in]{figs/firstbug.jpg}
%\caption{The first computer bug, taped to Grace Hopper's log book in 1947.
%\\ She discovered the moth in an electromagnetic relay of the Mark II.}
%\end{center}
%\end{figure}
% ABD: I don't love this particular piece of mythology, partly because it's not accurate, and partly because stories about the old days bore students.
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{Introduction to Java}
\index{high-level language}
\index{language!high-level}
The programming language you will learn is Java, which is relatively new (Sun released the first version in May 1995).
Java is an example of a {\bf high-level language}.
Other high-level languages you may have heard of include C and C++, JavaScript, Python, Ruby, and Visual Basic.
\index{low-level language}
\index{language!low-level}
There are also {\bf low-level languages}, sometimes referred to as ``machine languages'' or ``assembly languages.''
Loosely speaking, computers can only run programs written in low-level languages.
So programs written in a high-level language have to be translated before they can run.
This translation takes some time, which is a small disadvantage of high-level languages.
But the advantages of high-level languages are enormous.
As a result, low-level languages are only used for programs that need to interact directly with hardware.
\index{portable}
Due to the advantages, almost all programs are written in high-level languages.
First, it is {\em much} easier to program in a high-level language.
Programs take less time to write, are shorter and easier to read, and are more likely to be correct.
Second, high-level languages are {\bf portable}, meaning that 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.
\index{interpreter}
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 1.1 shows the structure of an interpreter.
\begin{figure}[!h]
\begin{center}
\includegraphics{figs/interpreter.pdf}
\caption{How interpreted languages like Python and Ruby are executed.}
\end{center}
\end{figure}
\index{compiler}
\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}
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, like a high-level language.
Thus it is possible to compile a Java program on one machine, transfer the byte code to another machine, and then execute (interpret) the byte code on the other machine.
%This ability is an advantage of Java over some other high-level languages.
\begin{figure}[!h]
\begin{center}
\includegraphics{figs/compiler.pdf}
\caption{The process of editing, compiling, and running a Java program.}
\end{center}
\end{figure}
Although this process may seem complicated, in most program development environments these steps are automated for you.
Usually you will only have to write a program and press a button or type a single command to compile and run it.
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{Formal languages}
\index{natural language}
\index{language!natural}
Learning a programming language is very different from learning a {\bf natural language} such as English, Spanish, or German.
The languages that people speak evolved naturally over time.
They were not designed by people, although we try to impose order on them for practical reasons.
\index{formal language}
\index{language!formal}
In contrast, {\bf formal languages} are designed by people for specific applications.
For example, the notation that mathematicians use is a formal language that is particularly good at denoting relationships among numbers and symbols.
Chemists use a formal language to represent the chemical structure of molecules.
And most importantly:
\index{programming language}
\index{language!programming}
\begin{quote}
{\bf Programming languages are formal languages that have been designed to express computations.}
\end{quote}
\index{syntax}
\index{semantics}
Formal languages have strict rules about both the {\bf syntax} (structure) and the {\bf semantics} (meaning) of statements.
For example, $3 + 3 = 6$ is a syntactically correct mathematical statement, but $3\ + = 3\ \$\ 6$ is not.
$1 + 2 = 4$ uses correct syntax, but is semantically incorrect.
$H_2O$ is a syntactically correct chemical formula, but $_2Zz$ is not.
\subsection{Tokens and grammar}
\index{token}
Syntax rules come in two flavors, pertaining to tokens and grammar.
{\bf Tokens} are the basic elements of the language, like words, numbers, and chemical elements.
One of the problems with $3\ + = 3\ \$\ 6$ is that $\$$ is not a legal token in mathematics.
Similarly, $_2Zz$ is not legal because there is no element with the abbreviation $Zz$.
\index{grammar}
The second type of syntax rule pertains to the {\bf grammar} of the language, or the way tokens can be arranged.
The statement $3\ + = 3$ is structurally illegal, even though $+$ and $=$ are legal tokens, because you can't have one right after the other.
Similarly, in a chemical formula the subscript comes after the element name, not before.
\index{parse}
When you read a sentence in English or a statement in a formal language, you have to figure out its structure.
This process is called {\bf parsing}, and in a natural language you learn to do it unconsciously.
For example, when you hear the statement ``the penny dropped,'' you understand that the penny is the subject and dropped is the predicate.
After you have parsed the statement, you can begin to figure out what it means.
%Assuming that you know what a penny is and what it means to drop, you will understand the general implication of this statement.
\subsection{Reading source code}
Although formal and natural languages have features in common---tokens, grammar, and meaning---there are some differences.
\begin{description}
\term{ambiguity}
Natural languages are full of ambiguity, which people deal with by using contextual clues and other information.
Formal languages are designed to be nearly or completely unambiguous, which means that any statement has exactly one meaning, regardless of context.
\term{redundancy}
In order to make up for ambiguity and reduce misunderstandings, natural languages employ lots of redundancy.
As a result, they are often verbose.
Formal languages are less redundant and more concise.
\term{literalness}
Natural languages are full of idiom and metaphor.
When someone says ``the penny dropped'' there is no penny and nothing dropping.
This idiom means that someone finally realized something after a period of confusion.
In contrast, formal languages mean exactly what they say.
\end{description}
People who grow up speaking a natural language---that is, everyone---often have a hard time adjusting to formal languages.
In some ways, the difference between natural and formal language is like the difference between poetry and prose, but more so.
\begin{description}
\term{poetry}
Words are used for their sounds as well as for their meaning, and the whole poem together creates an effect or emotional response.
Ambiguity is not only common but often deliberate.
\term{prose}
The literal meaning of words is more important, and the structure contributes more meaning.
Prose is more amenable to analysis than poetry but still often ambiguous.
\term{program}
The meaning of a computer program is unambiguous and literal, and can be understood entirely by analysis of the tokens and grammar.
\end{description}
%Here are some suggestions for reading programs (and other formal languages).
Remember that formal languages are much more dense than natural languages, so it takes longer to read them.
The structure is very important, so it is not always a good idea to read from top to bottom, left to right.
Over time you will learn to parse the program in your head, identifying the tokens and interpreting the structure.
Finally, the details matter.
Small errors in spelling and punctuation, which you can get away with in natural languages, can make a big difference in a formal language.
\section{The hello world program}
\label{sec: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:
\begin{code}
public class Hello {
public static void main(String[] args) {
// generate some simple output
System.out.println("Hello, World!");
}
}
\end{code}
Note the output of this program does not include the quote marks:
\begin{stdout}
Hello, World!
\end{stdout}
\index{public}
\index{static}
Unfortunately in Java, even this simple example requires language features that are difficult to explain to beginners.
But it provides a preview of topics that we will see in detail later on.
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.
We will discuss \java{void}, \java{String}, and \java{args} in the next few chapters.
For now, let's focus on the overall structure.
\index{class!definition}
\index{method!definition}
Java programs are made up of {\bf class} and {\bf method} definitions, which generally have the form:
\begin{code}
public class CLASSNAME {
METHOD {
STATEMENTS
}
METHOD {
STATEMENTS
}
}
\end{code}
\index{class!name}
Here \java{CLASSNAME} indicates the name chosen by the programmer.
Java requires the class name to match the source file name.
In the hello world example, the file name must be {\tt Hello.java} because the class name is \java{Hello}.
\index{statement}
\index{main}
Classes define a program's methods, or named sequences of {\bf statements}.
The \java{Hello} class has only one method:
\begin{code}
public static void main(String[] args)
\end{code}
The name and format of \java{main} is special; it marks the place in the class where execution begins.
When the program runs, it starts at the first statement in \java{main} and ends when it finishes the last statement.
\index{braces}
\index{squiggly braces}
Java uses squiggly braces (\{ and \}) to group things together.
In {\tt Hello.java}, the outermost braces (lines 1 and 8) contain the class definition, and the inner braces (lines 3 and 6) contain the definition of \java{main} method.
% ABD: It looks like we don't have line numbers in the listings.
% Is that a problem for the text here?
\index{println}
\index{statement!print}
The main method can have any number of statements, but the \java{Hello} example has only one.
It is a {\bf print statement}, meaning that it displays a message on the screen.
Confusingly, print can mean both ``display something on the screen'' and ``send something to the printer.''
%I won't say much about sending things to the printer;
In this book, we'll do all our printing on the screen.
The print statement ends with a semicolon ({\tt ;}).
\index{comments!inline}
\index{statement!comment}
Line 4 contains a {\bf comment}, or a bit of English text that explains the code that follows.
When the compiler sees {\tt //}, it ignores everything from there until the end of the line.
It is a good idea to write a comment before every major block of code so that other programmers (including your future self) can understand what you meant to do.
\section{Getting started with DrJava}
\index{JDK}
In order to compile Java programs on your own computer, you will need to install the Java Development Kit (JDK).
This free software by Oracle includes tools for developing and debugging Java programs.
All the examples in this book were developed and tested using Java SE Version 7.
Later versions of Java are generally backward compatible, so if you are using a more recent version, the examples in this book should still work.
\begin{figure}[!h]
\begin{center}
\includegraphics[width=\textwidth]{figs/drjava-hello.png}
\caption{Screenshot of DrJava editing the hello world program.}
\end{center}
\end{figure}
\index{DrJava}
We will use DrJava as the primary development environment throughout the book.
A useful feature of DrJava is the Interactions Pane at the bottom of the window.
It provides the ability to try out code quickly, without having to write a class definition and save/compile/run the program.
Refer to the DrJava documentation (\url{http://drjava.org/docs/quickstart/}) for more details.
Step-by-step instructions for installing the JDK and configuring DrJava are available on this book's website: \url{http://thinkjava.org/}
% TODO: when we have the specific URL for the install page, let's put it here.
\subsection{Command-line interface}
\index{command-line}
\index{terminal}
One of the most powerful and useful skills you can learn as a computer scientist is how to use the {\bf command-line}, also called
the {\em terminal}.
The command-line is a direct interface to the operating system.
It allows you to run programs, manage files and directories, and monitor system resources.
Many advanced tools, both for software development and general purpose computing, are available only at the command-line.
There are many good tutorials online for learning the command-line for your operating system; just search the web for ``command line tutorial.''
To get started, you only need to know four commands: how to change the working directory ({\tt cd}), list directory contents ({\tt ls}), compile Java programs ({\tt javac}), and run Java programs ({\tt java}).
% ABD: There's a conflict here between ``Find the details for your system'' and ``Here are the UNIX commands''.
\begin{figure}[!h]
\begin{center}
\includegraphics[width=4.5in]{figs/terminal.png}
\caption{Compiling and running {\tt Hello.java} from the command-line.}
\end{center}
\end{figure}
In this example, the {\tt Hello.java} source file is stored in the {\tt Desktop} directory.
After changing to that location and listing the files, we use the {\tt javac} command to compile {\tt Hello.java}.
Running {\tt ls} again, we see that the compiler generated a new file, {\tt Hello.class}, which contains the byte code.
We run the program using the {\tt java} command, which displays the output on the following line.
Note that the {\tt javac} command requires a {\em file name} (or multiple source files separated by spaces), whereas the {\tt java} command requires a single {\em class name}.
If you use DrJava, it runs these commands for you and displays the output in the Interactions Pane.
Taking time to learn this efficient and elegant way of interacting with your operating system will make you more productive as a computer user.
People who don't use the command-line don't know what they're missing.
% ABD: Maybe add a reference to Neal Stephenson's book?
\section{More printing}
You can put as many statements as you want in \java{main}.
For example, to print more than one line:
\begin{code}
public class Hello {
public static void main(String[] args) {
// generate some simple output
System.out.println("Hello, World!"); // print one line
System.out.println("How are you?"); // print another
}
}
\end{code}
As this program demonstrates, you can put comments at the end of a line as well as on lines all by themselves.
\index{String}
\index{type!String}
Phrases that appear in quotation marks are called {\bf strings}, because they contain a sequence of characters strung together.
Strings can contain any combination of letters, numbers, punctuation marks, symbols, and even non-printable characters like tab and backspace.
\index{newline}
\index{print}
\index{statement!print}
The name \java{println} is short for ``print line.''
It appends a special character, called a {\bf newline}, that advances the cursor to the beginning of the next line.
%The next time \java{println} is invoked, the new text appears on the next line.
To display the output from multiple print statements on one line, use \java{print}:
\begin{code}
public class Goodbye {
public static void main(String[] args) {
System.out.print("Goodbye, ");
System.out.println("cruel world");
}
}
\end{code}
The output appears on a single line as {\tt Goodbye, cruel world}.
Notice that there is a space between the word ``Goodbye'' and the second quotation mark.
This space appears in the output, so it affects the {\em behavior} of the program.
\subsection{Code formatting}
\label{sec:formatting}
Spaces that appear outside of quotation marks generally do not affect the behavior of the program.
For example, we could have written:
\begin{code}
public class Goodbye {
public static void main(String[] args) {
System.out.print("Goodbye, ");
System.out.println("cruel world");
}
}
\end{code}
This program would compile and run just as well as the original.
The newlines at the end of each line do not affect the program's behavior either.
So we could have also written:
\begin{code}
public class Goodbye { public static void main(String[] args) {
System.out.print("Goodbye, "); System.out.println
("cruel world");}}
\end{code}
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.
%Formatting your code well does not take much effort, and it pays huge dividends.
%We will discuss readability and style guidelines in the next chapter.
\subsection{Escape sequences}
It is possible to print multiple lines of output in just one line of code.
You simply have to tell Java where to put the newlines.
\begin{code}
public class Hello {
public static void main(String[] args) {
System.out.print("Hello!\nHow are you doing?\n");
}
}
\end{code}
The output is two lines, each ending with a newline character:
\begin{stdout}
Hello!
How are you doing?
\end{stdout}
\index{escape sequence}
The code \verb"\n" is an example of an {\bf escape sequence}, which is a sequence of characters in a string 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}[!h]
\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}
Another common use of escape sequences is to have quote 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{Working through examples}
\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, but if you put the code in a source file, it will be easier to try out variations.
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?
This kind of experiment helps you remember what you read.
It also helps with debugging, because you get to know 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, ``One of Linus's earlier projects was a program that would switch between printing AAAA and BBBB.
This later evolved to Linux.'' ({\em The Linux Users' Guide})
%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!
%\index{emotional debugging}
%\index{debugging!emotional response}
%There is evidence that people naturally respond to computers as if they were people.
%When they work well, we think of them as teammates, and when they are obstinate or rude, we respond to them the same way we respond to rude, obstinate people.
%(Reeves and Nass, {\it The Media Equation: How People Treat Computers, Television, and New Media Like Real People and Places})
%Preparing for these reactions might help you deal with them.
%One approach is to think of the computer as an employee with certain strengths, like speed and precision, and particular weaknesses, like lack of empathy and inability to grasp the big picture.
%Your job is to be a good manager: find ways to take advantage of the strengths and mitigate the weaknesses.
%And find ways to use your emotions to engage with the problem, without letting your reactions interfere with your ability to work effectively.
%Learning to debug can be frustrating, but it is a valuable skill that is useful for many activities beyond programming.
%At the end of each chapter there is a debugging section, like this one, with my thoughts about debugging.
%I hope they help!
\section{Vocabulary}
\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 specify 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 any of the three kinds of 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{natural language}
Any of the languages people speak that have evolved naturally.
\term{formal language}
A language people have designed for specific purposes, like representing mathematical ideas or computer programs.
\term{programming language}
A formal language that has been designed to express computations.
\term{syntax}
The structure of a program.
\term{semantics}
The meaning of a program.
\term{token}
A basic element of a program, such as a word, space, symbol, or number.
\term{grammar}
A set of rules that determines whether a statement is legal.
\term{parse}
To examine a program and analyze the syntactic structure.
\term{statement}
A part of a program that specifies a computation.
\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{print statement}
A statement that causes output to be displayed on the screen.
\term{comment}
A part of a program that contains information about the program but has no effect when the program runs.
\term{command-line}
A means of interacting with the computer by issuing commands in the form of successive lines of text.
\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.
\end{description}
\section{Exercises}
\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.
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!
\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 What is an executable?
\end{enumerate}