Stuck in your homework and missing deadline?

Get Urgent Writing Help In Your Essays, Assignments, Homeworks, Dissertation, Thesis Or Coursework & Achieve A+ Grades.

Privacy Guaranteed - 100% Plagiarism Free Writing - Free Turnitin Report - Professional And Experienced Writers - 24/7 Online Support

The method listfiles filenamefilter is ambiguous for the type file

20/10/2021 Client: muhammad11 Deadline: 2 Day

Java Programming: A Comprehensive Introduction is designed for an introductory programming course using Java. This text takes a logical approach to the presentation of core topics, moving step by step from the basics to more advanced material, with objects being introduced at the appropriate time. The book is divided into three parts:

Part One covers the elements of the Java language and the fundamentals of programming. An introduction to object-oriented design is also included.

Part Two introduces GUI (Graphical User Interface) programming using Swing.

Part Three explores key aspects of Java’s API (Application Programming Interface) library, including the Collections Framework and the concurrency API.

Hallmark Features Presents topics in a clear and logical order. This “straight ahead” approach introduces each new feature in a cohesive, logical sequence.

Introduces objects after the basics. Objects are introduced in Chapter 4, after key elements of the language are covered.

Separates the teaching of the GUI from the teaching of the language elements. The instructor has fl exibility in choosing when to introduce GUI programming.

Includes coverage of Java 7 (JDK 7). Students can learn a modern version of the language.

Provides numerous examples and exercises. Examples given throughout make the purpose and use of program elements clear, while the exercises test the student’s grasp of material. Answers to selected exercises are given in the back of the book.

Pedagogical Highlights Progress Checks reinforce core concepts and provide immediate feedback to the student that key concepts have been learned.

Ask the Expert sections supply additional information or interesting commentary related to the topic at hand.

Try This elements provide step-by-step examples that show core programming topics in action.

Learn more about Java Programming at the book’s web site: www.mhhe.com/schildt1e


Herbert Schildt | Dale Skrien

Java Programming A Comprehensive Introduction

College Programming Series

Java P rogram

m ing


o m p re h e n sive

In tro

d u c tio

n S childt S krien




#1174731 11/18/11 C Y







Java Programming

sch2207X_fm_p0i-xxxvi.indd 1 23/12/11 4:29 PM

sch2207X_fm_p0i-xxxvi.indd 2 23/12/11 4:29 PM

Java Programming A Comprehensive Introduction

Herbert Schildt

Dale Skrien Colby College

sch2207X_fm_p0i-xxxvi.indd 3 23/12/11 4:29 PM


Published by McGraw-Hill, a business unit of The McGraw-Hill Companies, Inc., 1221 Avenue of the Americas, New York, NY 10020. Copyright © 2013 by The McGraw-Hill Companies, Inc. All rights reserved. Printed in the United States of America. No part of this publication may be reproduced or distributed in any form or by any means, or stored in a database or retrieval system, without the prior written consent of The McGraw-Hill Companies, Inc., including, but not limited to, in any network or other electronic storage or transmission, or broadcast for distance learning.

Oracle and Java are registered trademarks of Oracle Corporation and/or its affiliates. All other trademarks are the property of their respective owners, and McGraw-Hill makes no claim of ownership by the mention of products that contain these marks.

Some ancillaries, including electronic and print components, may not be available to customers outside the United States.

This book is printed on acid-free paper.

1 2 3 4 5 6 7 8 9 0 DOC/DOC 1 0 9 8 7 6 5 4 3 2 ISBN: 978-0-07-802207-4 MHID 0-07-802207-X

Vice President & Editor-in-Chief: Marty Lange Vice President & Director Specialized Publishing: Janice M. Roerig-Blong Editorial Director: Michael Lange Global Publisher: Raghothaman Srinivasan Senior Marketing Manager: Curt Reynolds Developmental Editor: Robin A. Reed Senior Project Manager: Lisa A. Bruflodt Buyer: Sandy Ludovissy Design Coordinator: Brenda A. Rolwes Media Project Manager: Prashanthi Nadipalli Cover Design by Studio Montage, St. Louis, Missouri Cover Image: © Iconotec/Alamy Compositor: RPK Editorial Services Typeface: 10.5/12 Times Roman Printer: R. R. Donnelley Crawfordsville, IN

Library of Congress Cataloging-in-Publication Data Schildt, Herbert. Java programming : a comprehensive introduction / Herbert Schildt, Dale Skrien. -- 1st ed. p. cm. Includes bibliographical references and index. ISBN 978-0-07-802207-4 1. Java (Computer program language) I. Skrien, Dale John. II. Title. QA76.73.J38S332 2013 005.13’3–dc23 2011047187 www.mhhe.com

sch2207X_fm_p0i-xxxvi.indd 4 23/12/11 4:29 PM


PART I ThE JAvA LANguAgE 1 ChAPTER 1 Java Programming Fundamentals 3 ChAPTER 2 Introducing Data Types and Operators 43 ChAPTER 3 Program Control Statements 77 ChAPTER 4 Introducing Classes, Objects, and Methods 119 ChAPTER 5 More Data Types and Operators 155 ChAPTER 6 A Closer Look at Methods and Classes 205 ChAPTER 7 Inheritance 257 ChAPTER 8 Interfaces 303 ChAPTER 9 Packages 327 ChAPTER 10 Exception handling 347 ChAPTER 11 using I/O 383 ChAPTER 12 Multithreaded Programming 435 ChPATER 13 Enumerations, Autoboxing, and Annotations 475 ChAPTER 14 generics 505 ChAPTER 15 Applets and the Remaining Java Keywords 549 ChAPTER 16 Introduction to Object-Oriented Design 569


ChAPTER 17 Swing Fundamentals 619 ChAPTER 18 Exploring Swing Controls 659 ChAPTER 19 Working with Menus 711 ChAPTER 20 Dialogs 737 ChAPTER 21 Threading, Applets, and Painting 779

PART III ExPLORINg ThE JAvA API LIBRARy 811 ChAPTER 22 String handling 813 ChAPTER 23 Exploring java.lang 843 ChAPTER 24 Exploring java.util 879 ChAPTER 25 using the Data Structures in the Collections Framework 929 ChAPTER 26 Networking with java.net 985 ChAPTER 27 The Concurrency utilities 1009

APPENDIx A using Java’s Documentation Comments 1059 APPENDIx B An Introduction to Regular Expressions 1067 APPENDIx C Answers to Selected Exercises 1075

INDEx 1129

sch2207X_fm_p0i-xxxvi.indd 5 23/12/11 4:29 PM

sch2207X_fm_p0i-xxxvi.indd 6 23/12/11 4:29 PM




ChAPTER 1 Java Programming Fundamentals 3 Computing Basics 4 The Hardware Components of a Computer 4 Bits, Bytes, and Binary 5 The Operating System 6

The Program 7

Programming Languages 8 The Java Language 9 The Origins of Java 9 Java’s Contribution to the Internet 11 Java Applets 11 Security 11 Portability 12 Java’s Solution: The Bytecode 12 The Evolution of Java 13

The Key Attributes of Object-Oriented Programming 14

Encapsulation 15 Polymorphism 16 Inheritance 16

The Java Development Kit 17 A First Simple Program 18 Entering the Program 18 Compiling the Program 19 Running the Program 19 The First Sample Program Line by Line 19

Handling Syntax Errors 22 A Second Simple Program 23 Another Data Type 25

sch2207X_fm_p0i-xxxvi.indd 7 23/12/11 4:29 PM

viii contents

Two Control Statements 28 The if Statement 28 The for Loop 30

Create Blocks of Code 32 Semicolons and Positioning 33 Indentation Practices 34 Indentation Practices 34 The Java Keywords 36 Identifiers in Java 37 The Java Class Libraries 38 Exercises 39

ChAPTER 2 Introducing Data Types and Operators 43 Why Data Types are Important 43 Java’s Primitive Types 44 Integers 44 Floating-Point Types 46 Characters 47 The Boolean Type 48

Literals 50 Hexadecimal, Octal, and Binary Literals 51 Character Escape Sequences 52 String Literals 52

A Closer Look at Variables 53 Initializing a Variable 54 Dynamic Initialization 54

The Scope and Lifetime of Variables 55 Operators 58 Arithmetic Operators 58 Increment and Decrement 59

Relational and Logical Operators 60 Short-Circuit Logical Operators 62 The Assignment Operator 64 Shorthand Assignments 64 Type Conversion in Assignments 65 Using a Cast 66 Operator Precedence 68 Expressions 70 Type Conversion in Expressions 70 Spacing and Parentheses 72

Exercises 73

sch2207X_fm_p0i-xxxvi.indd 8 23/12/11 4:29 PM


ChAPTER 3 Program Control Statements 77 Input Characters from the Keyboard 78 The i f Statement 79 Nested i f s 81 The i f -e lse - i f Ladder 82 The switch Statement 83 Nested switch Statements 86 The for Loop 90 Some Variations on the for Loop 91 Missing Pieces 92 The Infinite Loop 93 Loops with No Body 93

Declaring Loop Control Variables Inside the for Statement 94 The Enhanced for Loop 95 The while Loop 95 The do-while Loop 97 Use break to Exit a Loop 102 Use break as a Form of goto 104 Use continue 108 Nested Loops 113 Exercises 114

ChAPTER 4 Introducing Classes, Objects, and Methods 119 Class Fundamentals 119 The General Form of a Class 120 Defining a Class 121

How Objects are Created 124 Reference Variables and Assignment 124 Methods 126 Adding a Method to the Vehicle Class 126

Returning from a Method 128 Returning a Value 129 Using Parameters 131 Adding a Parameterized Method to Vehicle 133

Constructors 141 Parameterized Constructors 142 Adding a Constructor to the Vehicle Class 143

The new Operator Revisited 145

sch2207X_fm_p0i-xxxvi.indd 9 23/12/11 4:29 PM

x contents

Garbage Collection and Finalizers 145 The finalize( ) Method 146

The this Keyword 149 Exercises 151

ChAPTER 5 More Data Types and Operators 155 Arrays 155 One-Dimensional Arrays 156

Multidimensional Arrays 161 Two-Dimensional Arrays 161 Irregular Arrays 163 Arrays of Three or More Dimensions 164 Initializing Multidimensional Arrays 164

Alternative Array Declaration Syntax 166 Assigning Array References 166 Using the length Member 168 The For-Each Style for Loop 176 Iterating Over Multidimensional Arrays 179 Applying the Enhanced for 180

Strings 181 Constructing Strings 182 Operating on Strings 182 Arrays of Strings 184 Strings are Immutable 185 Using a String to Control a switch Statement 186

Using Command-Line Arguments 187 The Bitwise Operators 189 The Bitwise AND, OR, XOR, and NOT Operators 189 The Shift Operators 194 Bitwise Shorthand Assignments 196

The ? Operator 200 Exercises 201

ChAPTER 6 A Closer Look at Methods and Classes 205 Controlling Access to Class Members 205 Java’s Access Modifiers 206

Pass Objects to Methods 211 How Arguments are Passed 212 Returning Objects 215 Method Overloading 217

sch2207X_fm_p0i-xxxvi.indd 10 23/12/11 4:29 PM


Overloading Constructors 222 Recursion 228 Understanding stat ic 232 Static Variables 233 Static Methods 235 Static Blocks 236

Introducing Nested and Inner Classes 240 Varargs: Variable-Length Arguments 244 Varargs Basics 245 Overloading Varargs Methods 247 Varargs and Ambiguity 249

Exercises 250

ChAPTER 7 Inheritance 257 Inheritance Basics 257 Member Access and Inheritance 260 Constructors and Inheritance 263 Using super to Call Superclass

Constructors 265 Using super to Access Superclass Members 269 Creating a Multilevel Hierarchy 273 When are Constructors Executed? 276 Superclass References

and Subclass Objects 277 Method Overriding 282 Overridden Methods Support

Polymorphism 285 Why Overridden Methods? 287 Applying Method Overriding to TwoDShape 287

Using Abstract Classes 291 Using f inal 296 final Prevents Overriding 296 final Prevents Inheritance 296 Using final with Data Members 297

The Object Class 298 Exercises 299

ChAPTER 8 Interfaces 303 Interface Fundamentals 303 Creating an Interface 304

sch2207X_fm_p0i-xxxvi.indd 11 23/12/11 4:29 PM

xii contents

Implementing an Interface 305 Using Interface References 309 Implementing Multiple Interfaces 311 Constants in Interfaces 319 Interfaces can be Extended 321 Nested Interfaces 322 Final Thoughts on Interfaces 323 Exercises 323

ChAPTER 9 Packages 327 Package Fundamentals 327 Defining a Package 328 Finding Packages and CLASSPATH 329 A Short Package Example 329

Packages and Member Access 331 A Package Access Example 332 Understanding Protected Members 334

Importing Packages 336 Importing Java’s Standard Packages 337

Static Import 341 Exercises 344

ChAPTER 10 Exception handling 347 The Exception Hierarchy 348

Exception Handling Fundamentals 348 Using try and catch 349 A Simple Exception Example 349

The Consequences of an Uncaught Exception 352

Exceptions Enable You to Handle Errors Gracefully 353

Using Multiple catch Clauses 355

Catching Subclass Exceptions 356

try Blocks can be Nested 357

Throwing an Exception 359 Rethrowing an Exception 360

sch2207X_fm_p0i-xxxvi.indd 12 23/12/11 4:29 PM


A Closer Look at throwable 361

Using f inal ly 363

Using throws 365

Java’s Built-in Exceptions 366

New Exception Features Added by JDK 7 369

Creating Exception Subclasses 370

Exercises 377

ChAPTER 11 using I/O 383 Java’s I/O Is Built on Streams 384 Byte Streams and Character Streams 384 The Byte Stream Classes 384 The Character Stream Classes 385 The Predefined Streams 386 Using the Byte Streams 387 Reading Console Input 388 Writing Console Output 389

Reading and Writing Files Using Byte Streams 390

Inputting from a File 391 Writing to a File 394

Automatically Closing a File 396 Reading and Writing Binary Data 399 Random-Access Files 404 Using Java’s Character-Based Streams 407 Console Input Using Character Streams 407 Console Output Using Character Streams 411

File I/O Using Character Streams 412 Using a FileWriter 412 Using a FileReader 413 File 415 Obtaining a File’s Properties 415 Obtaining a Directory Listing 417 Using FilenameFilter 418 The listFiles( ) Alternative 419 Various File Utility Methods 419

Using Java’s Type Wrappers to Convert Numeric Strings 421

Exercises 430

sch2207X_fm_p0i-xxxvi.indd 13 23/12/11 4:29 PM

xiv contents

ChAPTER 12 Multithreaded Programming 435 Multithreading Fundamentals 435 The Thread Class and Runnable Interface 436 Creating a Thread 437 Some Simple Improvements 440

Creating Multiple Threads 445 Determining When a Thread Ends 447 Thread Priorities 450 Synchronization 451 Using Synchronized Methods 452 The Synchronized Statement 455 Thread Communication Using notify( ) ,

wait( ) , and notifyA l l( ) 458 An Example That Uses wait( ) and notify( ) 458

Suspending, Resuming, and Stopping Threads 464

Exercises 469

ChAPTER 13 Enumerations, Autoboxing, and Annotations 475 Enumerations 475 Enumeration Fundamentals 476

Java Enumerations are Class Types 479

The values( ) and valueO f( ) Methods 479

Constructors, Methods, Instance Variables, and Enumerations 480 Two Important Restrictions 482

Enumerations Inherit Enum 482 Autoboxing 490 Type Wrappers and Boxing 490 Autoboxing Fundamentals 492 Autoboxing and Methods 493 Autoboxing/Unboxing Occurs in Expressions 494 A Word of Warning 496

Annotations (Metadata) 497 Creating and Using an Annotation 497 Built-in Annotations 498

Exercises 500

ChAPTER 14 generics 505 Generics Fundamentals 506 A Simple Generics Example 506

sch2207X_fm_p0i-xxxvi.indd 14 23/12/11 4:29 PM


Generics Work Only with Objects 510 Generic Types Differ Based on Their Type Arguments 510 A Generic Class with Two Type Parameters 510 The General Form of a Generic Class 512

Bounded Types 513 Using Wildcard Arguments 516 Bounded Wildcards 519 Generic Methods 522 Generic Constructors 524 Generic Class Hierarchies 525 Generic Interfaces 528 Raw Types and Legacy Code 535 Type Inference with the Diamond Operator 538 Erasure 540 Ambiguity Errors 540 Some Generic Restrictions 541 Type Parameters Can’t be Instantiated 541 Restrictions on Static Members 542 Generic Array Restrictions 542 Generic Exception Restriction 543

Exercises 543

ChAPTER 15 Applets and the Remaining Java Keywords 549 Applet Basics 549 A Complete Applet Skeleton 553 Applet Initialization and Termination 554 A Key Aspect of an Applet’s Architecture 554 Requesting Repainting 555 Using the Status Window 560 Passing Parameters to Applets 561 The Remaining Java Keywords 563 The volatile Modifier 564 The transient Modifier 564 instanceof 564 strictfp 564 assert 565 Native Methods 565

Exercises 567

ChAPTER 16 Introduction to Object-Oriented Design 569 Elegant Software and Why It Matters 570 Properties of Elegant Software 571

sch2207X_fm_p0i-xxxvi.indd 15 23/12/11 4:29 PM

xvi contents

Elegant Methods 573 Naming Conventions 573 Method Cohesion 574 Well-formed Objects 576 Internal Documentation 577 External Documentation 578

Elegant Classes 581 Class Cohesion and the Expert Pattern 581 Avoiding Duplication 583 Complete Interface 585 Design with Change in Mind 586 Demeter’s Law 589

Inheritance versus Delegation 591 UML Class Diagrams 591 Code Reuse Perspective 594 The Is-a Relationship 594 Similar Behavior 597 Polymorphism 600 Costs of Inheritance 600

Design Patterns 603 Adapter Pattern 604 Observer Pattern 607

Exercises 612


ChAPTER 17 Swing Fundamentals 619 The Origins and Design Philosophy

of Swing 620

Components and Containers 622 Components 622 Containers 623 The Top-Level Container Panes 623

Layout Managers 624 A First Simple Swing Program 625 The First Swing Example Line by Line 626

Event Handling 631 Events 631 Event Sources 631 Event Listeners 632 Event Classes and Listener Interfaces 632 Adapter Classes 632

sch2207X_fm_p0i-xxxvi.indd 16 23/12/11 4:29 PM


Using a Push Button 635 Introducing JTextF ield 643 Use Anonymous Inner Classes

to Handle Events 655 Exercises 656

ChAPTER 18 Exploring Swing Controls 659 JLabel and ImageIcon 660 The Swing Buttons 663 Handling Action Events 664 Handling Item Events 664 JButton 665 JToggleButton 668 Check Boxes 670 Radio Buttons 672

JTextF ield 675 JScrollPane 685 JL i s t 692 JComboBox 696 Trees 699 JTable 703 A Brief Word about Models 706 Exercises 707

Homework is Completed By:

Writer Writer Name Amount Client Comments & Rating
Instant Homework Helper


Instant Homework Helper


She helped me in last minute in a very reasonable price. She is a lifesaver, I got A+ grade in my homework, I will surely hire her again for my next assignments, Thumbs Up!

Guarantee Your Academic Success!

Hire Professional Writers And Get Best Homework Writing Services In Any Subject

6 writers have sent their proposals to do this homework:

Instant Homework Helper
Engineering Mentor
Assignment Guru
Essay Writing Help
Academic Master
Quick N Quality
Writer Writer Name Offer Chat
Instant Homework Helper


Instant Homework Helper

I am a professional and experienced writer and I have written research reports, proposals, essays, thesis and dissertations on a variety of topics.

$36 Chat With Writer
Engineering Mentor


Engineering Mentor

I am an academic and research writer with having an MBA degree in business and finance. I have written many business reports on several topics and am well aware of all academic referencing styles.

$19 Chat With Writer
Assignment Guru


Assignment Guru

I am a professional and experienced writer and I have written research reports, proposals, essays, thesis and dissertations on a variety of topics.

$41 Chat With Writer
Essay Writing Help


Essay Writing Help

I am an experienced researcher here with master education. After reading your posting, I feel, you need an expert research writer to complete your project.Thank You

$20 Chat With Writer
Academic Master


Academic Master

I have read your project description carefully and you will get plagiarism free writing according to your requirements. Thank You

$26 Chat With Writer
Quick N Quality


Quick N Quality

As an experienced writer, I have extensive experience in business writing, report writing, business profile writing, writing business reports and business plans for my clients.

$25 Chat With Writer

Let our expert academic writers to help you in achieving a+ grades in your homework, assignment, quiz or exam.

Similar Homework Questions

Circuit breaker adjustable trip settings - First year of College Seminar D6 - Clinical hours tracking sheet - Biological aging theories - Cruelty civility and other weighty matters - What is an endorsement for scheduled medicines - Forensic Accounting - Discussion Post - Ucb case study summary - Japanese group 2 verbs list - Business Intelligence (ITS-531-M31) group assignment - Soc 120 week 5 discussion 2 - Gary fields comedy club kalamazoo - Chapter 9 vehicle transportation lesson 9.2 dealer's cost answer key - Cardiff harvard referencing guide - Ted talk color blind or color brave - Phd IT in Data analytics and analysis - 495 week 2 replies - Biotic and abiotic components of ecosystem - My speech project, need a professional touch with low similarity index - Bibliography for job satisfaction project - CJUS 420 RESESARCH PAPER DUE 10/11/2020 - Synapse vs neuromuscular junction - Need in 8 hours - Alice walker essay beauty - Ashworth college intro to computers assignment 8 - Ac dc power supply block diagram - Thinking through the past volume 1 - Ati basic concept template maternal newborn - Microbiology essay questions and answers pdf - Premier stateliner mount gambier to adelaide - When i learn d the astronomer summary - Sun moon and talia - Catch 22 age rating - J&l railroad case study solution - Edwin starr war lyrics meaning - Avocado supply and demand 2017 - Apply: Signature Assignment: Shareholder Analysis - Dead men's path summary - Vce exams navigator 2021 - 10 rainforest road edmonton - University of phoenix reference generator - Surveymonkey multiple choice with text box - Marketing analytics case study pdf - Please help/assignment redo - Social class essay introduction - Hans christian andersen interesting facts - Hersey blanchard situational leadership model - Criminal justice - K ae ea rt - Jackson county senior services is a nonprofit organization - States of matter quiz - 7 2 excel homework iv probability - Please respond if you can answer in 6-6.5 hours - Family life merit badge workbook - Problem Set 8 - Microstation pattern cell library - One – Group Assessment - Vsim skyler hansen answers - Big mac inside the mcdonald's empire worksheet - Net force practice worksheet - Physics magnetism practice problems - Calculating and reporting healthcare statistics answer key - Introduction to criminal justice mcgraw hill - Functional relationship aba graph - LD4 - Bronfenbrenner defined human development as: - Family office presentation ppt - Paul mitchell lemon sage energizing body lotion walgreens - It follows clamshell - Ubss moodle - 10 basic tasks of the strategy execution process - Chapter 5 the rise of river valley civilizations answers - Postcode for gisborne nz - Theme from the giver - Assignment 3 - Waeco reversing camera spares - Trinity summer hill fees - Safety Stock - Finding your worldview thinking christianly about the world - Jd edwards implementation guide - Food for thought worksheet answers - What is hoodooing in to kill a mockingbird - Matlab easy question - Fife voluntary action jobs - What does scroll lock do - Ford pinto case study summary - Mysql workbench composite primary key - How would you describe the schools of ethical thought - Project closure document sample - Course Project: Topic Selection - How many bit strings are there of length eight - Bdawk6paper - Analyze Current Security Products and Services - ECO 100 Economiocs week 9 Assignment 2 - Discussion - Soil Composition Lab - Frank geyer devil in the white city - Can i get my essay done online - King duncan character traits - 1000 words and three scholarly sources due ASAP