INTRODUCTION TO JAVA ® PROGRAMMING COMPREHENSIVE VERSION Tenth Edition Y Daniel Liang Armstrong Atlantic State University Boston Columbus Indianapolis New York San Francisco Upper Saddle River Amsterdam Cape Town Dubai London Madrid Milan Munich Paris Montreal Toronto Delhi Mexico City Sao Paulo Sydney Hong Kong Seoul Singapore Taipei Tokyo To Samantha, Michael, and Michelle Editorial Director, ECS: Marcia Horton Executive Editor: Tracy Johnson (Dunkelberger) Editorial Assistant: Jenah Blitz-Stoehr Director of Marketing: Christy Lesko Marketing Manager: Yez Alayan Marketing Assistant: Jon Bryant Director of Program Management: Erin Gregg Program Management-Team Lead: Scott Disanno Program Manager: Carole Snyder Project Management-Team Lead: Laura Burgess Project Manager: Robert Engelhardt Procurement Specialist: Linda Sager Cover Designer: Marta Samsel Permissions Supervisor: Michael Joyce Permissions Administrator: Jenell Forschler Director, Image Asset Services: Annie Atherton Manager, Visual Research: Karen Sanatar Image Permission Coordinator: Cover Art: © Blend Images—PBNJ Productions/Getty Images Media Project Manager: Renata Butera Full-Service Project Management: Haseen Khan, Laserwords Pvt Ltd Credits and acknowledgments borrowed from other sources and reproduced, with permission, in this textbook appear on the appropriate page within text Microsoft® and Windows® are registered trademarks of the Microsoft Corporation in the U.S.A and other countries Screen shots and icons reprinted with permission from the Microsoft Corporation This book is not sponsored or endorsed by or affiliated with the Microsoft Corporation Copyright © 2015, 2013, 2011 Pearson Education, Inc., publishing as Prentice Hall, Lake Street, Upper Saddle River, New Jersey, 07458 All rights reserved Printed in the United States of America This publication is protected by Copyright, and permission should be obtained from the publisher prior to any prohibited reproduction, storage in a retrieval system, or transmission in any form or by any means, electronic, mechanical, photocopying, recording, or likewise To obtain permission(s) to use material from this work, please submit a written request to Pearson Education, Inc., Permissions Department, One Lake Street, Upper Saddle River, New Jersey 07458, or you may fax your request to 201-236-3290 Many of the designations by manufacturers and sellers to distinguish their products are claimed as trademarks Where those designations appear in this book, and the publisher was aware of a trademark claim, the designations have been printed in initial caps or all caps Library of Congress Cataloging-in-Publication Data available upon request 10 ISBN 10: 0-13-376131-2 ISBN 13: 978-0-13-376131-3 PREFACE Dear Reader, Many of you have provided feedback on earlier editions of this book, and your comments and suggestions have greatly improved the book This edition has been substantially enhanced in presentation, organization, examples, exercises, and supplements The new edition: ■ Replaces Swing with JavaFX JavaFX is a new framework for developing Java GUI programs JavaFX greatly simplifies GUI programming and is easier to learn than Swing ■ Introduces exception handling, abstract classes, and interfaces before GUI programming to enable the GUI chapters to be skipped completely if the instructor chooses not to cover GUI ■ Covers introductions to objects and strings earlier in Chapter to enable students to use objects and strings to develop interesting programs early ■ Includes many new interesting examples and exercises to stimulate student interests More than 100 additional programming exercises are provided to instructors only on the Companion Website Please visit www.pearsonhighered.com/liang for a complete list of new features as well as correlations to the previous edition The book is fundamentals first by introducing basic programming concepts and techniques before designing custom classes The fundamental concepts and techniques of selection statements, loops, methods, and arrays are the foundation for programming Building this strong foundation prepares students to learn object-oriented programming and advanced Java programming This book teaches programming in a problem-driven way that focuses on problem solving rather than syntax We make introductory programming interesting by using thoughtprovoking problems in a broad context The central thread of early chapters is on problem solving Appropriate syntax and library are introduced to enable readers to write programs for solving the problems To support the teaching of programming in a problem-driven way, the book provides a wide variety of problems at various levels of difficulty to motivate students To appeal to students in all majors, the problems cover many application areas, including math, science, business, financial, gaming, animation, and multimedia The book seamlessly integrates programming, data structures, and algorithms into one text It employs a practical approach to teach data structures We first introduce how to use various data structures to develop efficient algorithms, and then show how to implement these data structures Through implementation, students gain a deep understanding on the efficiency of data structures and on how and when to use certain data structures Finally we design and implement custom data structures for trees and graphs The book is widely used in the introductory programming, data structures, and algorithms courses in the universities around the world This comprehensive version covers fundamentals of programming, object-oriented programming, GUI programming, data structures, algorithms, concurrency, networking, database, and Web programming It is designed to prepare students to become proficient Java programmers A brief version (Introduction to Java Programming, Brief Version, Tenth Edition) is available for a first course on programming, commonly known as CS1 The brief version contains the first 18 chapters of the comprehensive version The first 13 chapters are appropriate for preparing the AP Computer Science exam The best way to teach programming is by example, and the only way to learn programming is by doing Basic concepts are explained by example and a large number of exercises what is new? fundamentals-first problem-driven data structures comprehensive version brief version AP Computer Science examples and exercises iii iv Preface with various levels of difficulty are provided for students to practice For our programming courses, we assign programming exercises after each lecture Our goal is to produce a text that teaches problem solving and programming in a broad context using a wide variety of interesting examples If you have any comments on and suggestions for improving the book, please email me Sincerely, Y Daniel Liang y.daniel.liang@gmail.com www.cs.armstrong.edu/liang www.pearsonhighered.com/liang ACM/IEEE Curricular 2013 and ABET Course Assessment The new ACM/IEEE Computer Science Curricular 2013 defines the Body of Knowledge organized into 18 Knowledge Areas To help instructors design the courses based on this book, we provide sample syllabi to identify the Knowledge Areas and Knowledge Units The sample syllabi are for a three semester course sequence and serve as an example for institutional customization The sample syllabi are available to instructors at www.pearsonhighered.com/liang Many of our users are from the ABET-accredited programs A key component of the ABET accreditation is to identify the weakness through continuous course assessment against the course outcomes We provide sample course outcomes for the courses and sample exams for measuring course outcomes on the instructor Website accessible from www.pearsonhighered.com/liang What’s New in This Edition? This edition is completely revised in every detail to enhance clarity, presentation, content, examples, and exercises The major improvements are as follows: ■ Updated to Java ■ Since Swing is replaced by JavaFX, all GUI examples and exercises are revised using JavaFX ■ Lambda expressions are used to simplify coding in JavaFX and threads ■ More than 100 additional programming exercises with solutions are provided to the instructor on the Companion Website These exercises are not printed in the text ■ Math methods are introduced earlier in Chapter to enable students to write code using math functions ■ Strings are introduced earlier in Chapter to enable students to use objects and strings to develop interesting programs early ■ The GUI chapters are moved to after abstract classes and interfaces so that these chapters can be easily skipped if the instructor chooses not to cover GUI ■ Chapters 4, 14, 15, and 16 are brand new chapters ■ Chapters 28 and 29 have been substantially revised with simpler implementations for minimum spanning trees and shortest paths Preface v Pedagogical Features The book uses the following elements to help students get the most from the material: ■ The Objectives at the beginning of each chapter list what students should learn from the chapter This will help them determine whether they have met the objectives after completing the chapter ■ The Introduction opens the discussion with representative problems to give the reader an overview of what to expect from the chapter ■ Key Points highlight the important concepts covered in each section ■ Check Points provide review questions to help students track their progress as they read through the chapter and evaluate their learning ■ Problems and Case Studies, carefully chosen and presented in an easy-to-follow style, teach problem solving and programming concepts The book uses many small, simple, and stimulating examples to demonstrate important ideas ■ The Chapter Summary reviews the important subjects that students should understand and remember It helps them reinforce the key concepts they have learned in the chapter ■ Quizzes are accessible online, grouped by sections, for students to self-test on programming concepts and techniques ■ Programming Exercises are grouped by sections to provide students with opportunities to apply the new skills they have learned on their own The level of difficulty is rated as easy (no asterisk), moderate (*), hard (**), or challenging (***) The trick of learning programming is practice, practice, and practice To that end, the book provides a great many exercises Additionally, more than 100 programming exercises with solutions are provided to the instructors on the Companion Website These exercises are not printed in the text ■ Notes, Tips, Cautions, and Design Guides are inserted throughout the text to offer valuable advice and insight on important aspects of program development Note Provides additional information on the subject and reinforces important concepts Tip Teaches good programming style and practice Caution Helps students steer away from the pitfalls of programming errors Design Guide Provides guidelines for designing programs Flexible Chapter Orderings The book is designed to provide flexible chapter orderings to enable GUI, exception handling, recursion, generics, and the Java Collections Framework to be covered earlier or later The diagram on the next page shows the chapter dependencies vi Preface Part I: Fundamentals of Programming Chapter Introduction to Computers, Programs, and Java Chapter Elementary Programming Chapter Selections Part II: Object-Oriented Programming Part IV: Data Structures and Algorithms Part III: GUI Programming Chapter Objects and Classes Chapter 14 JavaFX Basics Ch Chapter 18 Recursion Chapter 10 Thinking in Objects Chapter 15 Event-Driven Programming and Animations Ch 13 Chapter 19 Generics Chapter 11 Inheritance and Polymorphism Chapter 12 Exception Handling and Text I/O Chapter Mathematical Functions, Characters, and Strings Chapter 13 Abstract Classes and Interfaces Chapter Loops Chapter 17 Binary I/O Chapter 16 JavaFX Controls and Multimedia Ch 16 Chapter 30 Multithreading and Parallel Programming Chapter 31 Networking Chapter 20 Lists, Stacks, Queues, and Priority Queues Chapter 32 Java Database Programming Chapter 21 Sets and Maps Chapter 33 JavaServer Faces Chapter 34 Advanced GUI Programming Chapter 22 Developping Efficient Algorithms Chapter 35 Advanced Database Programming Chapter 23 Sorting Chapter Methods Chapter 24 Implementing Lists, Stacks, Queues, and Priority Queues Chapter Single-Dimensional Arrays Chapter 25 Binary Search Trees Chapter Multidimensional Arrays Part V: Advanced Java Programming Chapter 36 Internationalization Chapter 37 Servlets Note: Chapters 1–18 are in the brief version of this book Chapter 26 AVL Trees Note: Chapters 1–33 are in the comprehensive version Chapter 27 Hashing Note: Chapters 34–42 are bonus chapters available from the Companion Website Chapter 28 Graphs and Applications Chapter 38 JavaServer Pages Chapter 39 Web Services Chapter 29 Weighted Graphs and Applications Chapter 40 2-4 Trees and BTrees Chapter 41 Red-Black Trees Ch Chapter 42 Testing Using JUnit Preface vii Organization of the Book The chapters can be grouped into five parts that, taken together, form a comprehensive introduction to Java programming, data structures and algorithms, and database and Web programming Because knowledge is cumulative, the early chapters provide the conceptual basis for understanding programming and guide students through simple examples and exercises; subsequent chapters progressively present Java programming in detail, culminating with the development of comprehensive Java applications The appendixes contain a mixed bag of topics, including an introduction to number systems, bitwise operations, regular expressions, and enumerated types Part I: Fundamentals of Programming (Chapters 1–8) The first part of the book is a stepping stone, preparing you to embark on the journey of learning Java You will begin to learn about Java (Chapter 1) and fundamental programming techniques with primitive data types, variables, constants, assignments, expressions, and operators (Chapter 2), selection statements (Chapter 3), mathematical functions, characters, and strings (Chapter 4), loops (Chapter 5), methods (Chapter 6), and arrays (Chapters 7–8) After Chapter 7, you can jump to Chapter 18 to learn how to write recursive methods for solving inherently recursive problems Part II: Object-Oriented Programming (Chapters 9–13, and 17) This part introduces object-oriented programming Java is an object-oriented programming language that uses abstraction, encapsulation, inheritance, and polymorphism to provide great flexibility, modularity, and reusability in developing software You will learn programming with objects and classes (Chapters 9–10), class inheritance (Chapter 11), polymorphism (Chapter 11), exception handling (Chapter 12), abstract classes (Chapter 13), and interfaces (Chapter 13) Text I/O is introduced in Chapter 12 and binary I/O is discussed in Chapter 17 Part III: GUI Programming (Chapters 14–16 and Bonus Chapter 34) JavaFX is a new framework for developing Java GUI programs It is not only useful for developing GUI programs, but also an excellent pedagogical tool for learning object-oriented programming This part introduces Java GUI programming using JavaFX in Chapters 14–16 Major topics include GUI basics (Chapter 14), container panes (Chapter 14), drawing shapes (Chapter 14), event-driven programming (Chapter 15), animations (Chapter 15), and GUI controls (Chapter 16), and playing audio and video (Chapter 16) You will learn the architecture of JavaFX GUI programming and use the controls, shapes, panes, image, and video to develop useful applications Chapter 34 covers advanced features in JavaFX Part IV: Data Structures and Algorithms (Chapters 18–29 and Bonus Chapters 40–41) This part covers the main subjects in a typical data structures and algorithms course Chapter 18 introduces recursion to write methods for solving inherently recursive problems Chapter 19 presents how generics can improve software reliability Chapters 20 and 21 introduce the Java Collection Framework, which defines a set of useful API for data structures Chapter 22 discusses measuring algorithm efficiency in order to choose an appropriate algorithm for applications Chapter 23 describes classic sorting algorithms You will learn how to implement several classic data structures lists, queues, and priority queues in Chapter 24 Chapters 25 and 26 introduce binary search trees and AVL trees Chapter 27 presents hashing and implementing maps and sets using hashing Chapters 28 and 29 introduce graph applications The 2-4 trees, B-trees, and red-black trees are covered in Bonus Chapters 40–41 Part V: Advanced Java Programming (Chapters 30–33 and Bonus Chapters 35–39, 42) This part of the book is devoted to advanced Java programming Chapter 30 treats the use of multithreading to make programs more responsive and interactive and introduces parallel programming Chapter 31 discusses how to write programs that talk with each other from different hosts over the Internet Chapter 32 introduces the use of Java to develop database viii Preface projects Chapter 33 introduces modern Web application development using JavaServer Faces Chapter 35 delves into advanced Java database programming Chapter 36 covers the use of internationalization support to develop projects for international audiences Chapters 37 and 38 introduce how to use Java servlets and JavaServer Pages to generate dynamic content from Web servers Chapter 39 discusses Web services Chapter 42 introduces testing Java programs using JUnit Appendixes This part of the book covers a mixed bag of topics Appendix A lists Java keywords Appendix B gives tables of ASCII characters and their associated codes in decimal and in hex Appendix C shows the operator precedence Appendix D summarizes Java modifiers and their usage Appendix E discusses special floating-point values Appendix F introduces number systems and conversions among binary, decimal, and hex numbers Finally, Appendix G introduces bitwise operations Appendix H introduces regular expressions Appendix I covers enumerated types Java Development Tools IDE tutorials You can use a text editor, such as the Windows Notepad or WordPad, to create Java programs and to compile and run the programs from the command window You can also use a Java development tool, such as NetBeans or Eclipse These tools support an integrated development environment (IDE) for developing Java programs quickly Editing, compiling, building, executing, and debugging programs are integrated in one graphical user interface Using these tools effectively can greatly increase your programming productivity NetBeans and Eclipse are easy to use if you follow the tutorials Tutorials on NetBeans and Eclipse can be found under Tutorials on the Student Companion Website at www.pearsonhighered.com/liang Student Resource Website The Student Resource Website www.pearsonhighered.com/liang provides access to some of the following resources Other resources are available using the student access code printed on the inside front cover of this book (For students with a used copy of this book, you can purchase access to the premium student resources through www.pearsonhighered.com/liang.) ■ Answers to review questions ■ Solutions to even-numbered programming exercises ■ Source code for the examples in the book ■ Interactive quiz (organized by sections for each chapter) ■ Supplements ■ Debugging tips ■ Algorithm animations ■ Errata Instructor Resource Website The Instructor Resource Website, accessible from www.pearsonhighered.com/liang, provides access to the following resources: ■ Microsoft PowerPoint slides with interactive buttons to view full-color, syntax-highlighted source code and to run programs without leaving the slides ■ Solutions to all programming exercises Students will have access to the solutions of evennumbered programming exercises Preface ix ■ More than 100 additional programming exercises organized by chapters These exercises are available only to the instructors Solutions to these exercises are provided ■ Web-based quiz generator (Instructors can choose chapters to generate quizzes from a large database of more than two thousand questions.) ■ Sample exams Most exams have four parts: ■ Multiple-choice questions or short-answer questions ■ Correct programming errors ■ Trace programs ■ Write programs ■ ACM/IEEE Curricula 2013 The new ACM/IEEE Computer Science Curricula 2013 defines the Body of Knowledge organized into 18 Knowledge Areas To help instructors design the courses based on this book, we provide sample syllabi to identify the Knowledge Areas and Knowledge Units The sample syllabi are for a three semester course sequence and serve as an example for institutional customization Instructors can access the syllabi at www.pearsonhighered.com/liang ■ Sample exams with ABET course assessment ■ Projects In general, each project gives a description and asks students to analyze, design, and implement the project Some readers have requested the materials from the Instructor Resource Website Please understand that these are for instructors only Such requests will not be answered Online Practice and Assessment with MyProgrammingLab MyProgrammingLab helps students fully grasp the logic, semantics, and syntax of programming Through practice exercises and immediate, personalized feedback, MyProgrammingLab improves the programming competence of beginning students who often struggle with the basic concepts and paradigms of popular high-level programming languages A self-study and homework tool, a MyProgrammingLab course consists of hundreds of small practice problems organized around the structure of this textbook For students, the system automatically detects errors in the logic and syntax of their code submissions and offers targeted hints that enable students to figure out what went wrong—and why For instructors, a comprehensive gradebook tracks correct and incorrect answers and stores the code inputted by students for review MyProgrammingLab is offered to users of this book in partnership with Turing’s Craft, the makers of the CodeLab interactive programming exercise system For a full demonstration, to see feedback from instructors and students, or to get started using MyProgrammingLab in your course, visit www.myprogramminglab.com VideoNotes We are excited about the new VideoNotes feature that is found in this new edition These videos provide additional help by presenting examples of key topics and showing how to solve problems completely, from design through coding VideoNotes are available from www.pearsonhighered.com/liang VideoNote 1308 Index Maps (continued) singleton and unmodifiable, 816–817 summary, 817–818 synchronized collections for, 1127–1128 TestMap.java example, 813–814 tree maps see TreeMap class Maps, implementing with hashing MyHashMap.java example, 997–1002 MyMap.java example, 996–997 overview of, 995–996 TestMyHashMap.java, 1002–1003 Marker interfaces, 513 Match braces, in Welcome.java, 13 matches method, strings, 342 Math class BigInteger and BigDecimal classes, 384–385 complex numbers, 531–532 exponent methods, 121 invoking object methods, 331 methods generally, 120 pow(a, b) method, 48 random method, 87–88, 98–99, 122 rounding methods, 121–122 service methods, 122 trigonometric methods, 120–121 Matrices adjacency matrices for representing edges, 1021–1022 case study: designing class for matrix using generic types, 752–753 GenericMatrix.java example, 753–755 IntegerMatrix.java example, 755 RationalMatrix.java example, 755–756 TestIntegerMatrix.java example, 756 TestRationalMatrix.java example, 756–757 two-dimensional arrays for storing, 288–289 max method defining and invoking, 206–208 finding maximum element in lists, 776 finding maximum number in lists, 1132–1133 GeometricObjectComparator.java example, 773 MaxUsingGenericType.java example, 746–747 overloading, 220 overview of, 122 ParallelMax.java, 1132–1133 maxRow variable, for finding largest sum, 292 Mbps (million bits per second), MBs (megabytes), of storage, Media, 662–665 MediaPlayer, 662–665 MediaView, 662–665 Megabytes (MBs), of storage, Megahertz (MHz), clock speed, Memory, computers, 3–4 Merge sorts CreateFile.java example of external sort, 884 heap sort compared with, 880 merge sort algorithms, 867 MergeSort.java example, 867–869 overview of, 866 ParallelMergeSort.java, 1130–1132 quick sorts compared with, 874 recurrence relations and, 829 time complexity of, 870 mergeSort method, 868–869 Mersenne prime, 240 MessagePanel class DisplayClock.java, 573–574 ClockPane.java, 574–576 Metadata retrieval, from databases database metadata, 1202–1203 obtaining tables, 1204 overview of, 1202 result set metadata, 1204–1205 Meters, converting to/from feet, 236 Method header, 205 Method modifiers, 205, 1270–1271 Method signature, 205 Methods abstraction and, 225–226 accessing object methods, 330–331 calling, 206–208 case study: converting decimals to hexadecimals, 182–183 case study: generating random numbers, 223–225 case study: generic method for sorting array, 744–745 class, 337–338 Collection interface, 764 commenting, 18 Comparator interface, 772 defining, 204–206 deprecated methods of Thread class, 1103 generic, 742–744 identifiers, 39–40 implementation details, 229–232 invoking, 206–208, 331, 743 key terms, 232 modularizing code, 215–217 naming conventions, 44 object actions defined by, 322–323 overloading, 219–222 overriding, 970 overview of, 203–204 passing arrays to, 257–260 passing objects to, 347–351 passing parameters by values, 212–215 passing to two-dimensional arrays, 293–294 quiz and exercises, 234–244 recursive methods, 706 returning arrays from, 260–261 rounding, 121 static see Static methods stepwise refinement, 225–226, 232 summary, 233 synchronization wrapper methods, 1127 thread coordination, 1118–1119 top-down and/or bottom-up implementation, 227–229 top-down design, 226–227 tracing or stepping over as debugging technique, 106 trigonometric, 120–121 variable scope and, 222–223 void method example, 209–211 MHz (Megahertz), clock speed, Microsoft Access see Access Microsoft Windows, Million bits per second (Mbps), method finding minimum element in lists, 776 Math class, 122 Index 1309 Minimum spanning trees (MSTs) MST algorithm, 1075–1076 overview of, 1072 Prim’s minimum spanning tree algorithm, 1073–1075 TestMinimumSpanningTree.java, 1076–1078 weighted graphs and, 1062 WeightedGraph class, 1067–1069 Mnemonics, in assembly language, Modeling, graphs and, 1024–1028 Model-View-Controller (MVC) architecture, 1217 Modems (modulator/demodulator), Modifier keys, on keyboards, Modifiers list of, 1270–1271 method modifier, 205 Modularizing code GreatestCommonDivisorMethod.java, 215–216 overview of, 215 PrimeNumberMethod.java, 216–217 Monitors (displays), Monitors/monitoring, threads and, 1118 Motherboard, Mouse, as I/O device, MouseEvents ControlCircleWithMouseAndKey.java, 605–606 event-driven programming, 602–603 MouseEvent, 602–603 MST algorithm, 1075–1076 MST class, 1075–1076 MSTs see Minimum spanning trees (MSTs) Multi-dimensional arrays see Arrays, multi-dimensional Multimedia see JavaFX UI controls Multiple choice test, 294–296 Multiplication (*=) assignment operator, 54 Multiplication operator (*), 15, 46, 50 Multiplication table, 176 Multiplicities, in object composition, 373 Multiprocessing, 10 Multiprogramming, 10 Multithreading, 10 blocking queues, 1122–1124 case study: clock with audio, 1139–1142 case study: flashing text, 1105–1106 case study: producer/consumer, 1119–1122 cooperation among threads, 114–1119 creating tasks and threads, 1098–1099 deadlocks and, 1126 key terms, 1133 MultiThreadServer.java, 1149–1151 overview of, 1097–1098 quiz and exercises, 1134–1138 semaphores, 1124–1126 servers serving multiple clients, 1149 summary, 1133–1134 synchronization using locks, 1112–1114 synchronized collections, 1127–1128 synchronized keyword, 1111 synchronizing statements, 1111–1112 TaskThreadDemo.java, 1100–1101 Thread class, 1102–1104 thread concepts, 1198 thread pools, 1106–1108 thread states, 1126–1127 thread synchronization, 1108–1111 Multi-way if-else statements in computing taxes, 90–93 overview of, 81–83 Mutator methods see Setter (mutator) methods MySQL creating databases, 1180–1181 creating tables, 1181–1182 creating user account in, 1179–1180 JDBC drivers for accessing Oracle databases, 1189–1192 stopping/starting, 1180 tutorials on, 1178 N Named constants see Constants Naming conventions class design guidelines, 526 interfaces, 518 programming and, 44 SQL tables, 1181 wrapper classes, 380 Naming rules, identifiers, 39–40 NavigableMap interface, 813 N-by-n matrix, 238 Negative angles, drawing arcs, 569 Neighbors depth-first searches (DFS), 1038 vertices, 1018, 1022–1023 Nested classes see Inner (nested) classes Nested if statements in computing body mass index, 89–90 in computing taxes, 90–93 overview of, 81 Nested loops, 176–177, 291, 824–825 NetBeans built in debugging, 106 for creating/editing Java source code, 15 for developing JSF applications, 1214 Network interface cards (NICs), Networking case study: distributed tic-tac-toe games, 1156–1157 client sockets, 1141–1142 client.java, 1145–1147 client/server computing, 1140 client/server example, 1143 data transmission through sockets, 1142 InetAddress class, 1147–1148 multiple clients connected to single server, 1148–1151 overview of, 1139–1140 quiz and exercises, 1168–1171 sending and receiving objects, 1151–1156 server sockets, 1140–1141 server.java, 1143–1144 summary, 1168 TicTacToeClient.java, 1162–1168 TicTacToeConstants.java, 1157 TicTacToeServer.java, 1157–1162 new operator creating arrays, 246–247 creating objects, 329 next method, whitespace characters and, 133 nextLine method, whitespace characters and, 133 1310 Index Next-line style, block styles, 19 NICs (network interface cards), Nine tails problem graphic approach to, 1048–1053 reducing to shortest path problem, 1086–1090 No-arg constructors class design guidelines, 526 Loan class, 368 wrapper classes not having, 381 Node, 536–539 Nodes, AVL trees balancing on a path, 970–971 creating, 973 creating and storing in AVLTreeNode, 969–970 deleting elements, 972 rotation, 973–974 Nodes, binary trees deleting leaf node, 944–945 overview of, 930 representing binary search trees, 931 Nodes, JavaFX, 545–546 Nodes, linked lists creating, 910 deleting, 914–916 overview of, 906–908 storing elements in, 911 Nonleaves, finding, 960 Not (!) logical operator, 93–97 Not equal to (!=) comparison operator, 76 NotSerializableException, 695 null values, objects, 331–332 NullPointerException, as runtime error, 332 Number class case study: abstract number class, 501 as root class for numeric wrapper classes, 585 Numbers/numeric types abstract number class, 501–503 binary see Binary numbers case study: converting hexadecimals to decimals, 217–219 case study: displaying prime numbers, 188–190 case study: generating random numbers, 223–225 case study: guessing numbers, 161–163 casting to/from char types, 127 conversion between numeric types, 56–58, 364 converting to/from strings, 389–390 decimal see Decimal numbers double see double floating-point see Floating-point numbers (float data type) generating random numbers, 87–88 GreatestCommonDivisorMethod.java, 215–216 hexadecimal see Hexadecimal numbers integers see Integers (int data type) LargestNumbers.java, 502–503 overview of, 44–46 PrimeNumberMethod.java, 216–217 processing large numbers, 384–385 types of number systems, 1273 Numerators, in rational numbers, 520 Numeric keypads, on keyboards, Numeric literals, 48–49 Numeric operators applied to characters, 127 overview of, 46–47 O Object class, 422–423, 431–432 Object I/O see ObjectInputStream/ObjectOutputStream classes Object member access operator (.), 330, 429 Object reference variables, 330 ObjectInputStream/ObjectOutputStream classes overview of, 692–693 serializable interface, 695–696 Serializing arrays, 696–697 TestObjectInputStream.java, 694 TestObjectOutputStream.java, 693–694 Object-oriented programming (OOP), 322, 330, 370–373 Objects accessing data and methods of, 330–331 accessing via reference variables, 330 array of, 351–352 ArrayList class, 432–433 arrays as, 259 automatic conversion between primitive types and wrapper class types, 383–384 BigInteger and BigDecimal classes, 384–385 cannot be created from abstract classes, 500 case study: designing class for stacks, 378–380 case study: designing Course class, 376–377 casting, 427–428 CircleWithPrivateDataFields.java example, 345–346 CircleWithStaticMembers.java example, 338–339 class abstraction and encapsulation, 366–367 class design guidelines, 525–527 classes from Java Library, 334 comparing primitive variables with reference variables, 332–334 composing, 374–375 constructors, 329 creating, 324–325 data field encapsulation for maintaining classes, 344–345 Date class, 334–335 defining classes for, 322–324 edges defined as, 1021 equals method of Object class, 431–432 event listener object, 589 event objects, 588 immutable, 353–354 inheritance see inheritance key terms, 358, 399 Loan.java, 368–370 null values, 331–332 Object class, 422–423 object-oriented thinking, 370–373 overview of, 321–322, 365–366 passing to methods, 347–351 polymorphism, 123 processing primitive data type values as, 380–383 quiz and exercises, 359–364, 399–408 Random class, 355–356 reference data fields and, 331 representing edges, 1021 runnable objects, 1098 sending and receiving over network, 1151–1156 SimpleCircle.java example, 324–325 static variables, constants, and methods and, 337–338 summary, 359, 398–399 TestCircleWithPrivateDataFields.java example, 346–347 TestCircleWithStaticMembers.java example, 339–342 Index 1311 TestLoanClass.java, 367–368 TestSimpleCircle.java example, 324–326 TestTV.java example, 328–329 this reference and, 356–358 TotalArea.java example, 352–353 TV.java example, 327–328 variable scope and, 355–356 vertices as object of any type, 1019 visibility modifiers, 342–344 Octal integer literals, 49 Off-by-one errors arrays and, 251 in loops, 160 OOP (object-oriented programming), 322, 330, 370–373 Open addressing, hashing collision handling using, 989 double hashing, 991–993 linear probing, 989–990 quadratic probing, 990–991 Operands defined, 46 incompatible, 95 Operators assignment operator (=), 41–43 augmented assignment operators, 54–55 bit operators, 1277 comparison operators, 76 increment and decrement operators, 55–56 numeric operators, 46–47 precedence and associativity, 104–106 precedence and associativity chart, 1268–1269 precedence rules, 50–51 processing, 786 SQL arithmetic operators, 1186 SQL comparison or Boolean operators, 1184 SQL like, between-between-and, and is null operators, 1185 unary and binary, 47 Option buttons See Radio buttons Or (||) logical operator, 93–97 Oracle JDBC drivers for accessing Oracle databases, 1189–1192 tutorials on, 1178 order by clause, displaying sorted tuples, 1187–1188 OSs (operating systems) overview of, tasks of, 9–10 Output see also I/O (input/output) redirection, 167–168 streams, 678–679 OutputStream classes BufferedOutputStream, 688–690 case study: copying files, 691–692 data transmission through sockets, 1142 DataOutputStream, 684–686 DetectEndOfFile.java, 687 FileOutputStream, 681–682 FilterOutputStream, 684 ObjectOutputStream, 692–693, 1151 overview of, 680–681 serialization and, 695 TestDataStream.java, 686–687 TestFileStream.java, 682–683 TestObjectOutputStream.java, 693–694 Overflows Rational class, 524 variables, 45 Overloading methods, 219–222 Overriding methods, 419–422, 970 P p (pi), estimating, 237 Package-private (package-access) visibility modifiers, 342 Packages organizing classes in, 343 organizing programs in, 18 Packet-based communication, Java supporting, 1140 Page Down key, on keyboards, Page Up key, on keyboards, Pair of points, algorithm for finding closest, 843–846 Palindromes case study: checking if string is a palindrome, 187–188 case study: ignoring nonalphanumeric characters when checking palindromes, 396–398 palindrome integers, 234 palindromic primes, 240 RecursivePalindrome.java, 714–715 RecursivePalindromeUsingSubstring.java, 713–714 Panels ButtonInPane.java, 540 MessagePanel class see MessagePanel class Parallel edges, 1018 Parallel programming see also Multithreading overview of, 1128–1129 ParallelMax.java, 1132–1133 ParallelMergeSort.java, 1130–1132 Parameters actual parameters, 205 defining methods and, 204–205 generic classes, 742 generic methods, 744 generic parameters not allowed in static context, 751–752 as local variable, 222 order association, 212 passing by values, 212–215 variable-length argument lists, 264–265 Parent, 539 Parentheses (( )) defining and invoking methods and, 225 in Welcome.java, 14 Parsing methods, 382 Pascal, high-level languages, Pass-by-sharing arrays to methods, 258 objects to methods, 348–349 Pass-by-value arrays to methods, 258 Increment.java example, 212–213 objects to methods, 347–348 overview of, 212 TestPassByValue.java example, 213–215 PaswordField, 641 PathTransition, 609–612 Passwords, checking if string is valid password, 238 Pentagonal numbers, 234 Perfect hash function, 986 1312 Index Perfectly balanced trees, 966 Pivot element, 870 Pixels (picture elements) measuring resolution in, Points, 849 algorithm for finding closest pair of, 843–846 finding convex hull for a set of points, 849 Polygon and Polyline overview, 569 ShowPolygon.java, 570–571 Polymorphism CastingDemo.java example, 428–431 overview of, 423 PolymorphismDemo.java example, 423 Polynomial hash codes, 988 Postfix decrement operator, 55–56 Postfix increment operator, 55–56 Postorder traversal time complexity of, 948 tree traversal, 933 pow method, Math class, 48 Precedence, operator, 104–106, 1268–1270 Prefix decrement operator, 55–56 Prefix increment operator, 55–56 Prefix notation, 794 Preorder traversal time complexity of, 948 tree traversal, 933 PreparedStatement, for creating parameterized SQL statements, 1197–1199 Primary key constraints, integrity constraints in relational model, 1176–1178 Prime numbers algorithm for finding, 837 case study: displaying prime numbers, 188–190 comparing prime number algorithms, 843 EfficientPrimeNumbers.java example, 839–842 PrimeNumberMethod.java, 216–217 PrimeNumbers.java example, 838–839 SieveOfEratosthenes.java example, 842–843 types of, 240 Primitive types (fundamental types) automatic conversion between primitive types and wrapper class types, 383–384, 739 casting, 429 comparing parameters of primitive type with parameters of reference types, 349 comparing primitive variables with reference variables, 332–334 converting wrapper object to/from (boxing/unboxing), 383 creating arrays of, 351 hash codes for, 987 Prim’s minimum spanning tree algorithm Dijkstra’s algorithm compared to, 1078 overview of, 1073–1075 print method, PrintWriter class, 38, 476–477, 744–745 printf method, PrintWriter class, 476 Printing arrays, 291 println method, PrintWriter class, 38, 476 printStackTrace method, 461 PrintWriter class case study: replacing text, 480–482 writing data to file using, 476–477 for writing text data, 678 Priority queues implementing, 924 MyPriorityQueue.java example, 924 overview of, 783 PriorityQueue class, 784–785 for storing weighted edges, 1063 TestPriorityQueue.java example, 924–925 PriorityBlockingQueue class, 1122–1123 PriorityQueue class, 784–785 private encapsulation of data fields and, 344–345 visibility modifier, 343–344, 440–443 Problems breaking into subproblems, 190 creating programs to address, 34 solving with recursion, 712–713 Procedural paradigm, compared with object-oriented paradigm, 372–373 Procedures, 205 see also Methods Processing arrays, 249–251 Programming errors see also Exception handling ClassCastException, 428 debugging, 106 logic errors, 21–23 minimizing numeric errors related to loops, 178–179 runtime errors, 20–21 selections, 83–87 syntax errors, 14, 20 using generic classes for detecting, 738–739 Programming languages assembly language, high-level languages, 8–9 Java see Java programming machine language, overview of, Programming style block styles, 19 comments and, 19 indentation and spacing, 19 overview of, 18–19 Programs/programming assignment statements and expressions, 41–43 augmented assignment operators, 54–55 case study: counting monetary units, 63–65 case study: displaying current time, 52–53 character data type, 125–130 coding incrementally, 161 databases see Java database programming evaluating expressions and operator precedence rules, 50–51 exponent operations, 48 identifiers, 39–40 increment and decrement operators, 55–56 introduction to, 34 with Java language see Java programming key terms, 67 modularizing code, 215–217 named constants, 43 naming conventions, 44 numeric literals, 48–50 numeric operators, 46–47 numeric type conversions, 56–58 numeric types, 44–45 Index 1313 overview of, questions and exercises, 68–74 reading input from console, 37–39 recursive methods in, 706 software development process, 59–63 string data type, 130–139 summary, 67–68 variables, 40–41 writing a simple program, 34–37 protected data and methods, 440–442 visibility modifier, 343–344, 440–442 Protected data fields, in abstract classes, 899 Pseudocode, 34 Public classes, 325 public method, 346 public visibility modifier, 342–344, 440–442 Python, high-level languages, Q Quadratic algorithm, 825, 829–830 Quadratic probing, collision handling, 990–991 Queries, SQL, 1183–1184 Query methods, Map interface, 811 Query operations, Collection interface, 764 Queue interface, 783, 1123 Queues blocking queues see Blocking queues breadth-first search algorithm, 1045 bucket sorts and, 882–883 as collection type, 762 Deque interface, 783–786 GenericQueue.java example, 922–923 implementing, 920–921 overview of, 782 priority queues see Priority queues Queue interface, 783, 1123 TestStackQueue.java example, 922–923 unbounded, 1122 WeightedGraph class, 1067–1068 Quick sorts merge sorts compared with, 874 overview of, 870 quick sort algorithm, 870–871 QuickSort.java example, 871–874 Quincunx, 280 Quotients Quotient.java example, 450 QuotientWithException.java example, 452–454 QuotientWithIf.java example, 451 QuotientWithMethod.java example, 451–452 R Race conditions, in multithreaded programs, 1111 Radio buttons creating, 1222–1226 RadioButtonDemo.java, 638–639 Radix sorts, 881–883 Ragged arrays, 290–291, 1022 RAM (random-access memory), 4–5 Random class, java.util, 335–336 random method case study: generating random numbers, 223–225 case study: lottery, 98–99 Math class, 87–88, 122 Random numbers case study: generating random numbers, 223–225 case study: lottery, 98–99 generating, 87–88 Random-access files overview of, 697–699 TestRandomAccessFile.java, 699–700 Random-access memory (RAM), 4–5 Rational class case study: designing class for matrix using generic types, 752–753 overview of, 520–521 Rational.java example, 522–525 RationalMatrix.java example, 755–756 TestRationalClass.java example, 521–522 TestRationalMatrix.java example, 756–757 Rational numbers, representing and processing, 520–522 Raw types, backward compatiblity and, 746–747 readASolution method, applying to Sudoku grid, 300 Read-only streams, 697 see also InputStream class Read-only views, Collections class, 816 Rebalancing AVL trees, 966–968 Records insert, update, and delete, 1182–1183 relational structures, 1175 Rectangle overview, 564 ShowRectangle.java, 564–565 Recurrence relations, in analysis of algorithm complexity, 829 Recursion binary searches, 716–717 case study: computing factorials, 706–707 case study: computing Fibonacci numbers, 709–710 case study: determining directory size, 717 case study: fractals, 722–723 case study: Towers of Hanoi, 719–721 ComputeFactorial.java, 707–709 ComputeFactorialTailRecursion.java, 727–728 ComputeFibonacci.java, 710–712 depth-first searches (DFS), 1038–1039 DirectorySize.java, 717–719 displaying/visualizing binary trees, 949 Fork/Join Framework and, 1128 helper methods, 714 iteration compared with, 726–727 key terms, 728 overview of, 706 problem solving by thinking recursively, 712–713 questions and exercises, 728–736 RecursivePalindrome.java, 714–715 RecursivePalindromeUsingSubstring.java, 713–714 RecursiveSelectionSort.java, 715–716 selection sorts, 715 SierpinskiTriangle.java, 723–724 summary, 728 tail recursion, 727 TowersOfHanoi.java, 721–722 Recursive methods, 706 Red-black trees, 986, 1002 Reduction, characteristics of recursion, 712 1314 Index Reference types classes as, 330 comparing parameters of primitive type with parameters of reference types, 349 comparing primitive variables with, 332–334 generic types as, 738 reference data fields, 331–332 string data type as, 130 Reference variables accessing objects with, 330 array of objects as array of, 352 comparing primitive variables with, 332–334 regionMatches method, strings, 134–135 Register listeners ControlCircle.java, 592–593 ControlCircleWithMouseAndKey.java, 605–606 KeyEventDemo.java, 604 LoanCalculator.java, 600 overview of, 589–590 Regular expressions, matching strings with, 388 Rehashing load factor and, 993–995 time complexity of hashing methods and, 1002 Relational DBMS foreign keys in, 1177 integrity constraints, 1176–1178 overview of, 1174–1175 relational structures, 1175–1176 Relational model, 1175 Relational structures, 1175–1176 Relations, 1175 Relative file names, 473–474 Remainder (%) or modulo operator, 46, 50 Remainder (%=) assignment operator, 54–55 remove method, linked lists, 906–907 Repetition determining Big O for repetition statements, 824–827 loops see Loops replace method, strings, 388 replaceAll method, strings, 388 replaceFirst method, strings, 388 Request-scoped bean, 1233 Requirements specification, in software development process, 59–60 Reserved words see Keywords (reserved words) Resource ordering, to avoid deadlocks, 1126 Resources, role of OSs in allocating, Responsibilities, separation as class design principle, 526 Result set metadata, 1205 ResultSetMetaData interface overview of, 1205 TestResultSetMetaData.java, 1205–106 return statements, 207 Return value type constructors not having, 329 in defining methods, 205 Reusable code benefits of stepwise refinement, 232 code modularization and, 215 method enabling, 208 methods for, 204 reverse method applying to lists, 774 returning arrays from methods, 260–261 Right subtree, of binary trees, 930 Right-heavy, balancing AVL nodes, 966 RL imbalance, AVL nodes, 967–968 RL rotation AVLTree class, 972–973 balancing nodes on a path, 970 options for balancing AVL nodes, 967–968 Root, of binary trees, 930–931 Rotation AVLTree class, 972–973 balancing nodes on a path, 970–971 implementing, 971 methods for performing, 977 options for balancing AVL nodes, 966–967 Rounding methods, Math class, 122 Round-robin scheduling, of CPU time, 1104 Rows see Tuples (rows) RR imbalance, AVL nodes, 966–967 RR rotation AVLTree class, 974, 975 balancing nodes on a path, 970 options for balancing AVL nodes, 966–967 run method, for running threads, 1100, 1101 Runnable interface tasks as instances of, 1098–1099 Thread class, 1102 Runtime errors debugging, 106 declaring, 457–458 exception handling and, 39, 450 NullPointerException as, 332 programming errors, 21 Runtime stacks see Call stacks S Scanner class obtaining input with, 67 for reading console input, 37–39 reading data from file using, 478–479 for reading text data, 678 Scanners case study: replacing text, 480–481 creating, 454 Scene, 536–539 Scheduling operations, 10 Scientific notation, of integer literals, 49–50 Scope, of variables, 42, 222–223 Screen resolution, Script, for creating MySQL database, 1180–1181 Scroll bars overview of, 651 ScrollBarDemo.java, 652–653 Scroll panes DescriptionPanel.java, 643 overview of, 641 scrolling lists, 648 search method, AVLTree class, 981 Searches arrays, 265 binary search trees see Binary search trees binary searches, 266–269, 716–717 linear searches, 265–266 Index 1315 recursive approach to searching for words, 706 search keys, 986, 1011 Secondary clustering, quadratic probing issue, 991 Segments, merging, 886–887 select statements column aliases and, 1185–1186 queries with, 1183–1184 Selection sort algorithm analyzing, 828 recurrence relations and, 829 Selection sorts arrays, 265, 269–270 RecursiveSelectionSort.java, 715–716 using recursion, 715 Selection statements, 76, 78, 724–727 Selections Addition.Quiz.java example, 77–78 boolean data type, 76–78 case study: computing Body Mass Index, 89–90 case study: computing taxes, 90–93 case study: determining leap year, 97 case study: guessing birthdays, 139–142 case study: lottery, 98–99 common errors, 83–84 conditional expressions, 103–104 debugging, 106 formatting console output, 145–146 generating random numbers, 87–88 if statements, 78–79 if-else statements, 80–81 key terms, 107 logical operators, 93–97 nested if statements and multi-way if-else statements, 81–83 operator precedence and associativity, 104–106 overview of, 76 questions and exercises, 108–118 summary and exercises, 107 switch statements, 100–103 Semaphores, controlling thread access to shared resources, 1124–1126 Semicolons (;), common errors, 83 Sentinel-controlled loops, 165–167 Separate chaining handling collision in hashing, 993 implementing map using hashing, 995–996 Sequence statements, determining Big O for, 824–827 Sequential files, input/output streams, 697 Serialization of arrays, 696–697 of objects, 695 Student.java example, 1152 Servers client/server example, 1143 multiple clients connected to single server, 1148–1151 server sockets, 1140–1141 server.java, 1143–1144 StudentServer.java, 1154–1156 TicTacToeServer.java, 1157–1162 ServerSocket class, 1140 Session-scoped bean, 1233, 1252 Session tracking, 1233–1235 set method, List interface, 768 Set operations, Collection interface, 764 setLength method, StringBuilder class, 395–396 setPriority method, Thread class, 1104 setRadius method CircleWithPrivateDataFields.java example, 346 SimpleCircle example, 325 Sets case study: counting keywords, 809–810 as collection type, 762 comparing list performance with, 806–808 HashSet class, 798–799 key terms, 817 LinkedHashSet class, 802 overview of, 798 questions and exercises, 818–820 singleton and unmodifiable, 8816–817 summary, 817–818 synchronized collections for, 1127–1128 TestHashSet.java example, 799–800 TestMethodsInCollection.java example, 800–801 TestTreeSet.java example, 803–804 TestTreeSetWithComparator.java example, 804–806 TreeSet class, 802–803 Sets, implementing with hashing MyHashSet.java example, 1005–1010 MySet.java example, 1004–1005 overview of, 1004 TestMyHashSet.java example, 1010–1011 Setter (mutator) methods ArrayList class and, 436 encapsulation of data fields and, 344–347 implementing linked lists, 906–907 Seven Bridges of Königsberg problem, 1016–1017 Shallow copies, clone method and, 515–516 Shapes, 539–542 Arc, 567–569 Circle and Ellipse, 565–567 Line, 562–563 Polygon and Polyline, 569–572 Rectangle, 564–565 text, 560–562 Sharing code, 208 short, numeric types hash codes for primitive types, 987 overview of, 45 Short-circuited OR operator, 96 Shortest path tree, 1082 Shortest paths case study: weighted nine tails problem, 1086–1090 Dijkstra’s algorithm, 1079–1084 finding with graph, 117 nine tails problem, 1048–1053 overview of, 1078–1079 TestShortestPath.java, 1084–1086 WeightedGraph class and, 1069 ShortestPathTree class, 1082–1084 Shuffling arrays, 250–251, 292 Sierpinski triangle case study, 722–723 computing recursively, 729, 735–736 SierpinskiTriangle.java, 723–726 Sieve of Eratosthenes, 842–843 Simple graphs, 1017 sin method, trigonometry, 120–121 Single precision numbers see Floating-point numbers (float data type) 1316 Index Single-dimensional arrays see Arrays, single-dimensional Single-source shortest path algorithm, Dijkstra’s, 1079–1084 Singly linked lists see LinkedList class Sinking sorts, 280, 864–866 sleep method, Thread class, 1103 Sliders overview of, 654 SliderDemo.java, 655–656 Sockets client sockets, 1141–1142 data transmission through, 1142 overview of, 1140 server sockets, 1140–1141 in Server.java example, 1143–1144 Software development process, 59–61 programs as, sort method Arrays class, 270–271 ComparableRectangle.java example, 511–512 lists and, 773–774 SortRectangles.java example, 512–513 using recursion, 715–716 SortedMap interface, 812, 813 Sorting adding nodes to heaps, 875–876 arrays using heaps, 879 bubble sort algorithm, 962–963 bucket sorts and radix sorts, 881–882 complexity of external sorts, 889–890 complexity of heap sorts, 879–880 CreateFile.java example of external sort, 883–885 external sorts, 883 Heap class and, 878–879 heap sort algorithm, 874–875 Heap.java example, 878–879 HeapSort.java example, 879–880 implementation phases of external sorts, 884–885 key terms, 890 merge sort algorithm, 867–870 overview of, 862 questions and exercises, 891–894 quick sort algorithm, 870–874 removing root from heap, 876–877 storing heaps, 875 summary, 890 Sorting arrays bubble sorts, 279 case study: generic method for, 744–745 insertion sorts, 862–864 overview of, 269 selection sorts, 265, 269–270 Source objects, event sources and, 588–589 Source program or source code, 7, 39–40 Spacing, programming style and, 18 Spanning trees graphs, 1018 minimum spanning trees, 1072–1073 MST algorithm, 1075–1076 Prim’s minimum spanning tree algorithm, 1073–1075 TestMinimumSpanningTree.java, 1076–1078 traversing graphs and, 1037–1038 Special characters, 14 Specific import, 18 split method, strings, 388, 389 SQL (Structured Query Language) CallableStatement for executing SQL stored procedures, 1199–1202 column aliases, 1185–1186 creating databases, 1180–1181 creating tables, 1181–1182 creating user account in MySQL, 1179–1180 for defining and accessing databases, 1174 insert, update, and delete statements, 1182–1183 JDBC and, 1190–1194 operators, 1184–1186 overview of, 1178 PreparedStatement for creating parameterized SQL statements, 1197–1198 queries, 1183–1184 table joins, 1188–1189 tuples, 1187–1188 Stack class, 782 StackOfIntegers class, 378–379 StackOverflowError, recursion causing, 726 Stacks case study: designing class for stacks, 378–379 case study: evaluating expressions, 786–787 EvaluateExpression.java example, 788–790 GenericStack class, 741–742 implementing, 820–821 Stack class, 782 TestStackQueue.java example, 922–923 Stage , 536, 539 start method, for starting threads, 1099, 1101 Starvation, thread priorities and, 1104 State of objects, 322–323 of threads, 1126–1127 Statements break statements, 101 continue statements, 184–185 executing one at a time, 106 executing repeatedly (loops), 158 in high-level languages, if see if statements if-else see if-else statements return statements, 206 switch statements, 100–101 synchronizing, 1111–1112 terminators, 13 Statements, SQL auto commit and, 1194 CallableStatement for executing SQL stored procedures, 1199–1200 create table statement, 1181 drop table statement, 1182 insert, update, and delete, 1182–1183 PreparedStatement for creating parameterized SQL statements, 1103–1104 select statements, 1183–1185 Static methods in CircleWithStaticMembers.java, 338–339 class design guidelines, 526–527 declaring, 338 defined, 338 for lists and collections, 773 Index 1317 when to use instance methods vs static, 338–339 wrapper classes and, 382 Static variables in CircleWithStaticMembers.java, 338–339 class, 337–338 class design guidelines, 526–527 declaring, 338 instance variables compared with, 337 in TestCircleWithStaticMembers.java, 339 when to use instance variables vs static, 340 Stepwise refinement benefits of, 232 implementation details, 229–232 method abstraction, 225–226 top-down and/or bottom-up implementation, 227–229 top-down design, 226–227 Storage devices CDs and DVDs, disks, overview of, 4–5 USB flash drives, Storage units, for measuring memory, 3Stored procedures, executing SQL stored procedures, 1199–1202 Stream-based communication, Java supporting, 1140 String class, 386 String concatenation operator (+), 36 String literals, 386 String variables, 386 StringBuffer class, 386, 393, 397 StringBuilder class case study: ignoring nonalphanumeric characters when checking palindromes, 396–397 modifying strings in, 393–395 overview of, 338, 393 toString, capacity, length, setLength, and charAt methods, 395–396 Strings in binary I/O, 684–685 case study: checking if string is a palindrome, 187–188 case study: converting hexadecimals to decimals, 188–189 case study: ignoring nonalphanumeric characters when checking palindromes, 396–397 Character class, 189–190 command-line arguments, 272–275 concatenating, 36, 130 constructing, 386 converting to/from arrays, 389 finding characters or substrings in, 388–389 formatting, 390–392 generic method for sorting array of Comparable objects, 744–745 hash codes for, 987–988 immutable and interned, 386–387 key terms, 275 matching, replacing, and splitting by patterns, 388–389 overview of, 386 questions and exercises, 276–285 replacing, and splitting, 387 string data type, 130 StringBuilder and StringBuffer classes, 393–396 substrings, 37, 135–136 summary, 275–276 in Welcome.java, 12–13 Structure, in relational data model, 1174–1175 Structured Query Language see SQL (Structured Query Language) Subclasses abstract methods and, 496 abstracting, 500 constructors, 416–417 of Exception class, 456–457 inheritance and, 410–411 of RuntimeException class, 457 Subdirectories, 717 Subgraphs, 1018 Subinterfaces, 518 substring method, 135, 714 Substrings, 135–136 Subtraction (-) operator, 46, 50 Subtraction (-=) assignment operator, 54–55 Subtrees of binary trees, 930 searching for elements in BST, 932 Sudoku puzzle, 298–301, 859–860, 1137–1138 sum method, 293–294 super keyword, 416 Superclass methods, 418–419 Superclasses of abstract class can be concrete, 500 classes extending, 517 inheritance and, 410–411 subclasses related to, 496 Superkey attribute, primary key constraints and, 1177 Supplementary characters, Unicode, 125 swap method swapping elements in an array, 259–260 in TestPassByValue.java example, 213–214 switch statements ChineseZodiac.java example, 102–103 overview of, 100–101 Synchronization wrapper methods, Collections class, 1128 Synchronized blocks, 1112, 1133 Synchronized collections, 1126–1127 synchronized keyword, 1111 Syntax errors (compile errors) common errors, 14 debugging, 106–107 programming errors, 20–21 Syntax rules, in Welcome.java, 14 System activities, role of OSs, System analysis, in software development process, 59–60 System design, in software development process, 59, 61 System errors, 456 System resources, allocating, System.in, 37 System.out, 37, 145–149 T Tables creating, 1181–1182 dropping, 1182 insert, update, and delete records, 1182–1183 integrity constraints, 1176–1178 joins, 1188–1189 obtaining, 1204 queries, 1183–1184 relational structures, 1175 1318 Index Tables, storing, 288 Tail recursion ComputeFactorialTailRecusion.java, 727–728 overview of, 727 tan method, trigonometry, 120–121 TaskClass, 1100 Tasks creating, 1098–1099 running multiple see Multithreading TaskThreadDemo.java, 1100–1101 threads providing mechanism for running, 1098 TBs (terabytes), of storage, TCP (Transmission Control Protocol), 1140 Teamwork, facilitated by stepwise refinement, 232 Terabytes (TBs), of storage, Testing benefits of stepwise refinement, 232 in software development process, 60, 62–63 Text case study: replacing text, 480–481 files, 678 overview, 560 ShowText.java, 561–562 txt files (text), 680 TextAreaDemo.java, 644 TextFieldDemo.java, 639–641 TextArea, 641–644 TextField, 639–641 Text I/O vs binary I/O, 679–680 handling in Java, 678–679 overview of, 678 TextPad, for creating/editing Java source code, 15 this reference invoking constructors with, 357–358 overview of, 356–358 referencing hidden data fields with, 356–357 Thread class creating tasks and, 1100 deprecated methods, 1103 methods of, 1103–1104 overview of, 1102 Thread pools, 1106–1108 Thread synchronization AccountWithoutSync.java, 1109–1111 overview of, 1108–1109 synchronization using locks, 1112–1114 synchronized keyword, 1111 synchronizing statements, 1111–1112 Threads blocking queues, 1122–1124 case study: producer/consumer thread cooperation, 1119–1122 controlling animation with (flashing text case study), 1105–1106 creating, 1098–1099 deadlocks and, 1126 locks enforcing cooperation among threads, 1114–1115 overview of, 1098 semaphores, 1124–1126 states, 1126–1127 TaskThreadDemo.java, 1100–1102 Thread class, 1102–1104 ThreadCooperation.java, 1116–1119 Thread-safe classes, 1111, 1128 Three-dimensional arrays see Arrays, multi-dimensional throw keyword chained exceptions, 470 throw ex for rethrowing exceptions, 469 for throwing exceptions, 459 Throwable class generic classes not extending, 752 getting information about exceptions, 461–462 java.lang, 455–456 Throwing exceptions CircleWithException.java example, 463 QuotientWithException.java example, 453 rethrowing, 468–469 TestCircleWithCustomException.java example, 471 throw keyword for, 458–459 throws keyword for declaring exceptions, 458 IOException, 680–681 Tic-tac-toe game, 308, 1156–1157 TimeBean, 1220 Time sharing, threads sharing CPU time, 1098 Timers, for animation control, 1105–1106 toCharArray method, converting strings into arrays, 389 ToggleButton, 637 ToggleGroup, 637–638 Token reading methods, Scanner class, 479–480 Top-down design, 226–227 Top-down implementation, 227–229 toString method ArrayList class, 435 Arrays class, 270–271 Date class, 335 MyArrayList.java example, 903 Object class, 431 StringBuilder class, 395–396 total variable, for storing sums, 291 Towers of Hanoi problem analyzing algorithm for, 828–829 computing recursively, 730 nonrecursive computation, 796 recurrence relations and, 829 Tracing a program, 36 transient keyword, serialization and, 695 Transistors, CPUs, Transmission Control Protocol (TCP), 1140 Traveling salesperson problem (TSP), 1091 Traversing binary search trees, 933–934 Traversing graphs breadth-first searches (BFS), 1045–1048 case study: connected circles problem, 1042–1045 depth-first searches (DFS), 1038–1042 overview of, 1038 TestWeightedGraph.java, 1071 Tree class as inner class of AbstractGraph class, 1031 MST class extending, 1075–1076 ShortestPathTree class extending, 1082–1084 traversing graphs and, 1037 Tree interface, BST class, 935–936 Tree traversal, 933–935 TreeMap class case study: counting occurrence of words, 815–816 concrete implementation of Map class, 810–812 Index 1319 implementation of Map class, 986 overview of, 813 TestMap.java example, 813–815 types of maps, 810–811 Trees AVL trees see AVL trees binary search see Binary search trees connected graphs, 1018 creating BFS trees, 1046 Huffman coding see Huffman coding trees overview of, 930 red-black trees, 986, 1002 spanning trees see Spanning trees traversing, 933–934 TreeSet class implementation of Set class, 1002 overview of, 802–803 TestTreeSet.java example, 803–804 TestTreeSetWithComparator.java example, 504–506 types of sets, 798 Trigonometric methods, Math class, 120–121 trimToSize method, 904 True/false (Boolean) values, 76 Truth tables, 93–94 try-catch blocks catching exceptions, 457, 459–461 chained exceptions, 469–470 CircleWithException.java example, 464–465 exception classes cannot be generic, 752 InputMismatchExceptionDemo.java example, 454 QuotientWithException.java example, 452 rethrowing exceptions, 468–469 when to use exceptions, 467–468 Tuples (rows) displaying distinct, 1186–1187 displaying sorted, 1187–1188 primary key constraints and, 1176 relational structures, 1175 Twin primes, 240 Two-dimensional arrays see Arrays, two-dimensional Type casting between char and numeric types, 127 generic types and, 740 loss of precision, 65 for numeric type conversion, 56–57 Type erasure, erasing generic types, 750–751 U UDP (User Datagram Protocol), 1140 UML (Unified Modeling Language) aggregation shown in, 374 class diagrams with, 323 diagram for Loan class, 367 diagram of StackOfIntegers, 378 diagram of static variables and methods, 337–339 Unary operators, 47 Unbounded queues, 1123 Unbounded wildcards, 748 Unboxing, 383 Unchecked exceptions, 457 Unconditional AND operator, 104 Underflow, floating point numbers, 66 Undirected graphs, 1017 Unicode character data type (char) and, 125–129 data input and output streams, 685 generating random numbers and, 223 text encoding, 678 text I/O vs binary I/O, 679 Unified Modeling Language see UML (Unified Modeling Language) Uniform Resource Locators see URLs (Uniform Resource Locators) Unique addresses, for each byte of memory, Universal serial bus (USB) flash drives, UNIX epoch, 52 UnknownHostException, local hosts and, 1142 Unweighted graphs defined, 1018 modeling graphs and, 1024, 1026 UnweightedGraph.java example, 1033–1034 Upcasting objects, 427 Update methods, Map interface, 811 Update statements, SQL, 1182–1183 URL class, java.net, 482 URLs (Uniform Resource Locators) for connecting JDBC to other databases, 1191 ReadFileFromURL.java example, 483–484 reading data from Web, 482–483 USB (universal serial bus) flash drives, User accounts, MySQL, 1179–1180 User Datagram Protocol (UDP), 1140 UTF-8, 685 see also Unicode V valueOf methods converting strings into arrays, 389 wrapper classes and, 382 Value-returning methods return statements required by, 207 TestReturnGradeMethod.java, 209–211 void method and, 205 Values hashing functions, 986 maps and, 1011 values method, Map interface, 811 Variable-length argument lists, 264–265 Variables Boolean variables see Boolean variables comparing primitive variables with reference variables, 332–334 control variables in for loops, 171–172 declaring, 35–36, 41 declaring array variables, 246 declaring for two-dimensional arrays, 288–289 displaying/modifying, 106 hidden, 355 identifiers, 39–40 naming conventions, 44 overflow, 65 overview of, 40–41 reference variables, 330 scope of, 41, 222–223, 355–356 static variables, 337–338 1320 Index representing, 1063 shortest paths, 1078 summary, 1090 Vector class methods, 781–782 overview of, 781 Stack class extending, 782 Vertex-weighted graphs, 1063 Vertical scroll bars, 652 Vertical sliders, 654, 655 Vertices AbstractGraph class, 1031 adjacent and incident, 1018 depth-first searches (DFS), 1038 Graph.java example, 1028 on graphs, 1017 Prim’s algorithm and, 1072 representing on graphs, 1019–1020 shortest paths see Shortest paths TestBFS.java, 1046 TestGraph.java example, 1026 TestMinimumSpanningTree.java, 1076 TestWeightedGraph.java, 1070 vertex-weighted graphs, 1063 weighted adjacency matrices, 1064 WeightedGraph class, 1065–1066 Video, MediaDemo.java, 663–664 View-scoped bean, 1233 Virtual machines (VMs), 16 see also JVM (Java Virtual Machine) Visibility (accessibility) modifiers classes and, 342–343 protected, public, and private, 440–442 Visual Basic, high-level languages, Visualizing (displaying) graphs Displayable.java example, 1034 DisplayUSMap.java example, 1035–1037 GraphView.java example, 1035 overview of, 1034 VLSI (very large-scale integration), 706 VMs (virtual machines), 21 see also JVM (Java Virtual Machine) void method defined, 205 defining and invoking, 209 TestVoidMethod.java, 209 W Web, reading file data from, 482–484 Weighted graphs case study: weighted nine tails problem, 1086–1089 defined, 1017 Dijkstra’s single-source shortest-path algorithm, 1079–1084 key terms, 1090 minimum spanning trees, 1072–1073 modeling graphs and, 1024 MST algorithm, 1075–1076 overview of, 1015–1016 Prim’s minimum spanning tree algorithm, 1073–1075 priority adjacency lists, 1064–1065 questions and exercises, 1090–1096 TestMinimumSpanningTree.java, 1076–1078 TestShortestPath.java, 1084–1086 TestWeightedGraph.java, 1070–1072 weighted adjacency matrices, 1064 weighted edges using edge array, 1063–1064 WeightedGraph class, 1065–1066 WeightedGraph.java, 1066–1070 WeightedEdge class, 1064 WeightedGraph class getMinimumSpanningTree method, 1075, 1077–1078 overview of, 1097–1098 ShortestPathTree class as inner class of, 1082–1083 TestWeightedGraph.java, 1070–1072 WeightedGraph.java, 1066–1070 Well-balanced trees AVL trees, 966 binary search trees, 986 where clause, select statements, 1183 while loops case study: guessing numbers, 161–163 case study: multiple subtraction quiz, 164–165 case study: predicting future tuition, 181 deciding when to use, 174–176 design strategies, 163 do-while loop see do-while loop input and output redirections, 167–168 overview of, 158–159 RepeatAdditionQuiz.java example, 160–161 sentinel-controlled, 165–167 servers serving multiple clients, 1149 syntax of, 158 Whitespace characters, 133 as delimiter in token reading methods, 479 Wildcard import, 38 Wildcards, for specifying range of generic types, 747–750 Windows see Frames (windows) Windows OSs, Wireless networking, Worst-case input heap sorts and, 880 measuring algorithm efficiency, 822, 836 Wrapper classes automatic conversion between primitive types and wrapper class types, 683–684, 739 File class as, 473 numeric, 521 primitive types and, 380–383 Wrapping lines of text or words, 641, 643 Write-only streams, 697 see also OutputStream class X Xlint:unchecked error, compile time errors, 746 Java Quick Reference Console Input Conditional Expression Scanner input = new Scanner(System.in); int intValue = input.nextInt(); long longValue = input.nextLong(); double doubleValue = input.nextDouble(); float floatValue = input.nextFloat(); String string = input.next(); String line = input.nextLine(); boolean-expression ? expression1 : expression2 y = (x > 0) ? : -1 System.out.println(number % == ? "number is even" : "number is odd"); Console Output System.out.println(anyValue); Primitive Data Types byte short int long float double char boolean bits 16 bits 32 bits 64 bits 32 bits 64 bits 16 bits true/false Arithmetic Operators + * / % ++var var var++ var Relational Operators < >= == != less than less than or equal to greater than greater than or equal to equal to not equal addition subtraction multiplication division remainder preincrement predecrement postincrement postdecrement Assignment Operators = += -= *= /= %= Logical Operators && || ! ^ short circuit AND short circuit OR NOT exclusive OR switch Statements loop Statements switch (intExpression) { case value1: statements; break; case valuen: statements; break; default: statements; } while (condition) { statements; } { statements; } while (condition); for (init; condition; adjustment) { statements; } assignment addition assignment subtraction assignment multiplication assignment division assignment remainder assignment if Statements if (condition) { statements; } if (condition) { statements; } else { statements; } if (condition1) { statements; } else if (condition2) { statements; } else { statements; } Companion Web site: www.pearsonhighered.com/liang Java Quick Reference Frequently Used Static Constants/Methods Math.PI Math.random() Math.pow(a, b) Math.abs(a) Math.max(a, b) Math.min(a, b) Math.sqrt(a) Math.sin(radians) Math.asin(a) Math.toRadians(degrees) Math.toDegress(radians) System.currentTimeMillis() Integer.parseInt(string) Integer.parseInt(string, radix) Double.parseDouble(string) Arrays.sort(type[] list) Arrays.binarySearch(type[] list, type key) Text File Output PrintWriter output = new PrintWriter(filename); output.print( ); output.println( ); output.printf( ); Array/Length/Initializer int[] list = new int[10]; list.length; int[] list = {1, 2, 3, 4}; Multidimensional Array/Length/Initializer int[][] list = new int[10][10]; list.length; list[0].length; int[][] list = {{1, 2}, {3, 4}}; Ragged Array int[][] m = {{1, 2, 3, 4}, {1, 2, 3}, {1, 2}, {1}}; File Class Object Class File file = new File(filename); file.exists() file.renameTo(File) file.delete() Object o = new Object(); o.toString(); o.equals(o1); Comparable Interface Text File Input c.compareTo(Comparable) c is a Comparable object Scanner input = new Scanner( new File(filename)); String Class ArrayList Class String s = "Welcome"; String s = new String(char[]); int length = s.length(); char ch = s.charAt(index); int d = s.compareTo(s1); boolean b = s.equals(s1); boolean b = s.startsWith(s1); boolean b = s.endsWith(s1); boolean b = s.contains(s1); String s1 = s.trim(); String s1 = s.toUpperCase(); String s1 = s.toLowerCase(); int index = s.indexOf(ch); int index = s.lastIndexOf(ch); String s1 = s.substring(ch); String s1 = s.substring(i,j); char[] chs = s.toCharArray(); boolean b = s.matches(regex); String s1 = s.replaceAll(regex,repl); String[] tokens = s.split(regex); ArrayList list = new ArrayList(); list.add(object); list.add(index, object); list.clear(); Object o = list.get(index); boolean b = list.isEmpty(); boolean b = list.contains(object); int i = list.size(); list.remove(index); list.set(index, object); int i = list.indexOf(object); int i = list.lastIndexOf(object); printf Method System.out.printf("%b %c %d %f %e %s", true, 'A', 45, 45.5, 45.5, "Welcome"); System.out.printf("%-5d %10.2f %10.2e %8s", 45, 45.5, 45.5, "Welcome"); Companion Web site: www.pearsonhighered.com/liang Uploaded by [StormRG] ... to prepare students to become proficient Java programmers A brief version (Introduction to Java Programming, Brief Version, Tenth Edition) is available for a first course on programming, commonly... Java Enterprise Edition (Java EE) to develop server-side applications, such as Java servlets, JavaServer Pages (JSP), and JavaServer Faces (JSF) ■ Java Micro Edition (Java ME) to develop applications... phones This book uses Java SE to introduce Java programming Java SE is the foundation upon which all other Java technology is based There are many versions of Java SE The latest, Java SE 8, is used