www.elsolucionario.net www.elsolucionario.net Java Quick Reference Console Input GUI Input Dialog 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 string = JOptionPane.showInputDialog( "Enter input"); int intValue = Integer.parseInt(string); double doubleValue = Double.parseDouble(string); Message Dialog Console Output JOptionPane.showMessageDialog(null, "Enter input"); System.out.println(anyValue); Primitive Data Types Arithmetic Operators Assignment Operators byte short int long float double char boolean + * / % ++var var var++ var = += -= *= /= %= bits 16 bits 32 bits 64 bits 32 bits 64 bits 16 bits true/false addition subtraction multiplication division remainder preincrement predecrement postincrement postdecrement assignment addition assignment subtraction assignment multiplication assignment division assignment remainder assignment Relational Operators Logical Operators if Statements < >= == != && || ! ^ if (condition) { statements; } less than less than or equal to greater than greater than or equal to equal to not equal 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; } if (condition) { statements; } else { statements; } if (condition1) { statements; } else if (condition2) { statements; } else { statements; } Companion Web site: www.pearsonhighered.com/liang www.elsolucionario.net Java Quick Reference Frequently Used Static Constants/Methods Math.PI Math.random() Math.pow(a, b) System.currentTimeMillis() System.out.println(anyValue) JOptionPane.showMessageDialog(null, message) JOptionPane.showInputDialog( prompt-message) Integer.parseInt(string) Double.parseDouble(string) Arrays.sort(type[] list) Arrays.binarySearch(type[] list, type key) 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}}; Text File Output PrintWriter output = new PrintWriter(filename); output.print( ); output.println( ); output.printf( ); 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); 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(); 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 www.elsolucionario.net INTRODUCTION TO JAVA TM PROGRAMMING COMPREHENSIVE VERSION Eighth Edition Y Daniel Liang Armstrong Atlantic State University Prentice Hall 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 www.elsolucionario.net Vice President and Editorial Director, ECS: Marcia J Horton Editor in Chief, Computer Science: Michael Hirsch Executive Editor: Tracy Dunkelberger Assistant Editor: Melinda Haggerty Editorial Assistant: Allison Michael Vice President, Production: Vince O’Brien Senior Managing Editor: Scott Disanno Production Editor: Irwin Zucker Senior Operations Specialist: Alan Fischer Marketing Manager: Erin Davis Marketing Assistant: Mack Patterson Art Director: Kenny Beck Cover Image: Male Ruby-throated Hummingbird / Steve Byland / Shutterstock; Hummingbird, Nazca Lines / Gary Yim / Shutterstock Art Editor: Greg Dulles Media Editor: Daniel Sandin Copyright © 2011, 2009, 2007, 2004 by Pearson Higher Education Upper Saddle River, New Jersey, 07458 All right reserved Manufactured 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 materials from this work, please submit a written request to Pearson Higher Education, Permissions Department, Lake Street, Upper Saddle River, NJ 07458 The author and publisher of this book have used their best efforts in preparing this book These efforts include the development, research, and testing of the theories and programs to determine their effectiveness The author and publisher make no warranty of any kind, expressed or implied, with regard to these programs or the documentation contained in this book The author and publisher shall not be liable in any event for incidental or consequential damages in connection with, or arising out of, the furnishing, performance, or use of these programs Library of Congress Cataloging-in-Publication Data on file 10 ISBN-13: 978-0-13-213080-6 ISBN-10: 0-13-213080-7 www.elsolucionario.net This book is dedicated to Dr S K Dhall and Dr S Lakshmivarahan of the University of Oklahoma, who inspired me in teaching and research Thank you for being my mentors and advisors To Samantha, Michael, and Michelle www.elsolucionario.net PREFACE fundamentals-first problem-driven This book uses the fundamentals-first approach and teaches programming concepts and techniques in a problem-driven way The fundamentals-first approach introduces basic programming concepts and techniques before objects and classes My own experience, confirmed by the experiences of many colleagues, demonstrates that new programmers in order to succeed must learn basic logic and fundamental programming techniques such as loops and stepwise refinement The fundamental concepts and techniques of loops, methods, and arrays are the foundation for programming Building the foundation prepares students to learn object-oriented programming, GUI, database, and Web programming Problem-driven means focused on problem solving rather than syntax We make introductory programming interesting by using interesting problems The central thread of early chapters is on problem solving Appropriate syntax and library are introduced to support the writing of a program for solving the problems To support the teaching of programming in a problemdriven way, the book provides a wide variety of problems at various levels of difficulty to motivate students In order to appeal to students in all majors, the problems cover many application areas in math, science, business, financials, gaming, animation, and multimedia Two Versions comprehensive version brief version This comprehensive version covers fundamentals of programming, object-oriented programming, GUI programming, algorithms and data structures, concurrency, networking, internationalization, advanced GUI, database, and Web programming It is designed to prepare students to become proficient Java programmers A brief version (Introduction to Java Programming, Brief Version, Eighth Edition) is available for a first course on programming, commonly known as CS1 The brief version contains the first 20 chapters of the comprehensive version What’s New in This Edition? This edition substantially improves Introduction to Java Programming, Seventh Edition The major improvements are as follows: ■ This edition is completely revised in every detail to enhance clarity, presentation, content, examples, and exercises ■ In the examples and exercises, which are provided to motivate and stimulate student interest in programming, one-fifth of the problems are new early console input ■ In the previous edition, console input was covered at the end of Chapter The new edition introduces console input early in Chapter so that students can write interactive programs early hand trace box ■ The hand trace box is added for many programs to help novice students to read and trace programs multidimensional arrays ■ Single-dimensional arrays and multidimensional arrays are covered in two chapters to give instructors the flexibility to cover multidimensional arrays later Sudoku problem simplified ■ The case study for the Sudoku problem has been moved to the Companion Website A more pedagogically effective simple version of the Sudoku problem is presented instead ■ The design of the API for Java GUI programming is an excellent example of how the object-oriented principle is applied Students learn better with concrete and visual examples complete revision new problems iv www.elsolucionario.net Preface v So, basic GUI now precedes the introduction of abstract classes and interfaces The instructor, however, can still choose to cover abstract classes and interfaces before GUI basic GUI earlier ■ Exception handling is covered before abstract classes and interfaces so that students can build robust programs early The instructor can still choose to cover exception handling later exception handling earlier ■ Chapter 12, “Object-Oriented Design and Patterns,” in the previous edition has been replaced by spreading the design guidelines and patterns into several chapters so that these topics can be covered in appropriate context design guidelines ■ The chapter on sorting now follows right after the chapter on algorithm efficiency, so that students can immediately apply algorithm efficiency to sorting algorithms sorting ■ A brand-new bonus Chapter 44 covers Java 2D Java 2D ■ The coverage on data structures is expanded with new bonus chapters on AVL trees, splay trees, 2-4 trees, B-trees, and red-black trees, and hashing So the book can be used for a full data structures course new data structures chapters Learning Strategies A programming course is quite different from other courses In a programming course, you learn from examples, from practice, and from mistakes You need to devote a lot of time to writing programs, testing them, and fixing errors For first-time programmers, learning Java is like learning any high-level programming language The fundamental point is to develop the critical skills of formulating programmatic solutions for real problems and translating them into programs using selection statements, loops, methods, and arrays Once you acquire the basic skills of writing programs using loops, methods, and arrays, you can begin to learn how to develop large programs and GUI programs using the objectoriented approach When you know how to program and you understand the concept of object-oriented programming, learning Java becomes a matter of learning the Java API The Java API establishes a framework for programmers to develop applications using Java You have to use the classes and interfaces in the API and follow their conventions and rules to create applications The best way to learn the Java API is to imitate examples and exercises Pedagogical Features The book uses the following elements to get the most from the material: ■ Objectives list what students should have learned from the chapter This will help them determine whether they have met the objectives after completing the chapter ■ Introduction opens the discussion with representative problems to give the reader an overview of what to expect from the chapter ■ Problems 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 ■ 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 ■ Review Questions are grouped by sections to help students track their progress and evaluate their learning ■ Programming Exercises are grouped by sections to provide students with opportunities to apply on their own the new skills they have learned The level of difficulty is rated as easy (no learn from mistakes programmatic solution object-oriented programming Java API www.elsolucionario.net vi Preface 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 ■ LiveLab is a course assessment and management system Students can submit programs online The system automatically grades the programs/multiple-choice quizzes and gives students instant feedback Instructors can create custom programming exercises and quizzes as well as use the system prebuilt exercises and quizzes ■ Notes, Tips, and Cautions 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 the 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 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 Part I: Fundamentals of Programming (Chapters 1–7) The first part of the book is a stepping stone, preparing you to embark on the journey of learning Java You will begin to know Java (Chapter 1) and will learn fundamental programming techniques with primitive data types, variables, constants, assignments, expressions, and operators (Chapter 2), control statements (Chapters 3–4), methods (Chapter 5), and arrays (Chapters 6–7) After Chapter 6, you may jump to Chapter 20 to learn how to write recursive methods for solving inherently recursive problems Part II: Object-Oriented Programming (Chapters 8–11, 13–14, 19) 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 8–10), class inheritance (Chapter 11), polymorphism (Chapter 11), exception handling (Chapter 13), abstract classes (Chapter 14), and interfaces (Chapter 14) Processing strings will be introduced in Chapter along with text I/O Binary I/O is introduced in Chapter 19 www.elsolucionario.net 1330 Index Graphs: (continued) TestDFS.java, 914–915 time complexity, 913 directed, 893 edge array, 895–896 edge objects, 896 edges, 894 edges, representing, 895–898 Graph.java, 902–903 Knight’s Tour problem, 923–930 defined, 924 Hamiltonian cycle, 924 Hamiltonian path, 924 Hamiltonian path algorithm (listing), 926–927 KnightTourApp class, 924 KnightTourApp.java, 929–930 KnightTourModel class, 924 KnightTourModel.java, 925–926 NP-complete, use of term, 927 time complexity, 927 modeling, 898–909 and modeling of real-world problems, 892, 923 representing, 894–898 simple, 894 TestGraph.java, 900–902 theory, 892 undirected, 893 UnweightedGraph class, 898, 900, 902 UnweightedGraph.java, 908–909 vertices, representing, 894–895 Greatest common divisor, finding: case studies, 774–777 GCD1.java, 774–776 GCD2.java, 776–777 problem, 131–133 GreatestCommonDivisor.java, 132–133 GreatestCommonDivisorMethod.java, 165–166 GregorianCalendar class, 462–463, 1060 GridLayout manager, 413–415, 505, 1114 properties, 417 ShowGridLayout.java, 414–415 specifying the number of rows/columns in a grid, 414 Growth functions, comparing, 771 Growth rate, 766 GuessDate class: designing, 359–362 GuessDate.java, 361–362 UseGuessDateClass.java, 360–361 Guessing numbers (problem), 118–120 GuessNumber.java, 119–120 GuessNumberOneTime.java, 118–119 GuessNumberUsingBreak.java, 137 GUI event dispatch thread, 979–980 EventDispatcherThreadDemo.java, 979–980 GUI programming, 406–424 arcs, drawing, 506–507 Color class, 419 component classes, 406–407 container classes, 406–407 Font class, 408, 419–420 frames, 408–410 GUI classes, classification of, 407 helper classes, 406, 408 image icons, 422–424 Java GUI API, 406–408 layout managers, 411–417 BorderLayout manager, 415–417 FlowLayout manager, 411–413 GridLayout manager, 413–415 properties of, 417 setLayout method, 411, 420 panels, using as subcontainers, 417–419 polygons/polylines, drawing, 507–510 Swing GUI components, 406–407 common features of, 420–424 Swing vs AWT, 406 H Hand-traces, 55 HandleASession class, 1043 HandleEvent.java, 470–471 Handlers, 536, 1094 Handling the exception, use of term, 434 Hard disks, Hardware, 2, Hash map, 753–755 Hash sets, 730–732, 746 hashCode method, 731 HashMap class, 751–752 HashSet class, 730–734 Hashtable class, 753, 1003 hasNext() method, Iterator interface, 730, 880 Heap class, 804–806 class diagram, 804 heap time complexity, 807 Heap.java, 804–806 Heap sort, 801–802 HeapSort.java, 806 merge sort vs., 806 sort time, 801 Heaps, defined, 801 Heap class, 804–806 height of, 807 new node, adding, 802 root, removing, 802–804 Heavyweight Swing components, 406 Height, 510 Helper classes, 406, 408 Hertz (Hz), Heuristics, 929 hgap property: BorderLayout manager, 417, 1114 FlowLayout manager, 417 GridLayout manager, 417 Hidden data fields, 346 Hidden static methods, 383 High-level languages, 6, Histogram.java, 604–606 Hoare, C A R., 797 Horizontal alignment, 574, 584 Horizontal text position, 575 House.java, 472–473 howToEat method, 466, 475–476 hspace attribute, 617 HTML tag, 616 Hypertext Markup Language (HTML), I I/O, in Java, 650 IBM DB2, 1278 IBM Informix, 1278 Icons: alignments, 574 sharing, 424 text positions, 575 Identifiers, 299 using abbreviations for, 52 IdentifyHostNameIP.java, 1025–1026 IEEE 754, 33 if else statements, 79 if statements, 74–75 nested, 80–81 simple, 75 IllegalArgumentException, 438, 440, 445 Image icons, 422–424, 1152–1153, 1214 TestImageIcon.java, 423–424 ImageIcon, 1131 Images, displaying, 520–522 DisplayImage.java, 521–522 ImageViewer class, 522-525 ImageViewer.java, 525–525 SixFlags.java, 523 Immutable classes, 344, 487 Immutable objects, 344–345 Immutable strings, 302–303 Implicit import, 17 ImprovedFibonacci.java, 773 Incompatible operands, 90 Increment and decrement operators, 40, 45 Incremental development and testing, 88, 183 Increment.java, 163 Indent code, 52 Indentation style, 52 Indexed variables, 200 InetAddress class, 1025–1026 Infinite loop, 117, 128 Infinite recursion, 679 Information hiding, 177 Inheritance, 374 aggregation vs., in class design, 412 casting objects, 387–389 defined, 374 and modeling of the is-a relationship, 379, 394 multiple, 379 Object class, 384 overriding methods, 383–384 overriding vs overloading methods, 383–384 single, 379 subclasses, 374–379 super keyword, 380–382 superclass, 374–379 using to design stack and queue classes, 843 init method, Applet class, 620 initial-action, 126–127 Inner class, 541–542 Inner class listeners, 541 InnerClass class, 541–542 Inorder traversal, 861, 870 InorderIterator class, 880 inorderIterator() method, 880 Input dialogs, 55–58, 1167–1168 defined, 1167 using, 56–57 Input errors, 54 Input/output devices, 2, 4–5 keyboard, 4–5 monitor, mouse, Input stream, defined, 652 InputMismatchException, 327 InputStream class, 652 Insert key, insert(element) method, 870 www.elsolucionario.net Insertion sort, 219–222 InsertionSort.java, 222 Insertion sort algorithm, 770 insertRow method, 1242 Insets class, 1126 Inside access, 283 Instance, 264 Instance method, 271 Instance variables, 278, 350 Instantiation, 264 generic, 708 int, 32 Integer literals, 35 Integer vs decimal division, 37 Integer weights, 940 Integer wrapper class, 476 IntegerMatrix class, 719, 721 IntegerMatrix.java, 721–722 Integer.parseInt method, 56 Integrated Development Environment (IDE), 10 debugging in, 55 Integrity component, relational database systems, 1274 Integrity constraints, 1276–1278 domain constraints, 1276–1277 enforcing, 1277–1278 foreign key constraints, 1277 primary key constraints, 1277 Interface inheritance, 465 Interfaces, 465–476, 898–899 abstract classes vs., 473–476 in class design, 475 ActionListener interface, 469–471 Cloneable interface, 471–473 defined, 465 distinguishing from a class, 465 and generic programming, 469 in the Java Collections Framework, 728 marker, 471 naming convention, 4758 TestEdible.java, 465–466 International clock display, 1064–1066 WorldClockApp.java, 1066 WorldClockControl.java, 1064–1066 WorldClock.java, 1064 Internationalization, 1015–1047 character encoding, 1084–1085 EncodingDemo.java, 1085 date/time, displaying, 1060–1071 Locale class, 1058–1060 constants based on language, 1060 country codes, 1059 getAvailableLocales() method, 1060 language codes, 1059–1060 local sensitive operations, 1060 locale property, 1058 numbers, formatting, 1071 currency format, 1073 DecimalFormat class, 1074 example of, 1074–1077 locale dependence of, 1072 NumberFormat class, 1072–1074 NumberFormatDemo.java, 1074–1077 parsing numbers, 1073 percent format, 1073 plain number format, 1072–1073 resource bundles, 1077–1084 for the Chinese language (example), 1080 defined, 1077 for the English language (example), 1079 for the French language (example), 1080 getBundle method, 1078 ListResourceBundle class, 1077 MissingResourceException, 1079, 1084 naming conventions, 1078 property resource bundles, 1084 ResourceBundle class, 1077–1078, 1084 ResourceBundleDemo.java, 1080–1084 updateString method, 1084 ResourceBundle class, 1058 Unicode, 1058 Interned strings, 302–303 Internet, defined, 1018 Internet Protocol (IP), 1018 Internet Protocol (IP) address, 1018 Internet Service Provider (ISP), 1018 Interrelational constraints, 1276 interrupt() method, 977, 1002 InterruptedException, 977 Intrarelational constraints, 1276 invokeAndWait method, 979 invokeLater method, 979 Invoking a second constructor, 347 IOException class, 654 IP address, 1018 is-a relationships, 394, 475 is-kind-of relationship, 475 is null operator, 1284 isAlive() method, 1002 isCellEditable method, TableModel, 1243 isDigit method, Character class, 314 isEmpty() method, Map interface, 752 isEmpty() method, MyStack class, 394 isFocusable property, 557 isLetter method, Character class, 314 isLetterOrDigit method, Character class, 314 isLowerCase method, Character class, 314 isPalindrome method, 684 isVisited array, 914, 916, 929 ItemEvent, 537, 1094 ItemListener interface, 537 Iteration of a loop, 116 Iteration, recursion vs., 697 Iterator interface, 730, 739–740, 747, 880 Iterators, 879–881 advantages of, 881 defined, 879 Iterator interface, 880 Iterator pattern, 881 TestBinaryTreeWithIterator.java, 880–881 variations of, 881 J JApplet class, 618, 1114 Java, anatomy of characteristics of, defined, 2, 12 versatility of, 10 Java applet, accessing a database from, 1292–1294 FindGrade.java, 1292–1294 Java bytecode, running, 14 Java class, 265, 272 java ClassName, 15 Java Collections Framework, 728–757, 898, 1002 AbstractCollection interface, 729–730 Collection interface, 729–730 Comparator interface, 737–738 GeometricObjectComparator.java, 737–738 Index 1331 constructors, for concrete classes in, 737 defined, 728 design of, 729 interfaces and classes defined in, 729 maps, 751–756 priority queues, 748–750 queues, 748–750 sets, 706, 730–737 Set interface, 730 Stack class, 746–747 types of collections supported by, 729 Vector class, 746–747 java command, 15, 22 Java compiler, 12, 14 Java database programming, 1231–1268, 1250–1252, See also Database systems database systems, defined, 1274 JDBC, 1244–1252, See also JDBC URLs, 1247 PreparedStatement interface, 1253 preparedStatement method, 1253 relational database systems, 1274–1278 attributes, 1275 integrity, 1274 integrity constraints, 1276–1278 language, 1274 relational data model, 1274 structure, 1274 tables, 1275–1276 tuples, 1275 relational structures, 1275–1276 Structured Query Language (SQL), 1278–1286 arithmetic operators, 1284–1285 between-and operator, 1283–1284 Boolean operators, 1282–1283 from clause, 1282, 1286 column alias, 1284 comparison operators, 1282–1283 creating a database, 1279–1280 creating a user account on, 1278–1279 creating and dropping tables, 1280–1281 defined, 1278 delete records, 1281–1282 distinct tuples, displaying, 1285 inserting records, 1281–1282 is null operator, 1283–1284 like operator, 1283–1284 select clause, 1282–1283, 1285 simple queries, 1282 standard SQL, 1278 tables, joining, 1286 updating records, 1281–1282 Java Development Toolkit (JDK), 10 Java Enterprise Edition (Java EE), 14 Java expressions, evaluating, 36–37 java file, 14 Java GUI API, 406–408 Java keywords, See Keywords Java language specification, 10–11 Java Micro Edition (Java ME), 10 Java modifiers, See Modifiers Java program-development process, 13 Java program, simple, 11–13 Java source-code file, creating, 14 Java source programs, case sensitivity of, 14 Java Standard Edition (Java SE), 10 Java Virtual Machine (JVM), 14, 208, java.awt package, 406, 408 java.awt.Applet class, 1112 java.awt.Color class, 408, 419 java.awt.Component, 1112 1332 Index java.awt.Container, 408, 1112, 1115, 1123 java.awt.Dialog, 1112, 1174 java.awt.Dimension, 408 java.awt.Font, 408, 419 java.awt.FontMetrics, 408 java.awt.Frame class, 1112 java.awt.Graphics, 408, 499, 521 java.awt.GraphicsEnvironment, 420 java.awt.LayoutManager, 408 JavaBeans, 1092–1106 components, 1092 relationship between Java classes and, 1092–1093 custom event sets, creating, 1101–1106 CourseWithEnrollmentEvent.java, 1103–1105 EnrollmentEvent class, 1101–1102, 1104 EnrollmentEvent.java, 1101–1102 enrollmentExceeded method, 1104 EnrollmentListener class, 1102 EnrollmentListener.java, 1102–1103 TestCourseWithEnrollmentEvent.java, 1105–1106 custom source components, creating, 1097–1101 CourseWithActionEvent class, 1097–1098 CourseWithActionEvent.java, 1098–1099 deregistration method, 1097 multicast listener, 1097 registration method, 1097 TestCourseWithActionEvent.java, 1100–1101 defined, 1092 delegation-based model, 1094 event, 1094 event classes, 1094–1095 event listener interface, 1094–1095 event object, 1094 event set, 1094 Java event model, 1094–1096 listener, 1094 listener components, 1095–1096 minimum component requirements, 102 properties, 1093–1094 and data fields, 1093–1094 property-naming patterns, 1093 source components, 1095 source object, 1094 javac command, 15 javadoc comments, 51–52 java.io.FileNotFoundException, 653 java.io.IOException, 653–654 java.lang package, 17, 39, 56, 313, 467 java.lang.Class class, 632 java.lang.ClassNotFoundException, 664 java.lang.Comparable, 467, 475 java.lang.InterruptedException, 1002 java.lang.Number, 1073 java.lang.UnsupportedOperationException,730 java.math, 481 java.net, 632 java.net.BindException, 1019, 1024 java.net.ConnectException, 1024 java.net.URL class, 632, 1037 Java’s built-in monitor, 994–995 JavaServer Pages, 10 java.sun.com, 8–10, 51, 175 java.swing.SwingConstants, 1052 java.text.DateFormat class, 1060 java.text.DecimalFormat, 1074 www.elsolucionario.net java.text.ParseException, 1073 java.util package, 28 java.util.ArrayList, 1003, 1209 java.util.Calendar, 1060 java.util.Collection, 748 java.util.concurrent package, 998 java.util.Date, 1060 java.util.EventListener, 1094, 1101 java.util.EventObject, 1094, 1101 java.util.Hashtable, 753, 1003 java.util.Map, 1003 java.util.Observer interface, 1188 java.util.Queue, 998 java.util.TimeZone, 1060 java.util.Vector, java.util.Stack, 1003 javax.swing package, 406, 1251 javax.swing.Border package, 1138 javax.swing.BorderFactory, 1138 javax.swing.BoxLayout, 1118 javax.swing.event package, 596 javax.swing.event.ChangeEvent, 1204 javax.swing.event.EventListenerList, 1099 javax.swing.event.HyperlinkEvent, 1039 javax.swing.JApplet, 407, 615 javax.swing.JDialog, 407 javax.swing.JEditorPane, 1039 javax.swing.JFileChooser, 1176–1177 javax.swing.JFrame, 407 javax.swing.JPanel, 407, 1114 javax.swing.ListSelectionModel, 593 javax.swing.RowFilter, 1235 javax.swing.SwingUtilities, 979 javax.swing.Timer, 557 javax.swing.tree package, 1251 JButton class, 276, 406, 410, 420, 422, 522, 535–536, 572–573, 575, 583, 1092, 1112–1113, 1195–1196 GUIComponents.java, 277-278 JCheckBox class, 535, 572, 581 GUIComponents.java, 277–278 JCheckBoxMenuItem class, 11501153, 1156 JColorChooser class, 1174–1176, 1181 color preview panel, 1176 defined, 1174 showDialog method, 1175 tabbed pane, 1176 JComboBox class, 276, 406–408, 410, 412–413, 420, 422, 547, 551, 587, 602, 615, 1216–1219 ComboBoxCellRendererDemo.java, 1216–1219 GUIComponents.java, 277–278 properties/constructors, 1216 JComponent class, 499, 501, 583–584, 1158 JDBC, 1286–1303 CallableStatement interface, 1297 classes, 1288 connections, establishing, 1289–1290 defined, 1286 developing database applications using, 1287–1289 drivers, 1288 loading, 1288–1289 FindGradeUsingPreparedStatement.java, 1295–1297 interfaces, 1288 Java applet, accessing a database from, 1292–1294 metadata retrieval, 1300–1303 database tables, obtaining, 1301 DatabaseMetaData interface, 1300 ResultSetMetaData interface, 1302 TestDatabaseMetaData.java, 1301 TestResultSetMetaData.java, 1303 PreparedStatement interface, 1295 relationships between Java programs, JDBC API, JDBC drivers, and relational databases, 1287 ResultSet, processing, 1290 SimpleJDBC.java, 1291–1292 statements, executing, 1290 JDBC-ODBC bridge driver, 1287, 1292 jdbc:odbc:dataSource, 1289 JDialog class, 406–407, 1112–1113, 1164, 1171 JDK 1.6, 10 JEditorPane class, 1039–1041 WebBrowser.java, 1040–1041 JFileChooser class, 290, 1176–1181, 1153 currentDirectory property, 1177 dialogTitle property, 1177 dialogType property, 1177 multiSelectionEnabled property, 1177 no-arg constructor, 1176 ReadFileUsingJFileChooser.java, 329–330 selectedFile property, 1177 selectedFiles property, 1177 showOpenDialog method, 1177 showSaveDialog method, 1177 TextEditor.java, 1177–1181 JFrame class, 276, 406–408, 410, 412–413, 420, 422, 547, 551, 587, 602, 615, 1112–1113 compared to JApplet class, 618 setDefaultCloseOpeartion method, 276 setLocation method, 276 setSize method, 276 setTitle method, 276 setVisible method, 276 JLabel class, 406, 420, 422, 500, 583–584 JList class, 276, 535, 593–594, 1196 constructors, 1205 DefaultListCellRenderer, 1212 DefaultListModel, 1210–1211 HORIZONTAL_WRAP, 1206 list layout orientations, 1206 list-selection models, 1206–1207 list-selection modes, 1206–1207 methods, 1205 properties, 1205 scrollable list, creating, 1209 string values, 1207 VERTICAL, 1206 VERTICAL_WRAP, 1206 JMenu class, 1113, 1150 JMenuBar class, 1112–1113, 1150 JMenuItem class, 1112–1113, 1150 JOptionPane class, 50, 55, 1164–1171 confirmation dialog, 1166–1167 defined, 1164 creating, 1169–1171 dialogs created using, 1164 input dialog, 1167–1168 defined, 1164, 1167 message dialogs, 1165–1166 defined, 1164 option dialog, 1168–1169 defined, 1164, 1168 showMessageDialog method, 29, 98 JOptionPaneDemo.java, 1170–1171 www.elsolucionario.net JPanel class, 277, 406–408, 417, 420, 500, 503, 521, 554, 1114, 1181 as a canvas for drawing, 500 JPasswordField class, 572, 586 JPEG (Joint Photographic Experts Group), 422 JProgressBar, 1007–1010 class diagram, 1008 ProgressBarDemo.java, 1008–1010 PropertyChangeEvent, 1010 JRadioButton class, 276, 406, 535, 578, 581 GUIComponents.java, 277–278 JRadioButtonMenuItem class, 1150–1153 JScrollBar class, 596 JScrollPane class, 1128–1132 hsbPolicy parameter, 1129 methods, 1129 ScrollMap.java, 1130–1131 setCorner method, 1129 viewport, 1128 vsbPolicy parameter, 1129 JScrollPane class, 586 JSlider class, 599 jspDate, 1204 jspDay, 1204 JSpinner class, 1196–1198 getNextValue() method, 1197–1198 getPreviousValue() method, 1197–1198 getValue() method, 1197–1198 methods, 1197–1198 sequence value, 1197–1198 SimpleSpinner.java, 1198 JSpinner.DateEditortor, 1201 JSpinner.DefaultEditor, 1201 JSpinner.ListEditor, 1202 JSpinner.NumberEditor, 1201 JSplitPane class, 1133, 1195 defined, 1133 properties/constructors/methods, 1134 ShowLayout.java, 1134–1136 jspMonth, 1204 JTabbedPane class, 1132–1133 defined, 1132 DisplayFigure.java, 1133 JTable class, 1226–1250 auto sort and filtering, 1235–1237 classes, 1227 column model, 1226 constructors, 1226 for creating tables, 1227 defined, 1226 and events, 1205 interfaces, 1226 JTableHeader, as supporting class, 1226 list-selection model, 1226 methods, 1226–1227 properties, 1226–1227, 1231 rows/columns, modifying (case study), 1237–1242 rowSorter method, 1235–1236 scrollable table, creating, 1226 table column models, 1231, 1233, 1237, 1247 AbstractTableModel class, 1231 DefaultTableModel class, 1231 TableModel interface, 1231 TableModelEvents, 1231 TestTableModel.java, 1231–1232 table model events, 1247–1250 table models, 1231 table renderers and editors, 1242–1245 custom, 1245–1247 TableColumn, as supporting class, 1226 TablePropertiesDemo.java, 1229–1231 TestTable.java, 1228 TestTableSortFilter.java, 1236–1237 JTableHeader class, 1226, 1235 JTextArea class, 572, 576 constructors/methods, 586 JTextComponent class, 1039 JTextField class, 406, 418, 420, 535, 572, 584–585 GUIComponents.java, 277–278 JToggleButton class, 578 JToolBar class, 1158–1160 floatable toolbar, 1160 ToolBarDemo.java, 1159–1160 JTree class, 1250 classes, 1251–1252 complexity of, 1251 constructors for creating tables, 1251 data representation of the tree, 1251 defined, 1250 editable property, 1265 interfaces, 1251 modifying trees (case study), 1262–1265 ModifyTree.java, 1262–1265 SimpleTreeDemo.java, 1253–1254 supporting interfaces and classes, 1251 TestTreeModel.java, 1255–1256 TestTreePath.java, 1260–1262 tree events, 1267 tree node rendering and editing, 1265–1267 JViewport class, 1128 K Key codes, 555 Key constants, 555 Key events, 555–557 defined, 555 KeyEventDemo.java, 556–557 KeyAdapter class, 551–557 Keyboard, 4–5 accelerators, 1152–1153 mnemonics, 1152–1153 KeyEvent class, 535, 537, 555, 1094, 1247 KeyEventDemo.java, 556–557 KeyListener interface, 537, 555 keyPressed handler, 555 keyReleased handler, 555 keySet() method, Map interface, 752 KeyStroke class, 1152 keyTyped handler, 555 Keywords, 11, 1311 Knight’s Tour problem: defined 923–924 Hamiltonian cycle, 924 Hamiltonian path, 924 Hamiltonian path algorithm (listing), 926–929 KnightTourModel.java, 929–930 NP-complete, use of term, 927 time complexity, 927 L Labels, 583–584 defined, 583 LAN (local area network), Language codes, 1058–1059 Language component, relational database systems, 1274 Index 1333 Large input size, 766 LargeFactorial.java, 482 lastIndexOf method, String class, 308 lastModified() method, File class, 324 Layout managers, 411–417, 1114–1123 alignmentX (alignmentY) property, 417 BorderLayout manager, 429–431, 415, 426, 1114, 1146 hgap property, 411, 1114 setHgap method, 411, 413, 415 ShowBorderLayout.java, 416 vgap property, 431, BoxLayout manager, 1121, 1134 and component’s alignmentX or alignmentY property, 1119 glue, 1119 rigid area, 1119 ShowBoxLayout.java, 1119–1122 strut, 1119–1120 unique features of, 1119 CardLayout manager, 1115–1118 add method, 1116 methods, 1116 ShowCardLayout.java, 1116–1118 custom, creating, 1123–1128 defined, 1114 doLayout method, 1115 FlowLayout manager, 411–413, 1114 hgap property, 1114–15 order of components added to a container, 407 placing components in a frame using, 417 properties, 409 setHgap method, 417 setVgap method, FlowLayout manager, 417 ShowFlowLayout.java, 411–413 vgap property, 411 GridLayout manager, 413–415, 1114 properties, 417 ShowGridLayout.java, 414–415 specifying the number of rows/columns in a grid, 414 maximumSize property, 1115 minimumSize property, 1115 null layout manager, using, 1121–1123 ShowNoLayout.java, 1122–1123 preferredSize property, 1114–1115, 1124 properties affecting sizing/location of components in container, 1114 setLayout method, 411 validate method, 1115 LayoutManager interface, 1116, 1123–1124 layoutContainer method, 1126 Lead path, 1259 Leading, 574–575 leadSelectionIndex method, 1207 leafIcon property, 1266 Leap year, determining (problem), 91 LeapYear.java, 91 Left child of a node, 872 Left subtree, 872 leftAction, MyAction class, 1164` length() method, StringBuilder, 278 Level of a tree, 872 Lightweight Swing components, 406–407 like operator, 1283 Line comment, 11 Line numbers, 11 Line separator sting, 328 Linear search algorithm, 766 Linear time, 747 1334 Index LinearSearch.java, 216–217 LineBorder class, 1136–1138 Lines, drawing, 501–502 LinkageError class, 438 Linked hash map, 752–754 Linked hash set, 734–735, 745 Linked lists, 830–842 LinkedList class, 832–833 MyLinkedList class, 832–833 addFirst(e) method, 834 add(index, e) method, 835–836 addLast(e) method, 834–835 implementing, 836–839 MyArrayList class vs., 841–842 removeFirst() method, 836–837 remove(index) method, 837–838 removeLast() method, 838–839 MyLinkedList.java, 839–841 nodes, 830–832 TestLinkedList.java, 833 variations of, 842–843 LinkedBlockingQueue, 998 LinkedHashMap class, 728 LinkedHashSet class, 728, 731 LinkedList class, 740–741 defined, 740 methods, 741 TestArrayAndLinkedList.java, 741–742 Linux, List cell renderer, 1212–1215 List interface, 739–741, 823 add method, 739 addAll method, 739–740 indexof method, 739 methods in, 739 remove method, 740 set method, 740 List layout orientations, 1206 List models, 1209–1212 and ListModel interface, 1209 ListModelDemo.java, 1210–1212 List properties demo (example), 1207–1209 List-selection models/list-selection modes, 1206–1207 ListCellRenderer class, 1212, 1214 getListCellRendererComponent method, 1212 ListCellRendererDemo.java, 1214–1215 MyListCellRenderer.java, 1213–1214, ListCellRenderer interface, 1217 ListDataEvent, 1209 ListDataListener, 1209 Listener components, 1095–1096 TestSourceListener.java, 1096 ListenerClass class, 492 Listeners, 469, 535–541 anonymous class listeners, 542–544, 547 defined, 535 inner class listeners, 542, 544 listener interface adapters, 536–537 AdapterDemo.java, 551–552 ListIterator interface, 739 add method, 730 hasNext() method, 730 next() method, 730 previous() method, 730 set method, 730 ListModel interface 1209, 1216 ListPropertiesDemo.java, 1207–1209 ListResourceBundle class, 1077 www.elsolucionario.net Lists, 593–596 738–742 array lists, 825–830 MyArrayList.java, 826–829 TestList.java, 829–830 ArrayList class, 740–742 defined, 740 TestArrayAndLinkedList.java, 741–742 trimToSize() method, 740 circular doubly l, 842–843 circular, singly linked, 842 common features for, 822–825 compared to sets, 792–793 defined, 593 doubly linked, 842–843 expressions, evaluating (case study), 847–851 JList class, 593 linked lists, 830–842 variations of, 842–843 linked structure, 822 LinkedList class 740–741 defined, 740 LinkedList(Collection), 741 methods, 741 TestArrayAndLinkedList.java, 741–742 List interface, 739 ListDemo.java, 594–596 performance of, 745–746 queues, 748–750 SetListPerformanceTest.java, 745–746 stacks, 746–748 static methods for, 742–745 ListSectionListener, 1206 ListSelectionEvent, 535 Literals, defined, 35 Load factor, 731 Loan class, 347–349 class diagram, 348 Loan.java, 349–351 test program, writing, 348–351 TestLoanClass.java, 348–349 Loan payments, computing (case study), 37–39 Local area network (LAN), 1018 Local variables, 171, 345 Locale class, 1058–1060 constants based on language, 1058 country codes, 1059 getAvailableLocales() method, 1059 language codes, 1059 local sensitive operations, 1060 locale property, 1058 Lock interface, 989 Locks and Java’s built-in monitor, 994 synchronization using, 989–991 AccountWithSyncUsingLock.java, 990–991 ReentrantLock class, 989 Log-linear time, 771 Logarithmic time, , 771 Logic errors, 54 Logical operators, 88–90 long, 32 long literal, 35 Long string, breaking, 26 Long wrapper class, 476 Loop body, 123 loop-continuation-condition, 116–117 Loop statement, 41 Loops, 103–139, 860 body, 123 case studies, 131–135 controlling, with a confirmation dialog, 139–140 controlling with a sentinel value, 122–124 defined, 116 do-while loop, 124–126 infinite, 117 iteration of, 117 for loop, 126–128 nested, 129–130 pre-test, 128 while loop, 116–124 Loss of precision, 41, 49 Lottery (problem), 91–93 Lottery.java, 91–93 Lower-bound wildcard, 715 M Mac OS, Machine language, 7, 15 Main class, 265 main method, 11–12, 15–16, 157–158, 266, 614, 618–621, 624, 634, 637 passing strings to, 320–321 Main window, 602 MalformedURLException, 1037 Map, 728 Map interface, 751–752 Maps, 751–756 AbstractMap class, 752 HashMap class, 753 LinkedHashMap class, 753 Map interface, 751–752 concrete implementations of, 752 methods, 751–752 query methods, 752 update methods, 752 SortedMap interface, 752 TestMap.java, 754–755 TreeMap class, 752 Marker interface, 471 matches method, String class, 308 Matching braces, 12 Math class, 172–175, 272, 279, 396 abs method, 174 exponent methods, 173 max method, 174 method, 174 random method, 174–175 rounding methods, 173–174 trigonometric methods, 172 Math learning tool, 73 advanced, 121–124 improved, 82–84 MatteBorder class, 1136–1138, 1144 max and methods, Collections class, 744 max method, 157–159, 468–469 Math class, 174 Max1.java, 714 maxDaysInMonth method, 1204 Max.java, 713 Mbps (million bits per second), Megabyte (MB), Megahertz (mHz), Memory chips, Memory (main memory), Menu bar, creating, 1150 Menus, 1150–1156 check-box menu items, 1151–1152 classes, 1150 www.elsolucionario.net creating, 1152 menu bar, 1150 menu items, 1151–1152 MenuDemo.java, 1153–1156 popup, 1156–1158 radio-button menu items, 1151 submenu items, 1151 using, 1153–1156 Merge sort, 794–797 algorithm (listing), 794–795 illustration, 795 merge sort time, 796–797 method for merging two arrays (listing), 794–795 quick sort vs., 801 time analysis, 796 Message dialog box, displaying text in, 16–17 Message dialogs, 1165–1166 defined, 1164 MessagePanel class (case study), 512–516 implementation of, 513 MessagePanel.java, 513–516 TestMessagePanel.java, 513 xCoordinate property, 512 yCoordinate property, 512 MessagePanel.java, 513–516 Meta object, 633 Metadata retrieval, 1300–1303 database tables, obtaining, 1301–1302 DatabaseMetaData interface, 1300–1301 ResultSetMetaData interface, 1302–1303 TestDatabaseMetaData.java, 1301 TestResultSetMetaData.java, 1303 Method abstraction, 176–183 bottom-up design, 179–180 PrintCalendar.java, 181–183 top-down design, 177–179 Method block, 12 Method header, 157 Method name, 157 Method overloading, 169 Method signature, 157 Methods, 16, 156–183, 271–272 body, 157 call stacks, 160 calling, 158–160 defined, 156–158 modularizing code, 165–167 naming, 52 overloading, 168–170 parameters, 157 passing arrays to, 209–212, 240–241 passing objects to, 286–287 passing parameters by values, 162–165 syntax for defining, 156 value-returning, 157 void, 160–162 Microsoft Windows, 6–7 method, Math class, 174 Minimum spanning trees (MSTs), 949–955 getMinimumSpanningTree method, 952 implementation of, 951–955 MST class, 952 Prim’s algorithm, 950–951 TestMinimumSpanningTree.java, 953–955 time complexity, 953 uniqueness of, 952 MissingResourceException, 1078–1079, 1084 Modal dialogs, 1176 Model-view-controller (MVC), See MVC Models, 1188 Modem, Modifier key, Modifiers, 282, 289, 395–396, 466 methods, 157, 159 ModifyTree.java, 1262–1265 Modularizing code, 165–167 GreatestCommonDivisorMethod.java, 165–166 PrimeNumberMethod.java, 166–167 Monetary units, counting (case study), 47–50 Monitor, defined, 994 Mouse, Mouse events, 552–554 MoveMessageDemo.java, 553–554 moving a message on a panel using a mouse (example), 553–554 mouseDragged method, 554 MouseEvent, 535, 537, 1094, 1106, 1247 MouseListener interface, 552–553 MouseMotionListener interface, 536–537, 552–554 mousePressed handler, 1158 mouseReleased handler, 1158 MovableMessagePanel class, 554 MoveMessageDemo.java, 553–554 MS Access, 1278 JDBC-ODBC driver, 1287 URL, 1289 MST class, 951–953 Multidimensional arrays, 236–251 birth dates, guessing (problem), 250–251 Multimedia, 634–637 animations, 634–637 Multiple-choice test, grading (problem), 241–242 GradeExam.java, 241–242 Multiple clients, serving, 1026–1029 Multiple inheritance, 379 Multiple solutions, 133 Multiple windows: creating, 602–606 Histogram.java, 604–606 MultipleWindowsDemo.java, 603–604 Multiplication (*), 33 MultiplicationTable.java, 129–130 Multiplicative constants, ignoring, 766 Multiplicity, 354 multiplyMatrix method, 720–722 Multiprocessing, Multiprogramming, multiSelectionEnabled property, JFileChooser class, 1177 Multithreading, 8, 972–1010, 1028 blocking queues, 998–999 ArrayBlockingQueue, 998–999 concrete, 998 ConsumerProducerUsingBlockingQueue.java, 999 defined, 998 LinkedBlockingQueue, 998 PriorityBlockingQueue, 998 cooperation among threads, 991–995 deadlocks, 1001–1002 avoiding, 1001–1002 defined, 972 FlashingText.java, 978–979 GUI event dispatch thread, 979–980 JProgressBar, 1007–1010 class diagram, 1008 ProgressBarDemo.java, 1008–1010 Index 1335 Producer/Consumer (case study), 995–996 and program responsiveness/interactivity, 972 Semaphore class: acquire() method, 1000 class diagram, 1001 release() method, 1000 semaphores, 1000–1001 SwingWorker class, 1004–1007 synchronized collections, 1002–1003 synchronized keyword, 987–988 tasks, 972–975 thread concepts, 972 thread pools, 983–985 thread states, 1002 thread synchronization, 985–989 MultiThreadServer.java, 1026–1029 MutableComboBoxModel interface, 1216 MutableTreeNode, 1251, 1255–1256 Mutator method, 284–285, 522 MVC, 1188–1219 MVCDemo.java, 1193–1194 Swing architecture, 1195–1196 variations, 1194–1195 MyAbstractList interface, 823–824 MyAbstractList.java, 824–825 MyAction class, 1164 MyArrayList class, time complexities for methods in, 841–842 MyArrayList.java, 826–829 add method, 828 clear method, 828 contains method, 828 ensureCapacity method, 828 get method, 828 indexOf method, 828 lastIndexOf method, 828 remove method, 829 set method, 829 toString method, 829 MyFrame.java, 408–409 MyFrameWithComponents.java,410 MyImageCellRenderer.java, 1245–1247 MyLinkedList class, 833–834 addFirst(e) method, 834 add(index, e) method, 835–836 addLast(e) method, 834–835 implementing, 834–839 MyArrayList class vs., 841–842 removeFirst() method, 836–837 remove(index) method, 838–839 removeLast() method, 837–838 MyLinkedList.java, 839–841 time complexities for methods in, 841–842 MyList interface, 823–824 MyList.java, 823–824 MyListCellRenderer.java, 1213–1214 MyPriorityQueue class, 846 MyPriorityQueue.java, 846–847 MyQueue class, 844 MySQL, 1278–1279 JDBC driver, 1287–1288 URL, 1289 MyStack class, 788 MyStack.java, 393–394, MyTableModel.java, 1243–1244 N Naming conflicts, avoiding, 266 Naming conventions, 475 www.elsolucionario.net 1336 Index Narrowing a type, 41 native keyword, 472 native modifier, 1316 Natural order, 735 nCopies method, Collections class, 744 Neighbors, 894 Nested blocks, 171 Nested class, 541–542 Nested if statements, 74, 80–81 Nested loops, 129–130 NetBeans, 10–11, 409, 1092 Network interface card (NIC), 2, Networking: applet clients, 1029–1030 client/server computing, 1018–1025 client sockets, 1019 Client.java, 1022–1025 data transmission through sockets, 1020 example of, 1020–1025 server sockets, 1018–1019 Server.java, 1021–1022 distributed TicTacToe game, 1041–1052 Cell class, 1042 HandleASession class, 1042–1043 TicTacToeClient class, 1042–1043 TicTacToeClient.java, 1047–1052 TicTacToeConstants class, 1042 TicTacToeConstants.java, 1043 TicTacToeServer class, 1042–1043 TicTacToeServer.java, 1043–1047 Domain Name Servers (DNS), 1018 domain names, 1018 IdentifyHostNameIP.java, 1025–1026 InetAddress class, 1025–1026 Internet Protocol (IP) address, 1018 JEditorPane class, 1039–1041 multiple clients, serving, 1026–1029 packet-based communications, 1018 sending and receiving objects, 1031–1036 ObjectInputStream, 1031 ObjectOutputStream, 1031 StudentAddress class, 1032 StudentAddress.java, 1032–1033 StudentClient.java, 1033–1035 StudentServer.java, 1035–1036 stream-based communications, 1018 Transmission Control Protocol (TCP), 1018 User Datagram Protocol (UDP), 1018 Web servers, retrieving files from, 1036–1039 java.net.URL class, 1037 MalformedURLException, 1037 openStream() method, 1037 ViewRemoteFile.java, 1038–1039 New account inner class (listing), 1000–1001 new operator, 267–268, 270 newCondition() method, 989, 991, 993, 997 Condition interface, 991 newDeposit condition, 991–994 newFixedThreadPool(int) method, 983 NewInterface, 474 next(), 27, 50–51 Next-line style, 52–53 next() method, Iterator interface, 740 nextByte() method, 27,326 nextDouble() method, 27,326 nextFloat() method, 27,326 nextInt() method, 27,326 nextLine() method, 27,326 nextLong() method, 27,326 nextShort() method, 27,326 NIC, 2, Nine tail problem, 919–923 NineTailModel.java, 921–923 No-arg constructor, 266 NoClassDefFoundError, 15 Nondominating terms, ignoring, 766 Nonextensible is-a relationship, 379 Nonserializable fields, 664 Nonstrict mode, floating-point arithmetic, 1311 NoSuchMethodError, 15 not operator, 1283 notify() method, 994–995 notifyAll() method, 994–995 NotSerializableException, 664 null keyword, 17 null value, 272–273 NullPointerException, 273, 438–439, 516 Number class, 477–478, 482, 486 NumberFormat class, 1072–1074 getCurrencyInstance method, 1072 getInstance method, 1072 getNumberInstance method, 1072 getPercentInstance method, 1072 setMaximumFractionDigits method, 1072 setMinimumFractionDigits method, 1072 NumberFormatDemo.java, 1074–1077 numberOfObjects, 278–284 Numbers, formatting, 42, 1071–1077 converting to strings, 56 currency format, 1073 DecimalFormat class, 1074 example of, 1074–1077 locale dependence of, 1071 NumberFormat class, 1072 NumberFormatDemo.java, 1074–1077 parsing numbers, 1073 percent format, 1073 plain number format, 1072–1073 Numeric data types, 32–37 Numeric errors: avoiding, 1313 minimizing, 130–131 Numeric keypad, Numeric literals, 35–36 Numeric operators, 33–35 on characters, 47 Numeric types: conversions, 41–42 range of, 41 Numeric values, converting to strings, 309–310 Numeric wrapper classes, 477–478 abstract methods implemented by, 478 numOfCredits attribute, 1276, 1278, 1280, 1282 O Oak language, Object class, 384 clone method, 471 equals method, 384, 477 toString method, 384 Object I/O, 662–666 TestObjectInputStream.java, 663–664 TestObjectOutputStream.java, 663 Object member access operator (.), and casting operator, 389 Object serialization, 664 ObjectInputStream class, 662–663, 1031–1033, 1036 readObject method, 1033, 1036 ObjectOutputStream class, 1031–1033, 1036 writeObject method, 1033 Objects: anonymous, 272 array of, 287–289 behavior of, 264 calling, 271 defined, 264 object reference variables vs., 271 passing to methods, 286–287 processing primitive data type values as, 476–479 state of, 270 Occurrences of letters, counting (case study), 212–215 CountLettersInArray.java, 213–215 Occurrences of words (case study), 755–756 Octal numbers, 35, 720 ODBC, 1287, 1289 Off-by-one error, 203 offer method, Queue interface, 748 openIcon property, 1266 openStream() method, 1037 Operands, converting, 41 operandStack, 847–848, 851 Operating system (OS), 7–8, 14 defined, scheduling operations, system activities, controlling/monitoring, system resources, allocating/assigning, operationMenu menu, 1156 Operator associativity, 97–98 Operator precedence, 97–98 Operator precedence chart, 97–98, 1314–1315 operatorStack, 847–851 Option buttons, See Radio buttons Option dialog, 1168–1169 defined, 1168 or operator, 1283 Oracle, 1278 JDBC driver, 1287–1289 URL, 1289 Order by comparator, 735 orientation property, 1160 OuterClass class, 541 Output stream, defined, 650 OutputStream class, 653, 659 Ovals, drawing, 501–505 Overflow, 33 Overloaded constructors, 270 Overloading methods, 168–170 TestMethodOverloading.java, 169–170 Overriding: methods, 382–383 prevention of, 396 P pack() method, 544, 586 Package-access, 282 Package-private, 282 Packages, using, 16, 282 Packet-based communications, 1018 Page Up/Page Dn keys, paintComponent method, 499–500, 505, 516, 520–521, 523 invoking, 505 TestPaintComponent.java, 500–501 Palindromes, checking (problem), 310–311 www.elsolucionario.net Panels, using as subcontainers, 417–419 TestPanels.java, 417–419 Parallel edges, 894 Parameter list, 157, 169 Parameter order association, 162 Parameters, methods, 157 Parent classes, See Superclasses parse method, 1073 parseDouble method, Double class, 478 parseInt method, Integer class, 478 Parsing numbers, 1073 Partition: illustration, 799 method, 799–800 Pascal, Pass-by-sharing, 209, 287 Pass-by-value, use of term, 163 Passing arrays to methods, 209–212 TestPassArray.java, 211–212 Passing parameters by values, 162–165 Increment.java, 163 TestPassByValue.java, 163–165 peek method: Queue interface, 748 Stack class, 747 Percent format, 1073 Pixels, 5, 498, 500 Plain number format, 1072–1073 Plus sign (+), 26 PNG (Portable Network Graphics), 422 Point class, 552, 694 poll method, Queue interface, 748 Polygons/polylines, drawing, 507–510 DrawPolygon.java, 509–510 polyLine method, 528 Polymorphism, 384–385 defined, 384 dynamic binding, 385–387 generic programming, 388 matching vs binding, 387 PolymorphismDemo.java, 385 pop() method, MyStack.java, 394 pop() method, Stack class, 747 Popup menus, 1156–1158 popup triggers, 1156 PopupMenuDemo.java, 157–1158 Postdecrement operator, 40 Postincrement operator, 40 Postorder traversal, 861, PostorderIterator class, 891 postorderIterator() method, 861 pow(a, b) method, 37, 172 Precedence, 97 Predecrement operator, 40 Predefined renderers and editors, 1242–1245 preferredSize property, 1242 Preincrement operator, 40 Preorder traversal, 861–862, 864, 866 PreorderIterator class, 880 preorderIterator() method, 880 presentNation(index) method, 637 Pressed icons, 572–573 Primary key, 1276–1278 Primary key constraints, 1277 Prime number algorithms, comparisons of, 783 Prime numbers displaying (problem), 137–139 finding (case studies), 774–783 EfficientPrimeNumbers.java, 780–782 PrimeNumbers.java, 778–780 SieveOfEratosthenes.java, 782–783 PrimeNumber.java, 138–139 PrimeNumberMethod.java, 166–167 Primitive data types, 25 Prim’s minimum spanning tree algorithm, 950–951 print method, 326 println method compared to, 28 printAdjacencyMatrix() method, AbstractGraph class, 902 PrintCalendar.java, 181–183 PrintChar class, 975 printEdges() method, AbstractGraph class, 902 PrintNum class, 975 printPath(v) method, Tree class, 902 printTree() method, Tree class, 902 PrintWriter class, writing data using, 325, 650 Priority queues, 846–847 MyPriorityQueue class, 846 MyPriorityQueue.java, 846 TestPriorityQueue.java, 847 PriorityBlockingQueue, 998 PriorityQueue class, 749–750 PriorityQueueDemo.java, 750 private constructor, 283 Private constructor, 362 Private data fields, 344, 376, 379 private modifier, 282–283, 363, 395, 1316 Procedures, 157 process method, 1010 processEvent method, 1099–1100, 1094 Processing arrays, 201–203 Producer/Consumer (case study), 995–997 ConsumerProducer.java, 996–997 Programming errors, 53–55 debugging, 54–55 logic errors, 54 runtime errors, 54 syntax errors, 53 Programming style, 51–53 defined, 51 Programs, 5–7, creating/compiling/executing, 13–16 ProgressBarDemo.java 1008–1010 Properties, 264 Property default values, 422 Protected data fields, 825 protected modifier, 282, 396, 1316 Pseudocode, 24, 106 public modifier, 274, 282, 396, 1316 publish method, 1010 publishPrimeNumbers, 1010 push() method, Stack class, 747 push(Object element) method, MyStack.java, 393–394 put method, Map interface, 750 putAll method, Map interface, 750 Q Quadratic algorithm, 768 Quadratic time, 768, 771 Queue classes, designing, 843–844 Queue interface, 748 Queues, defined, 843 Quick sort algorithm (listing), 797–798 defined, 797 illustration, 798 merge sort vs., 801 partition method, 800 Index 1337 partitioning, 798–800 quick sort time, 800–801 QuickSort.java, 798–800 quickSort methods, 798 Quotient.java, 432 QuotientWithException.java, 433–434 QuotientWithIf.java, 432–433 R Race condition, 987 Radio-button menu items, 1151 Radio buttons, 581–583 defined, 581 RadioButtonDemo.java, 582–583 radius data field, 264 radius property, 285 Radix, decimal number system, 1319 Radix sort, 807 Ragged array, 238 RAM (random-access memory), Random access files, 666–668 defined, 666 and processing of files of record, 668 TestRandomAccessFile.java, 667–668 Random class, 275 random() method, Math class, 82, 92 Random numbers, generating (case study), 175–176 RandomCharacter.java, 175–176 TestRandomCharacter.java, 176 RandomAccessFile class: defined, 666 UML diagram, 666 Rational class, 483–487 limitations of, 487 overflow, 487 properties/constructors/methods, 483 Rational.java, 484–486 TestRationalClass.java, 483–484 RationalMatrix class, 722 RationalMatrix.java, 722 Raw type, 713–714 and backward compatibility, 713 Max1.java, 714 Max.java, 713 Read-only property, 1094 Read-only streams, 757 ReadFileUsingJFileChooser.java, 329–330 readObject() method, 666, ObjectInputStream class, 1031–1033 Rectangle class, 375, 377–378 Rectangle1.java, 378 , TestCircleRectangle.java, 379 Rectangle.java, 460 Rectangles, drawing, 501–502 Recurrence functions, 760 Recursion, 678–698 advantages of, 697 defined, 678 directory size, finding (problem), 687–688 Eight Queens puzzle, 695–697 defined, 695 EightQueens.java, 695–697 factorials, computing, 678–681 base case, 678 ComputeFactorial.java, 679–680 stopping condition, 678–679 Fibonacci numbers, computing (problem), 681–683 fractals (problem), 692–695 www.elsolucionario.net 1338 Index Recursion (continued) Sierpinski triangle, 692 SierpinskiTriangle.java, 692–695 infinite, 679 iteration vs., 697 overhead, 697 and performance concern, 697 problem solving using, 683–684 RecursivePalindromeUsingSubstring.java, 684 recursive helper methods, 684–687 binary search, 686–687 RecursivePalindrome.java, 684–685 selection sort, 685–686 Tower of Hanoi (problem), 688–691 Recursive call, 678 Recursive methods, 678 Recursive thinking, 683 RecursivePalindrome.java, 684–685 RecursivePalindromeUsingSubstring.java, 684 RecursiveSelectionSort.java, 685–686 ReentrantLock class, 989 Reference type, defined, 271 Reference variables: accessing an object’s data and methods, 271-272 accessing objects via, 270–274 Circle1.java, 267–268 defined, 270 reference data fields and the null value, 272–273 and reference types, 273–274 TestCircle1.java, 266–267 variables of primitive types and reference types, differences between, 273–274 regionMatches method, String class, 304 Register listener, 536 Regular expression, 307 Relational database systems, 1274–1278 attributes, 1275 integrity, 1274 integrity constraints, 1276–1278 language, 1274 relational data model, 1274 structure, 1274 tables, 1275 tuples, 1277 Relational operators, 72 Relational structures, 1275–1276 Relative file name, 324 release() method, Semaphore class, 1001 Remainder (%), 33–34 remove method: Map interface, 751–754 Queue interface, 748 remove() method, Iterator interface, 880 removeActionListener method, 1099 removeColumn method, TableColumnModel, 1242 removeFirst() method, MyLinkedList class, 836–837 remove(index) method, MyLinkedList class, 838–839 removeLast() method, MyLinkedList class, 837–838 removeRow(rowIndex) method, 1242 reorderingAllowed property, 1235 repaint method, Component class, 505 replaceAll method, String class, 307–308 replaceFirst method, String class, 307–308 ReplaceText.java, 329 Replacing strings, 307 requestFocusInWindow() method, 586 Reserved words, 11 Resolution, 5, 409 Resource bundles, 1077–1084 for the Chinese language (example), 1080 defined, 1077 for the English language (example), 1079 for the French language (example), 1080 getBundle method, 1079 ListResourceBundle class, 1077–1078 MissingResourceException, 1079, 1084 naming conventions, 1078 property resource bundles, 1084 ResourceBundle class, 1077–1078, 1084 ResourceBundleDemo.java, 1080–1084 updateString method, 1084 Resource ordering, 1001–1002 ResourceBundle class, 1084 ResultSetMetaData interface, 1300, 1302 Rethrowing exceptions, 447 return statement, 158–161 Return value type, methods, 157 Reusing methods, 160, 379 revalidate() method, 1132, 1164 reverse method, Collections class, 743 RGB model, 419 Right-associative operators, 98 Right child of a node, 872 Right subtree, 872 rightAction, MyAction class, 1164 Rigid area, 1119 rollback() method, 1292 Rollover icons, 572–573 Rounding methods, Math class, 173–174 RowFilter class, 1235 Rows/columns, modifying (case study), 1237–1242 Add New Column button, 1238, 1242 Add New Row button, 1237, 1242 Clear button, 1238, 1242 Delete Selected Row button, 1238, 1242 ModifyTable.java, 1238–1242 Restore button, 1238, 1242 Save button, 1238, 1242 rows property, GridLayout manager, 413, 415 rowSorter method, JTable class, 1235–1237 Runnable interface, 972–973 Runnable object, 972, 975, 979, 984 Runtime errors, 54 RuntimeException, 730, 1003 S SalesTax.java, 42 InputMismatchException, 327 Scientific notation, 36 Scope of variables, 171–172 Screen resolution, Scroll bars, 596–599 JScrollBar class, 596 ScrollBarDemo.java, 598–599 ScrollMap.java, 1130–1132 search() method, Stack class, 747 Search word problem, 678 search(Object element) method, MyStack.java, 393 selectedFile property, JFileChooser class, 1177 selectedFiles property, JFileChooser class, 1177 Selection sort, 219–220, 685–686 defined, 219, 685 RecursiveSelectionSort.java, 685–686 SelectionSort.java, 220 Selection sort algorithm, 770, 792 Selection statements, 72, 81–82 selectionMode method, 593, 1206–1027 selectionMode property, 1206 selectionModel property, 1206 Selections, 72–100 Semaphore class: acquire() method, 1000–1001 class diagram, 1001 release() method, 1000–1001 Semaphores, 1000–1001 Semicolon (statement terminator), 11–12 Sentinel value, 122 SentinelValue.java, 123–124 SentinelValueUsingConfirmationDialog.java, 140 Serializable interface, 664–665, 1032, 1126, 1209 serializing arrays, 665–666 TestObjectStreamForArray.java, 665–666 Serializable objects, defined, 664 Serialization, 664 Server class, 1024 Server.java, 1021–1024 Set interface, 730 setAccelerator method, 1152 setAlignment method, FlowLayout manager, 417 setAutoCommit(false) method, 1292 setBackground method, Component class, 419, 516 setBorder method, 1152 setColor method, 503, 1194 Graphics class., 516 setColumns method, GridLayout manager, 417 setComponentPopupMenu(JPopupMenu) method, 1158 setDefaultCloseOpeartion method, JFrame class, 276 setEditor method, 1202 setFilled method, 1194 setFont method: Component class, 419, 516 Graphics class, 516 setHgap method: BorderLayout manager, 417 FlowLayout manager, 417 GridLayout manager, 417 setHorizontalTextPosition method, 1152 setJMenuBar method, 1150 setLayout method, 418–419 setlength() method, StringBuilder, 317–318 setLocation method, JFrame class, 276 setLocationRelativeTo(null), 409 setMaximumFractionDigits method, NumberFormat class, 1073 setMinimumFractionDigits method, NumberFormat class, 1073 setModel method, CircleView class, 1194 setPage(url) method, 1039 setPriority method, 977 setRadius method, 285, 1194 setRows method, GridLayout manager, 417 Sets, 730–737 compared to lists, 746 HashSet class, 730 LinkedHashSet class, 734–735 www.elsolucionario.net and nonduplicate elements, 738 performance of, 745–746 SetListPerformanceTest.java, 745–746 TestHashSet.java, 732 TestLinkedHashSet.java, 734–735 TestMethodsInCollection.java, 732–734 TestTreeSet.java, 735–736 TreeSet class, 735–736 setSize method, JFrame class, 276, 409, 544 setSize(w, h) method, 409 Setter method, 284 setTitle method, 413 JFrame class, 276, 408–409 setVgap method: BorderLayout manager, 417 FlowLayout manager, 417 GridLayout manager, 417 setVisible method, JFrame class, 276 setVisibleRowCount method, 1209 Seven Bridges of Königsberg problem, 892–893 Shallow copy, 473 Short-circuit operator, 90 short type, 27 Shortest-path tree, 958 Shortest paths, 955–965 algorithms, 955–958 implementation of, 958–962 ShortestPathTree class, 958 TestShortestPath.java, 960–962 Shorthand operators, 39–41 ShowBoxLayout.java, 1119–1121 ShowCardLayout.java, 1116–1118 showConfirmDialog method, 1167 ShowCurrentTime.java, 43–44, 274 showDayNames method, 1070 showDays method, 1070 ShowDiagonalLayout.java, 1127–1128 ShowGridLayout.java, 414–415 showHeader method, 1070 showInputDialog method, 55, 57, 1168 ShowLayout.java, 1134–1136 showMessageDialog method, JoptionPane class, 16 ShowNoLayout.java, 1122–1123 showOpenDialog method, JfileChooser class, 1177, 1180 showPopup method, 1158 showSaveDialog method, JfileChooser class, 1177, 1181 shuffle method, Collections class, 746 Sierpinski triangle, 692–694 creation of, 692 defined, 692 SierpinskiTriangle.java, 692–694 Point class, 694 Sieve of Eratosthenes algorithm, 781–783 SieveOfEratosthenes.java, 782–783 signal() method, 991, 994 signalAll() method, 991, 994 Simple graphs, 894 SimpleDateFormat class, 1062, 1070 SimpleSpinner.java, 1198 SimpleTreeDemo.java, 1253–1254 Single inheritance, 379, 473 Single precision, 33 Single selection mode, 593, 1209, 1260 Single-source all-shortest-path tree, 958 Single space, 52 size method, Map interface, 752 Sliders, 599–602 JSlider class, 599 SliderDemo.java, 600–602 SoftBevelBorder class, 1137–1138 Software, 2, 5–7, 14 defined, Sorted tuples, displaying, 1285–1286 SortedMap interface, 752 SortedSet interface, 735 Sorting, 792–816 bubble sort, 792–794 algorithm (listing), 793 bubble sort time, 794 BubbleSort.java, 793–794 defined, 793 improved algortithm (listing), 793 bucket sort, 807–809 algorithm (listing), 807–809 stability of, 807–808 defined, 792 external sort, 809–816 analysis, 816 copying first half segments (listing), 812 CreateLargeFile.java, 809–811 creating initial sorted segments (listing), 811 defined, 809 merging all segments (listing), 812–813 merging two segments (listing), 812–813 phase I, implementation of, 811 phase II, implementation of 811–812 sort phases, defined, 809 SortLargeFile.java, 813–816 two phases, combining, 812–813 heap sort, 801–807 HeapSort.java, 806–807 merge sort vs., 807 sort time, 807 lower bound on sort, 807 merge sort, 794–797 algorithm (listing), 795–796 illustration, 795 merge sort time, 796–797 method 796–797 quick sort, 797–801 algorithm (listing), 797–798 defined, 797 illustration, 798 merge sort vs., 801 partition method, 799 partitioning, 798–800 quick sort time, 800–801 QuickSort.java, 798–799 radix sort, 807–809 reasons for studying, 793 SortLargeFile.java, 814–815 Source components, 1095 Source file, 7, 14 Source object (source component), 469 Source program (source code), 6–7, 14 Spacing, 52–53 Spanning tree, 949 Special characters, escape sequences for, 46 Special floating-point values, 438 Specific import, 17 Specifier, 96–97 Speed, CPU, Spinner, defined, 1196 Spinner editors, 1201–1204 JSpinner.DateEditortor, 1201 JSpinner.DefaultEditor, 1201 JSpinner.ListEditor, 1202 Index 1339 JSpinner.NumberEditor, 1201 SpinnerModelEditorDemo.java, 1202–1204 using, 1202–1204 Spinner models, 1198–1201 SpinnerModelEditorDemo.java, 1202–1204 using, 1202–1204 SpinnerDateModel, 1198–1199, 1201, 1204 SpinnerListModel 1198–1200, 1204 SpinnerModel interface, 1198 SpinnerNumberModel, 1198, 1200, 1204 spinnerYear, 1204 Splash screen, 424 split method, String class, 307 Splitting strings, 307–308 SQL, See Structured Query Language (SQL) sqrt method, 173 Stack class, 746–748 empty() method, 747 peek() method, 747 pop() method, 747 push() method, 747 search() method, 747 Stack classes, designing, 747 StackOfIntegers class, 358–359 StackOfIntegers.java, 359 TestStackOfIntegers.java, 358–359 UML diagram, 358 Stacks, 160, 357 defined, 746 TestStackQueue.java, 845–846 start method, Applet class, 620 Start tag, 616 startAngle, 506 Starvation, 978 State, of objects, 264 Statement, 11 Statement interface, 1288, 1295 Statement terminator, 11 static inner class, 542 Static methods, 278 hidden, 383 static modifier, 1316 Static variables, 278-281, 345 Circle2.java, 279 TestCircle2.java, 279–281 Stepwise refinement, 177 StillClock class, 516–520, 559 DisplayClock.java, 516–518 StillClock.java, 518–520 UML diagram, 517 stop method, Applet class, 620 Stopping condition, 678 Storage devices, 2, Stream-based communications, 1018 Stream, defined, 650 Stream sockets, 1020 Strict mode, floating-point arithmetic, 1311 strictfp keyword, 1311 strictfp modifier, 1217 String class, 302–313 characters, 302 combining strings, 305–306 compareTo method, 304 as immutable class, 344 methods for comparing strings, 303–304 string length, 305–306 String concatenation operator, 26 String literal, 45 String type, 50–51 StringBuffer class, 315–320, 362 www.elsolucionario.net 1340 Index StringBuilder, 318 StringBuilder class, 315–320, 362 capacity() method, 318 charAt(index) method, 318 constructors, 316 initial capacity, 318 length() method, 318 methods for modifying string builders, 316–317 setlength method, 317–318 Strings: calculator (problem), 321–322 characters, finding in, 308–309 CheckPalindrome.java, 310–311 command-line arguments, 320–322 comparisons, 304–305 constructing, 302 conversion between arrays and, 309 converting, 307 converting characters and numeric values to, 309–310 converting to numbers, 56 immutable, 302–303 index range, 305 interned, 302–303 matching, by patterns, 307–308 PalindromeIgnoreNonAlphanumeric.java, 319–320 palindromes, checking (problem), 310–311 palindromes, ignoring nonalphanumeric characters when checking (problem), 318–320 passing to the main method, 320–321 replacing, 307-308 by patterns, 308 splitting, 307–308 by patterns, 308 string literal, 45, 305 string literal object, 302 string object, 302 string value, 302, 305 string variable, 302 substrings: finding in, 308–309 obtaining, 306 Strong is-a relationship, 475 Structure component, relational database systems, 1232 Structured Query Language (SQL), 1278–1286 arithmetic operators, 1284–1285 between-and operator, 1284 Boolean operators, 1282–1283 from clause, 1282 column alias, 1284 comparison operators, 1282–1283 creating a database, 1279–1280 creating a user account on, 1278–1279 creating and dropping tables, 1280–1281 defined, 1278 delete records, 1281–1282 distinct tuples, displaying, 1285 inserting records, 1281–1282 is null operator, 1284 like operator, 12831 select clause, 1282 simple queries, 1282 standard SQL, 1278 tables, joining, 1286 updating records, 1281–1282 Strut, 1119 Stubs, 179–180 Student class, 272, 344, 386–387 Student table, joining Enrollment table and, 1286 StudentAddress.java, 1032–1033 StudentClient.java, 1033–1035 StudentServer.java, 1035–1036 Subinterface, 474 Subproblem, 139 substring method, String class, 306 Substrings: finding in a string, 308–309 obtaining, 306 Subtraction (-), 33 SubtractionQuiz.java, 83–84 SubtractionQuizLoop.java, 121–122 Subtype, 384 Subwindows, 602 Sudoku game, developing an applet for, 614 Sudoku (problem), 244–248 Sun Java Website, 9–10 super keyword, 380–382 constructor chaining, 380–382 superclass constructors, 380 superclass methods, calling, 382 Superkey, 1277 Supertype, 384–385 Supplementary Unicode, 45, 651 Swing: AWT vs., 406 components, 406 Swing borders, 1136–1144 and Border interface, 1136 BorderDemo.java, 1140–1144 defined, 1136 Swing container structures, 1112–1114 JApplet class, 1113–1114 JFrame class, 1113 JPanel class, 1114 Swing GUI components, 420-421, 572, 575 common features of, 420–421 TestSwingCommonFeatures.java, 421–422 Swing MVC architecture, 1195–1196 SwingUtilities class, 979 SwingWorker class, 1004–1007, 1010 class diagram, 1004 defined, 1004 and GUI, 1007 SwingWorkerDemo.java, 1005–1007 switch statements, 74, 93–94 and break statement, 94 Sybase, 1274, 1278 Synchronization using locks, 989–991 Synchronization wrapper, 1003 Synchronized block, 988 Synchronized collections, 1002–1003 defined, 1002 synchronized keyword, 987–988, 994, 1003, 1311 synchronizing statements, 988–989 synchronized methods, 988 synchronized modifier, 1317 Syntax errors, 53 Syntax rules, 12 System errors, 438 System.currentTimeMillis(), 37 System.out.println, 11–12 T Table model events, 1247–1250 Table renderers and editors, 1242 custom, 1245–1247 MyTableModel.java, 1243–1244 predefined, 1242 TableCellRendererEditorDemo.java, 1244 TableCellEditor interface, 1226 TableCellRenderer interface, 1226, 1245 TableCellRendererEditorDemo.java, 1244 tableChanged method, TableModelListener, 1250 TableColumn, as supporting class, 1226 TableColumn class, 1226, 1233–1234 properties/constructors/methods, 1233–1234 TableColumnModel interface, 1233 TestTableColumnModel.java, 1234–1235 TableEventsDemo.java, 1247–1250 tableHeader property, 1235 TableModel interface, , 1231–1233 and table data management, 1233 TableModelEvents, 1231 TablePropertiesDemo.java, 1229–1231 Tables, joining, 1286 Tables, relational database systems, 1275–1276 Tag, defined, 616 Tag name, defined, 616 Tapes, Target node, 920, 923 Tasks: creating, 972–973 defined, 972 TaskThreadDemo.java, 974–975 run() method, 974 start() method, 974 TaskThreadDemo.java, 974–975 run() method, 974 start() method, 974 Taxes, computing (problem), 85–88 TCP (Transmission Control Protocol), 1018 Ternary operator, 95 TestArrayAndLinkedList.java, 741–742 TestArrayList.java, 390–392 TestBFS.java, 917–918 TestBinaryTreeDelete.java, 874–875 TestBinaryTree.java, 869–870 TestBinaryTreeWithIterator.java, 880–881 TestBreak.java, 135–136 TestButtonIcons.java, 573–576 TestCalendar.java, 463–465 TestCallableStatement.java, 1299 TestCenterMessage.java, 511-512 TestCircle1.java, 266–267 TestCircle2.java, 279–280 TestCircle3.java, 285–286 TestColorDialog.java, 1174 TestContinue.java, 136 TestCourse.java, 356 TestCourseWithActionEvent.java, 1100–1101 TestCourseWithEnrollmentEvent.java, 1104–1105 TestDatabaseMetaData.java, 1301 TestDFS.java, 914–915 TestDoWhile.java, 125–126 TestEdible.java, 465–466 TestFileClass.java, 324–325 TestFrame.java, 276 TestGeometricObject.java, 461–462 TestHashSet.java, 732 TestImageIcon.java, 423 TestIntegerMatrix.java, 722–723 TestLinkedHashSet.java, 734–735 TestList.java, 829–830 TestLoanClass.java, 348–349 www.elsolucionario.net TestMap.java, 754 TestMax.java, 158–160 TestMethodOverloading.java, 169–170 TestMethodsInCollection.java, 732–734 TestMinimumSpanningTree.java, 953–954 TestObjectInputStream.java, 663–664 TestObjectOutputStream.java, 663 TestObjectStreamForArray.java, 665–666 TestPaintComponent.java, 500 TestPanels.java, 417–419 TestPassArray.java, 211–212 TestPassByValue.java, 163-165 TestPassObject.java, 286–287 TestPriorityQueue.java, 847 TestQueue.java, 749 TestRandomAccessFile.java, 667–668 TestRandomCharacter.java, 176 TestRationalMatrix.java, 723 TestResultSetMetaData.java, 1303 TestShortestPath.java, 960–961 TestStackOfIntegers.java, 358–359 TestStackQueue.java, 845 TestSum.java, 130–131 TestSwingCommonFeatures.java, 421–422 TestTableColumnModel.java, 1234–1235 TestTable.java, 1228 TestTableModel.java, 1231–1232 TestTableSortFilter.java, 1236–1237 TestTreeModel.java, 1255–1256 TestTreeSet.java, 735–736 TestTreeSetWithComparator.java, 738 TestVoidMethod.java, 160–162 TestWeightedGraph.java, 947–948 TestWindowEvent.java, 549–551 Text areas, 586–589 DescriptionPanel.java, 587–589 TextAreaDemo.java, 589 Text fields, 584–586 defined, 584 TextFieldDemo.java, 585–586 Text I/O, binary I/O vs., 650–652 Text I/O classes, 650 TextAreaDemo class, 587–588 TextEditor.java, 1177-1181 open method, 1180 save method, 1181 Think before coding, use of term, 118 this keyword, 346 this(arg-list) statement, 347 Thread class, 975–978 class diagram, 975 extending, 976 join method, 977 methods, 975 resume() method, 976 sleep method, 976–977 stop() method, 976 suspend() method, 976 yield() method, 976 Thread cooperation, 991–995 ever-waiting, 994 Java’s built-in monitor, 994–995 ThreadCooperation.java, 992–994 Thread-safe class, 987 Thread states, 1002 Thread synchronization, 985–989 AccountWithoutSync.java, 985–987 Account class, 986–987 AddAPennyTask class, 986 and data inconsistency, 987 isTerminated() method, 986 Threads: Blocked state, 1002 concurrent, 975 cooperation among, 991–994 creating, 972–973 defined, 972 interrupt() method, 1002 isAlive() method, 1002 New state, 1002 Ready state, 1002 Running state, 1002 separating tasks from, 975 starting, 973 Thread class, 975–978 class diagram, 975 extending, 976 join method, 977 methods, 975 resume() method, 976 sleep method, 976–977 stop() method, 976 suspend() method, 976 yield() method, 976 time sharing, 972 timers vs., 979 Throwable class, 438, 442 Throwing exceptions, 440 throws Exception, 326–327 TicTacToe game (case study), 628–632 TicTacToe.java, 629–632 TicTacToeClient class, 1043 TicTacToeClient.java, 1047–1052 TicTacToeConstants class, 1042 TicTacToeConstants interface, 1052 TicTacToeConstants.java, 1043 TicTacToeServer class, 1043 TicTacToeServer.java, 1043–1047 Time sharing, 972 Timer class, animation using, 557–560 AnimationDemo.java, 558–559 ClockAnimation.java, 559–560 Timers, threads vs., 979 TimeZone class, 1060–1061 TitledBorder class, 1138, 1144 toCharArray method, 309 Toggle button, 578 Token-reading methods, 327 toLowerCase method, Character class, 314-315 Tool tip, 420–421, 577 Toolbars, 1158 Top-down design, 177–179 toString method: Date class, 274–275 GeometricObject class, 382–383 MyStack.java, 393–395 TotalArea.java, 288–289 toUpperCase method, Character class, 307 Tower of Hanoi (problem), 688–691 analyzing, 771 defined, 688 TowersOfHanoi.java, 690–691 transient keyword, 664 transient modifier, 1317 Transmission Control Protocol (TCP), 1018 Traversals: graphs, 911–912 trees, 861–863, 875 Tree class, 885, 911–912, 914, 916, 951–954, 960 class diagram, 912 Tree events, 1267 Index 1341 Tree interface, 862, 911 TreeMap, 751–752, 754–756 Tree node rendering and editing, 1265–1267 Tree sets, 735–737, 738 Tree traversal, 861–863 breadth-first traversal, 861, 863 depth-first traversal, 861 inorder traversal, 861, 869, 875 postorder traversal, 861–862, 866, 869–870 preorder traversal, 861, 863, 866, 869–870, 875 Tree visualization, 876–879 DisplayBinaryTree.java, 876 TreeCellRenderer interface, 1265 treeCollapsed, 1267 TreeExpansionEvent, 1267 TreeExpansionListener, 1267 treeExtended, 1267 Tree.java, 863–864 TreeMap class, 752 TreeModel class, 1251 TreeModel interface, 1254–1256 TreeNode class, 1251, 1255–1256, 1257–1258 TreeNodeDemo.java, 1256–1259 TreePath class, 1251, 1259–1262 Trees: binary search trees, 858–870 deleting elements in, 870-876 defined, 858 iterators, 879–881 TreeSelectionEvent, 1267 TreeSelectionListener interface, 1267 TreeSelectionModel interface, 1251, 1259–1260 TreeSet class, 730, 735–738, 898 Trigonometric methods, Math class, 172 Truncation, 41 try-throw-catch block, template for, 434 Tuples, 1277 distinct, displaying, 1285 sorted, displaying, 1285 Two-dimensional arrays, 236–248 closest pair, finding (problem), 242–244 creating, 236–237 declaring variables of, 236–237 multiple-choice test, grading (problem), 241–242 obtaining the lengths of, 237 processing, 238–240 ragged array, 238 Sudoku (problem), 244–248 Type casting, 31, 41 defined, 41 explicit casting, 41–42 implicit casting, 47, 387 and loss of precision, 49 syntax for, 41 Type erasure, 716 U UDP (User Datagram Protocol), 1018 UML (Unified Modeling Language): class diagram, 265 notation, 265 Unary operator, 35 Unbounded wildcard, 715 Unboxing, 481 Unchecked exceptions, 439 Underflow, 33 Unicode, 45, 1058 supplementary, 45, 651 www.elsolucionario.net 1342 Index Unix epoch, 43 UnmodifiableCollection class, 757 UnmodifiableList class, 757 UnmodifiableMap class, 757 UnmodifiableSet class, 757 UnmodifiableSortedMap class, 757 UnmodifiableSortedSet class, 757 UnsupportedOperationException, 730 Unweighted edges, 893 UnweightedGraph class, 898–900, 902, 908–909, 940, 942 updateDate() method, 1204 updateString method, 1084 URL class, 632–633 DisplayImagePlayAudio.java, 634 DisplayImageWithURL.java, 633 USB flash drives, UseGuessDateClass.java, 360–361 User actions, source object and event type, 534 User Datagram Protocol (UDP), 1018 User interfaces: buttons, 572–578 AbstractButton class, 572–573 alignments, 574 ButtonDemo.java, 576–578 defined, 572 icons, 572–574 pressed icons, 572–573 rollover icons, 572–573 TestButtonIcons.java, 573–574 text positions, 575 using, 575–578 check boxes, 578–581 CheckBoxDemo.java, 579–581 toggle button, 578 combo boxes, 590–593 ComboBoxDemo.java, 591–593 defined, 590, 1216 JComboBox class, 590 creating, 572–606 labels, 583–584 lists, 593–596 multiple windows, creating, 602–606 radio buttons, 581–583 defined, 581 RadioButtonDemo.java, 582–583 scroll bars, 596–599 JScrollBar class, 596–597 ScrollBarDemo.java, 598–599 sliders, 599–602 JSlider class, 599, 602 SliderDemo.java, 600–602 text areas, 586–589 DescriptionPanel.java, 587–589 TextAreaDemo class, 586 TextAreaDemo.java, 585–586 text fields, 584–586 defined, 584 TextFieldDemo.java, 585–586 UTF-8 format, 657 V validate method, 1223-1224 Value-returning method, 157–158, 317 valueChanged method: ListSelectionListener, 1250 TreeSelectionListener interface, 1267 valueIsAdjusting method, 1207 valueOf method, String class, 309, 478 values() method, Map interface, 752 VarArgsDemo.java, 215–216 Variable-length argument lists, 215–216 Variables, 27 class’s, 345 control, 127 declarations, 30 delaring/initializing in one step, 30 indexed, 198, 200 instance, 271, 278, 280–281, 346 local, 171, 272, 345, 396, 697 naming, 30, 52 scope of, 171, 345–346 static, 278–281, 345–346, 665 used as expressions, 31 Vector class, 746–748 methods, 747 Vertical alignment, 573–574, 584 Vertical text position, 575 vertices data field, 910 vgap property: BorderLayout manager, 417, 1114 FlowLayout manager, 417 GridLayout manager, 417 ViewRemoteFile.java, 1038–1039 Views, 1188 VirtualMachineError class, 437–438 Visibility, changing of, 396 Visibility modifiers, 282–283, 395 visible property, JFrame, 422 visibleRowCount method, 1206–1207 Visual Basic, Visualization, trees, 876–879 void keyword, 270 Void method, 157 void method, 160-162 invoking, 161 return in, 161–162 TestVoidMethod.java, 160–162 vspace attribute, 617 W wait() method, 991, 994, 1002 Weak is-a relationship, 475 Web servers, retrieving files from, 1036–1039 java.net.URL class, 1037 MalformedURLException, 1037 openStream() method, 1037 ViewRemoteFile.java, 1038–1039 WebBrowser.java, 1040–1041 Weighted edges, representing, 940 edge array, 940 priority adjacency lists, 941–942 weighted adjacency matrices, 941 WeightedEdge.java, 941–942 Weighted graphs: applications, 940–965 representing, 940–942 Weighted nine tail problem (case study), 962–964 WeightedNineTailMode class, 964 WeightedNineTailModel.java, 963–964 WeightedEdge.java, 941–942 WeightedGraph class, 898, 942–949 TestWeightedGraph.java, 947–949 WeightedGraph.java, 943–947 WelcomeInMessageDialogBox.java, 16–17 Welcome.java, 11–13 while loop, 116–124 Whitespace, 51 Whitespace character, 27, 51 Widening a type, 41 Wildcard generic types, 714–716 type, 715 bounded wildcard, 715 lower-bound wildcard, 715 unbounded wildcard, 715 WildCardDemo1.java, 714–715 WildCardDemo2.java, 715–716 WildCardDemo3.java, 716 Wildcard import, 17 WildCardDemo3.java, 716 Window events, handling, 549–551 windowActivated method, 551 WindowAdapter class, 551 windowClosed method, 551 windowClosing method, 551 windowDeactivated method, 551 windowDeiconified method, 551 WindowEvent, 535, 537, 549 windowIconified method, 551 WindowListener interface, 551 windowOpened method, 551 Windows Calculator, 1320 World Wide Web (WWW), defined, WorldClockApp.java, 1066 WorldClockControl.java, 1064–1066 WorldClock.java, 1064 Worst-case input, 766 Wrapper class, 476–478 naming convention, 477 and no-arg constructors, 478 Wrapper class types, automatic conversion between primitive types and, 481 Wrapper objects, constructing, 478 Write-only property, 1094 Write-only streams, 666 writeBytes(String s) method, 656 writeChar(char c) method, 656 writeChars(String s) method, 656 WriteData.java, 325–326 writeObject method, ObjectOutputStream class, 1033, 1036 writeUTF(String s) method, 656–657 X xCoordinate, Component class, 512 Y yCoordinate, Component class, 512 Z Zero, division by, and runtime errors, 54 based array indices, 200 www.elsolucionario.net Video Notes Locations of Video Notes http://www.pearsonhighered.com/liang Chapter Introduction to Computers, Programs, and Java First Java Program Compile and Run a Java Program Brief Eclipse Tutorial Chapter Chapter Elementary Programming Obtain Input Program Computations Use Operators / and % 26 43 37 Compute BMI 66 Selections Program Addition Quiz Program Subtraction Quiz Multiple Alternative if Statements Sort Three Integers Chapter Chapter Chapter Chapter Chapter 10 107 Guess a Number Multiple Subtraction Quiz Minimize Numeric Errors 118 121 130 Display Loan Schedule 150 Methods Compute p Chapter 73 82 85 Loops Define and Invoke Max Method Use Void Method Modularize Code Chapter 11 15 14 158 160 165 191 Single-Dimensional Arrays Random Shuffling Lotto Numbers Selection Sort 202 204 219 Coupon Collector’s Problem 232 Multidimensional Arrays Find the Row with the Largest Sum Grade Multiple-Choice Test Sudoku 239 241 244 Multiply Two Matrices 253 Objects and Classes Use Classes Static versus Instance Data Field Encapsulation 277 278 283 The Fan Class 297 Strings and Text I/O Check Palindrome Command-Line Argument Write and Read Data 310 321 000 Decimal to Binary Number 000 Thinking in Objects The Loan Class The BMI Class The StackOfInterger Class 347 351 357 Design and Implement MyPoint Class 367 www.elsolucionario.net Chapter 11 Inheritance and Polymorphism Geometric Class Hierarchy Polymorphism and Dynamic Binding The ArrayList Class The MyStack Class Chapter 12 Chapter 13 Chapter 15 GUI Basics 411 417 420 Display a Checkerboard 429 Exception Handling Chapter 17 Chapter 18 Chapter 19 Chapter 20 432 448 456 Abstract Classes and Interfaces Abstract GeometricObject Class Calendar and GregorianCalendar Classes The Concept of Interface 458 462 465 Redesign the Rectangle Class 492 Graphics The FigurePanel Class The MessagePanel Class The StillClock Class Plot a Sine Function Chapter 16 393 Use FlowLayout Panels as Subcontainers Swing Common Properties Exception Handling Advantage Create Custom Exception Classes The HexFormatException Class Chapter 14 374 386 390 502 512 516 529 Event-Driven Programming Create Source and Listener Anonymous Inner Class Move Message with the Mouse Animate a Clock 540 543 553 559 Animate a Rising Flag 564 Creating User Interfaces Use Buttons Use Check Boxes Use Radio Buttons Use Labels and Text Fields 575 578 581 584 Use Text Areas 610 Applets and Multimedia First Applet Run Applets Standalone TicTacToe Audio and Image 614 618 628 635 Control a Group of Clocks 642 Binary I/O Copy File Object I/O 660 662 Split a Large File 673 Recursion Binary Search Directory Size Fractal and the Sierpinski Triangle 686 687 692 Search a String in a Directory 704 ... three editions: Java Standard Edition (Java SE), Java Enterprise Edition (Java EE), and Java Micro Edition (Java ME) Java SE can be used to develop client-side standalone applications or applets Java. .. designed to prepare students to become proficient Java programmers A brief version (Introduction to Java Programming, Brief Version, Eighth Edition) is available for a first course on programming, ... This Edition? This edition substantially improves Introduction to Java Programming, Seventh Edition The major improvements are as follows: ■ This edition is completely revised in every detail to