Table Of ContentTexts in Computer Science
Quentin Charatan
Aaron Kans
Java in Two
Semesters
Featuring JavaFX
Fourth Edition
Texts in Computer Science
Series editors
David Gries, Department of Computer Science, Cornell University, Ithaca, NY,
USA
Orit Hazzan, Faculty of Education in Science and Technology, Technion—Israel
Institute of Technology, Haifa, Israel
More information about this series at http://www.springer.com/series/3191
Quentin Charatan (cid:129) Aaron Kans
Java in Two Semesters
Featuring JavaFX
Fourth Edition
123
QuentinCharatan Aaron Kans
University of EastLondon University of EastLondon
London,UK London,UK
ISSN 1868-0941 ISSN 1868-095X (electronic)
Textsin Computer Science
ISBN978-3-319-99419-2 ISBN978-3-319-99420-8 (eBook)
https://doi.org/10.1007/978-3-319-99420-8
LibraryofCongressControlNumber:2018961214
1stedition:©TheMcGraw-HillCompanies2002
2ndedition:©McGraw-HillEducation(UK)Limited2006
3rdedition:©McGraw-HillEducation(UK)Limited2009
4thedition:©SpringerNatureSwitzerlandAG2019
Thisworkissubjecttocopyright.AllrightsarereservedbythePublisher,whetherthewholeorpart
of the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations,
recitation, broadcasting, reproduction on microfilms or in any other physical way, and transmission
orinformationstorageandretrieval,electronicadaptation,computersoftware,orbysimilarordissimilar
methodologynowknownorhereafterdeveloped.
The use of general descriptive names, registered names, trademarks, service marks, etc. in this
publicationdoesnotimply,evenintheabsenceofaspecificstatement,thatsuchnamesareexemptfrom
therelevantprotectivelawsandregulationsandthereforefreeforgeneraluse.
The publisher, the authors and the editors are safe to assume that the advice and information in this
book are believed to be true and accurate at the date of publication. Neither the publisher nor the
authorsortheeditorsgiveawarranty,expressorimplied,withrespecttothematerialcontainedhereinor
for any errors or omissions that may have been made. The publisher remains neutral with regard to
jurisdictionalclaimsinpublishedmapsandinstitutionalaffiliations.
ThisSpringerimprintispublishedbytheregisteredcompanySpringerNatureSwitzerlandAG
Theregisteredcompanyaddressis:Gewerbestrasse11,6330Cham,Switzerland
To Alexi
Quentin Charatan
To Wendy
Aaron Kans
Preface
Accompanying Web site: https://www.springer.com/book/9783319994192.
Aswithpreviouseditions,thisbookisdesignedforuniversitystudentstakinga
firstmoduleinsoftwaredevelopmentorprogramming,followedbyasecond,more
advanced module. This book uses Java as the vehicle for the teaching of pro-
gramming concepts—design concepts are explained using the UML notation. The
topicistaughtfromfirstprinciplesandassumesnopriorknowledgeofthesubject.
Thisbookisorganizedsoastosupporttwotwelve-week,one-semestermodules,
whichmighttypicallycompriseatwo-hourlecture,aone-hourseminar,andaone-
ortwo-hourlaboratorysession. Theoutcomesatthestart ofeachchapterhighlight
itskeylearning objectives,theself-test questions attheendofeachchapterensure
thatthelearningobjectives forthatchapterhavebeenmet,whiletheprogramming
exercises that follow allow these learning objectives to be applied to complete
programs.Inadditiontotheseexercisesandquestions,acasestudyisdevelopedin
eachsemestertoillustratetheuseofthetechniquescoveredinthetexttodevelopa
non-trivial application. Lecturers who teach on modules that run for fewer than
twelve weeks in a semester could treat these case studies as a self-directed student
learning experience, rather than as taught topics.
Theapproachtakeninthisbookisidealforallstudentsincludingthoseentering
university with little or no background in the subject matter, perhaps coming from
pre-degree courses in other disciplines, or perhaps returning to study after long
periodsawayfromformaleducation.Itistheauthors’experiencethatsuchstudents
have enormous difficulties in grasping the fundamental programming concepts the
first time round and therefore require a simpler and gentler introduction to the
subject that is presented in most standard texts.
This book takes an integrated approach to software development by covering
suchtopicsasbasicdesignprinciplesandstandards,testingmethodologies,andthe
user interface, as well as looking at detailed implementation topics.
Inthefirstsemester,considerabletimeisspentconcentratingonthefundamental
programming concepts such as declarations of variables and basic control struc-
tures, methods and arrays, prior to introducing students to classes and objects,
inheritance, graphics, and event-driven programming.
Thesecondsemestercoversmoreadvancedtopicssuchasinterfaces,exceptions,
collection classes from the Java collections framework, advanced graphics,
vii
viii Preface
file-handlingtechniques,packages,theimplementationofmulti-threadedprograms,
socket programming, and processing collections using streams.
Thefourtheditionachievesthreemaingoals.Firstly,itincorporatesallthevery
useful feedback on the third edition that we have received from students and
lecturers since its publication. Secondly, it includes many new questions and pro-
gramming exercises at the end of the chapters. Finally, it includes new material to
bring it completely up to date with the current developments in the field—in par-
ticular a number of key developments that were introduced in Java 8 which,
accordingtoOracleTM,is“themostsignificantre-engineeringofthelanguagesince
its launch.”
One key feature of this new edition is that all graphical user interface devel-
opmentsarebased onJavaFX,ratherthan theSwingTechnologyused inprevious
editions. JavaFX allows for the creation of sophisticated modern graphical inter-
facesthatcanrunonavarietyofdevicesandisnowOracle’spreferredtechnology
for building such interfaces, having decided that Swing will no longer be devel-
oped. JavaFX therefore plays a very significant role throughout the new text, and
three new chapters are devoted to it.
OtherkeydevelopmentsarisingfromJava8thathavebeenincorporatedintothe
new text include lambda expressions, which allow us to simplify development
considerably by passing functions as arguments to methods, and the new Stream
API,atechnologythatallowsustoprocesscollectionsinaveryconcise,declarative
style of programming.
In addition to the above key changes, we also introduce techniques to improve
the robustness of code—in particular the Optional class for dealing with empty
values and the try-with-resources construct to ensure resources such as files are
safely closed before exiting methods.
As well as adding these new features, some existing chapters have undergone
significant enhancements. The Java Collections Framework chapter, for example,
has been expanded to include a comprehensive section on the sort methods
availableinvariousclassesandinterfacesinJava.Thecoverageofgenericshasalso
been considerably expanded and the packages chapter now introduces the Hiber-
nate ORM technology for accessing remote databases.
The accompanying Web site (see URL above) contains all the codes from the
™
textbookandaguideonhowtoinstallandusetheNetBeans JavaIDE,aswellas
a collection of other useful resources.
We would like to thank our publisher, Springer, for the encouragement and
guidance that we have received throughout the production of this book. Addi-
tionally,wewouldespeciallyliketothankthecomputingstudentsoftheUniversity
ofEastLondonfortheirthoughtfulcommentsandfeedback andStevenMartinfor
hishelpandadvice.Forsupportandinspiration,special thanksaredueonceagain
to our families and friends.
London, UK Quentin Charatan
Aaron Kans
Contents
Part I Semester One
1 The First Step. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2 Software. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.3 Compiling Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.4 Programming in Java. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.5 Integrated Development Environments (IDEs). . . . . . . . . . . . . 6
1.6 Java Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.7 Your First Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.7.1 Analysis of the “Hello World” Program. . . . . . . . . . 11
1.7.2 Adding Comments to a Program . . . . . . . . . . . . . . . 13
1.8 Output in Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
1.9 Self-test Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
1.10 Programming Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
2 Building Blocks. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
2.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
2.2 Simple Data Types in Java . . . . . . . . . . . . . . . . . . . . . . . . . . 19
2.3 Declaring Variables in Java . . . . . . . . . . . . . . . . . . . . . . . . . . 21
2.4 Assignments in Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
2.5 Creating Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
2.6 Arithmetic Operators. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
2.7 Expressions in Java. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
2.8 More About Output. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
2.9 Input in Java: The Scanner Class. . . . . . . . . . . . . . . . . . . . . . 31
2.10 Program Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
2.11 Self-test Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
2.12 Programming Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
3 Selection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
3.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
3.2 Making Choices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
ix
x Contents
3.3 The ‘if’ Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
3.3.1 Comparison Operators. . . . . . . . . . . . . . . . . . . . . . . 46
3.3.2 Multiple Instructions Within an ‘if’ Statement . . . . . 47
3.4 The ‘if…else’ Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
3.5 Logical Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
3.6 Nested ‘if…else’ Statements . . . . . . . . . . . . . . . . . . . . . . . . . 53
3.7 The ‘switch’ Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
3.7.1 Grouping Case Statements. . . . . . . . . . . . . . . . . . . . 56
3.7.2 Removing Break Statements . . . . . . . . . . . . . . . . . . 57
3.8 Self-test Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
3.9 Programming Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
4 Iteration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
4.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
4.2 The ‘for’ Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
4.2.1 Varying the Loop Counter. . . . . . . . . . . . . . . . . . . . 70
4.2.2 The Body of the Loop . . . . . . . . . . . . . . . . . . . . . . 72
4.2.3 Revisiting the Loop Counter . . . . . . . . . . . . . . . . . . 76
4.3 The ‘while’ Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
4.4 The ‘do…while’ Loop. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
4.5 Picking the Right Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
4.6 The ‘break’ Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
4.7 The ‘continue’ Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
4.8 Self-test Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
4.9 Programming Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
5 Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
5.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
5.2 Declaring and Defining Methods . . . . . . . . . . . . . . . . . . . . . . 96
5.3 Calling a Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
5.4 Method Input and Output . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
5.5 More Examples of Methods. . . . . . . . . . . . . . . . . . . . . . . . . . 103
5.6 Variable Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
5.7 Method Overloading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
5.8 Using Methods in Menu-Driven Programs . . . . . . . . . . . . . . . 112
5.9 Self-test Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
5.10 Programming Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
6 Arrays. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
6.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
6.2 Creating an Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
6.3 Accessing Array Elements. . . . . . . . . . . . . . . . . . . . . . . . . . . 124
6.4 Passing Arrays as Parameters. . . . . . . . . . . . . . . . . . . . . . . . . 129
6.5 Varargs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
Description:This easy-to-follow textbook teaches Java programming from first principles, as well as covering design and testing methodologies. The text is divided into two parts. Each part supports a one-semester module, the first part addressing fundamental programming concepts, and the second part building on