Statistics
3
Views
0
Downloads
0
Donations
Support
Share
Uploader

高宏飞

Shared on 2026-03-18

AuthorMalhotra S., Choudhary S.

No description

Tags
No tags
Language: 英文
File Format: PDF
File Size: 9.6 MB
Support Statistics
¥.00 · 0times
Text Preview (First 20 pages)
Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

(This page has no text content)
SAURABH CHOUDHARY Programming in Java Second Edition SACHIN MALHOTRA 1 Associate Professor IMS, Ghaziabad Formerly, Head IT Department IMS, Ghaziabad
3 Oxford University Press is a department of the University of Oxford. It furthers the University’s objective of excellence in research, scholarship, and education by publishing worldwide. Oxford is a registered trade mark of Oxford University Press in the UK and in certain other countries. Published in India by Oxford University Press YMCA Library Building, 1 Jai Singh Road, New Delhi 110001, India © Oxford University Press 2010, 2014 The moral rights of the author/s have been asserted. First Edition published in 2010 Second Edition published in 2014 All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by any means, without the prior permission in writing of Oxford University Press, or as expressly permitted by law, by licence, or under terms agreed with the appropriate reprographics rights organization. Enquiries concerning reproduction outside the scope of the above should be sent to the Rights Department, Oxford University Press, at the address above. You must not circulate this work in any other form and you must impose this same condition on any acquirer. ISBN-13: 978-0-19-809485-2 ISBN-10: 0-19-809485-X Typeset in Times New Roman by Sukuvisa Enterprises Printed in India by Yash Printographics, Noida 201301
Dedicated to Our Parents
Sachin Malhotra is currently Associate Professor in the IT department of IMS Ghaziabad. He has more than a decade long experience in mentoring students on developing Java applications as well as training practising professionals in the fi eld of Java. He has also designed and conducted various corporate trainings in Java and networking. Saurabh Choudhary is currently a practising IT consultant and corporate trainer. He has more than 12 years of experience in industry, academia, and consultancy. He has worked on positions of eminence at IMS Ghaziabad as Head of IT department and Dean Academics (University Campus). His areas of expertise include Java, Database Management System, and Information Systems. Testimonials From pervasive computing to communications industry, medical science to aeros pace, Java is gaining a foothold in every domain. Programming in Java has been written to arouse the interest even in a novice computer programmer to an expert, craving to sharpen his programming skills. Pankaj Verma | Senior Software Engineer | OSI Inc. It is defi nitely the best textbook on Java that I have run into. I highly recommend it. Sachin Dhama | Team Lead | Accenture Java is a very powerful language for developing enterprise applications. I am hopeful that this book will provide a basic building platform for Java programmers to enhance their knowledge. Awadhesh Kumar Katiyar | Technical Lead | HCL Technologies Ltd. Java enables users to develop applications on the Internet for servers, desktops computers, and small handheld devices. The future of computing is being infl uenced by the Internet, and Java promises to play a big part in it. This book is perfect for those who are seeking a clear understanding of Java. It should allow the readers to create codes that are a lot clearer and are far more effective than before. Saurabh Moondhra | Sr. Technical Consultant | SGT Inc This is the most interesting Java programming book for beginners; at the same time, it is equally good for intermediate readers as well. This should be your fi rst Java book if you are learning from scratch. Pankaj Jain | Senior Manager | Bank of America When you go through this book, you will gain confi dence after completing each chapter. The authors have written it in such a simple way covering each and every aspect of Java that anyone can learn how to develop effective codes. Rajeev Varshney | Lead Consultant | HCL NZ Ltd. About the Authors
Java was primarily designed as a platform-independent language for usage in small consumer electronic devices. It was derived from C++ but with a lot of difference. Java’s platform independence originally addressed the problem that applications for embedded devices must run on a wide variety of hardware. But since the Internet was emerging at the same time, Java soon got adopted as an Internet language because of its portable nature. Major Internet browsers such as Netscape Navigator and Microsoft Internet Explorer became Java-compatible, as it effectively addressed the concerns for security by providing a fi rewall between web applications and the computer. Eventually it became a standard programming language and is now being used for creating a variety of applications including standalone applications, web applications, enterprise-wide applications, and mobile games. It can therefore be inferred that since its inception, Java has emerged as the most important programming language. As the domain of Java is quite vast and a bit more complex than other programming languages such as C, C++, and Visual Basic, it is observed that students and novice programmers strive hard to comprehend its core concepts. Hence, a need for a book in this area, which is both concise and simple, is a necessity. About the Book The book encapsulates the concepts of the latest version of Java, i.e. Java 6, encompassing a comprehensive coverage of curriculum and industry expectations. It is useful for the students of undergraduate and postgraduate courses of computer science and engineering and information technology disciplines as well as for the instructors at various levels. The book provides a thorough understanding of the basic concepts of object-oriented programming principles and gradually moves on to the advanced concepts in Java. It includes numerous examples, line-by-line description of examples, fi gures, explanation of concepts, and key notes. Review questions and programming exercises are included as chapter-end exercises to assess the learning outcomes. Every topic in the book is supported by examples followed by an output and explanation. It also offers an appendix on general interview questions which provides students an insight into the current requirements of the industry and allows them to prepare accordingly. The main features of this book include the following:   an exhaustive coverage of Java features such as operators, classes, objects, inheritance, packages, and exception handling   comprehensive discussion on the latest features of Java such as enumerations, generics, logging API, console class, StringBuilder class, NetworkInterface class, and assertions   latest features combined with core concepts such as multithreading, applets, AWT, and swings   an introduction to the advanced concepts in Java such as servlets, RMI, and JDBC Preface to the First Edition
Appendix A: Lab Manual—Java Lab Exercises XIPreface to the First Edition xi ACKNOWLEDGEMENTS Several people have been instrumental throughout this tiring yet wonderful journey. First of all, we would like to express our sincere gratitude to our families without whose support, patience, and cooperation, this would not have been possible and we would not have been what we are today. We are very thankful to Dr R. K. Bharadwaj, Head of our institution, for his inspirational thoughts which inculcated urgency for writing this book. We are also thankful to our colleagues for their endless support and suggestions during the entire process of writing this book. Sachin Malhotra Saurabh Choudhary
Java is an easy-to-learn, versatile, robust, portable, and secure language with rich user interfaces. It has set up new benchmarks in the software development world ranging from desktop to web- based enterprise applications to mobile and embedded applications. Since its inception in 1995, it has come a long way by continuously evolving itself and in the process, changing the style of programming the world over. Java is not only found in laptops or data centres, it is also widely used in cell phones, SIM cards, smart cards, printers, routers and switches, set-top boxes, ATMs, and navigation systems, to name a few. According to Oracle, a staggering 1.1 billion desktops and 3 billion cell phones are based on Java. This second edition of Programming in Java confi rms to Java Standard Edition 7, the latest release since Oracle took over Sun Microsystems. It is signifi cant in the sense that the last update was six years back and this major release comes bundled with plenty of enhancements which were overdue. To list a few noticeable enhancements, Java 7 includes support for strings in switch and try-with-resources statements, improved multi-catch, binary numeric literals, numeric literals with underscores, new APIs in NIO such as path and fi les, automatic resource management, and much more. All the new topics are appropriately explained with suitable examples. New to the Second Edition This revised edition has been updated thoroughly with greater topical coverage as well as more programming examples in every chapter, in addition to the confi rmation to Java 7. Practically every chapter, with the exception of Chapter 11, has been revisited to refi ne the text as much as possible. The most noticeable changes are as follows:   New practical programming examples to show how Java is used in practice.  Enhanced coverage of servlets and JDBC along with an introduction to JSP, Java beans, Jar fi les and enterprise Java beans  Enhanced coverage of swing components like JTree, JTable, layered pane, JDesktopPane, internal frames, JColorChooser, JFileChooser, and JEditorPane  New classes of java.nio package and project coin language enhancements   Enhanced coverage of utility classes  Appendix B contains more interview questions to help students prepare for their interviews.  The second edition is supplemented with a rich online resource centre that contains chapter- wise PPTs for teachers and additional practical programming examples for students. Key Features The most prominent feature of this book has been the line-by-line explanation section under each program. They facilitate in-depth understanding of the whole program. We have retained this feature in the second edition as it has been well appreciated by the users. Other noticeable features include the following: Preface to the Second Edition
Preface to the Second Edition vii   A recap of object-oriented programming concepts before introducing the concepts of Java  Plenty of user-friendly programs and key notes at appropriate places to highlight important concepts  A variety of end-chapter exercises that includes subjective as well as objective questions Extended Chapter Material The second edition includes the following changes: Chapter 1, Introduction to OOP: Enhanced coverage of UML and its application in pictorial representation of OOP concepts. Chapter 2, Getting Started with Java: New sections about the features of Java 7 and how to install JDK 1.7. Chapter 3, Java Programming Constructs: Numeric literals with underscores, binary numeric literals, and how to use strings in switch statements. Chapter 4, Classes and Objects: New topics such as inner classes, variable length arguments, arrays as return values from methods, and objects as arguments to and return type from methods. It contains a practical problem on complex numbers to demonstrate how OOP concepts can be put to practise. Chapter 5, Inheritance: New section that highlights the differences between shadowing and overriding. At the end of the chapter, there is a practical programming example on circle and cylinder class. Chapter 6, Interfaces, Packages, and Enumeration: Practical problem on banking concepts to demonstrate the usage of packages in creating applications. Chapter 7, Exception, Assertions, and Logging: try-with-resources and catching multiple exceptions features which are new enhancements of Java 7. Chapter 8, Multithreading in Java: Concrete practical example to show the use of threads in applications. Chapter 9, Input/Output, Serialization, and Cloning: New classes included in java.nio package and how to perform cloning of objects. Chapter 10, Generics, java.util and other API: Utility classes like Random class, Runtime class, Observer and Observable and refl ection API. Chapter 12, Applets: how to use threads and images in applets. The practical problem at the end of the chapter explains how to display a digital clock. Chapter 13, Event Handling in Java: Practical programming example that explains how to create a cartoon on applet and performs its event handling. This is actually a series of examples with gradual and step-by-step revision in all of them in order to enhance their functionality and then eliminate their drawbacks. Chapter 14, Abstract Window Toolkit: Mini project like programming example on CityMap Applet. The applet shows the map of a city from top angle with fi ve buttons, namely, Hospitals, Shopping Malls, Police station, Post Offi ce, and Stadium. If a user presses the Hospital button, all the hospitals are shown on the map with a specifi c color and likewise for Malls, Police station, Post offi ce and Stadium. Chapter 15, Swing: Explanation of new classes with examples and also includes a practical programming example to create a mini text editor. Chapter 16, Introduction to Advanced Java: Introductory sections on JSP, Java Beans, Jar fi les and enterprise Java beans with lots of examples apart from enhanced coverage of servlets and JDBC. This chapter also encompasses a login application built using servlets and database to demonstrate how to create and use a web application.
viii Preface to the Second Edition Content and Structure This book comprises 16 chapters and two appendices. A brief outline of each chapter is as follows. Chapter 1 focuses on the object-oriented concepts and principles. It provides real life mapping of concepts and principles besides depicting them pictorially. In addition to this, the chapter also provides an introduction to Unifi ed Modeling Language (UML), which is a modeling language to show classes, objects, and their relationship with other objects. Chapter 2 introduces Java and its evolution from its inception to its current state. Besides introducing the features of Java, it also tells you about the structure of JDK (Java Development Kit) and the enhancements made to Java in its latest versions. It describes how to install and run the JDK that is in turn required for executing a Java program. Chapter 3 describes the basic programming constructs used in Java such as variables, data types, identifi ers, etc. Java reserved keywords are also depicted in this chapter. The operators (arithmetic, relational, boolean, etc.) that act on variables are also explained in this chapter. For each set of operators, we have provided suffi cient examples along with their explanation and output. Apart from variables and operators, this chapter focuses on statements like if and other loops available in Java (for, while, do…while, and for...each). Chapter 4 deals with classes and objects. A lot of practical problems and their solutions have been discussed in this chapter. It begins with how to defi ne classes, objects, and method creation. Method overloading is also discussed. Later, it emphasizes on the differences between instance variables/methods and class variables and methods. Finally, a discussion about arrays, this keyword, and command-line arguments is also provided. Chapter 5 focuses on inheritance and its uses. How it is realized in Java is discussed in this chapter. Apart from this, polymorphism concepts are visualized through method overriding and super keyword. How practical programming problems are solved through super keyword forms a major part of this chapter. Towards the end of the chapter, some related concepts like abstract classes are also discussed. Chapter 6 covers interfaces, packages, and enumeration. It highlights the differences between abstract classes and interfaces and their practical usages with examples. The role of packages in Java and their creation and usage is also discussed. In-depth coverage of a predefi ned package java.lang is included in this chapter along with some of the famous classes such as String, StringBuffer, StringBuilder, and Wrapper classes. Chapter 7 discusses exceptions in detail. Apart from explaining in detail the fi ve keywords (try, catch, throw, throws, and fi nally) used in handling exceptions, it also discusses how a user can create his own exceptions and handle them. Concepts such as exception, encapsulation, and enrichment are also explained in this chapter. Besides these, the new facilities provided by Java like assertions and logging are also discussed. Chapter 8 covers multithreading concepts, its states, priorities, etc. It also discusses in detail the inter-thread communication and synchronization concepts. Methods like wait(), notify(), and notifyAll() have also been discussed. Chapter 9 emphasizes on the essentials of I/O concepts like how standard input can be taken and how output is delivered to the standard output. A few main classes of the java.io package are discussed with examples and their usages. Console class, used for taking user input, is also discussed. What is the use of making objects persistent and how will it be done is discussed towards the end of the chapter. Chapter 10 discusses the java.util package in detail. The interfaces like Map, Set, and List etc have been discussed in detail as well as their subclasses like LinkedList, ArrayList, Vector, HashSet, HashMap, TreeMap, etc. Java 5 introduced a new feature named ‘Generics’ which
Preface to the Second Edition ix forms the core of the java.util package. This concept along with its application has been covered in detail. Chapter 11 explains how network programming can be done in Java. In-depth coverage of sockets is extended in this chapter. Client and server concept is illustrated by the programs created. TCP and UDP clients and server and their interactions are demonstrated. The concept of multithreading is merged with socket and illustrated to create server programs. Some main classes such as URL, URL connection, and network interface (new feature) are also discussed. Chapter 12 focuses on applets, its lifecycle, methods, etc. and how they are different from applications. Besides providing an in-depth coverage of java.applet package, some of the classes of java.awt package are also discussed as they are very useful in creating applets such as Graphics class, Font class, Color class, and FontMetric class. All these classes are discussed and supported by an example for each of them. Chapter 13 talks about event handling in Java. Basically for creating effective GUI applications, we need to handle events and this forms the basis of this chapter. The event handling model is not only discussed but applied throughout the chapter. All the approaches to event handling have been discussed such as Listener interfaces, Adapter classes, inner classes, and anonymous inner classes. Chapter 14 focuses on GUI creation through java.awt package. It has an in-depth coverage of containers and components. Containers like Frame, Window, etc. and components like Label, Button, TextField, Choice, Checkbox, List, etc. are discussed in detail. How the components can be arranged in a container is also discussed, e.g. BorderLayout, GridBagLayout, and GridLayout. Chapter 15 shows how to create more advanced and lightweight GUI applications in Java. More advanced layouts like SpringLayout have been discussed. Lightweight components like JButton, JLabel, JCheckBox, JToggleButton, JList, JScrollPane, JTabbedPane, etc. have been discussed. How to create Dialogs is also discussed. The pluggable look and feel of Java is explained in detail. Chapter 16 focuses on advanced Java concepts such as servlets, JDBC, and RMI. An introduction to the advanced technologies has been discussed. This chapter is equipped with numerous fi gures showing how to install the necessary softwares required for executing an advanced Java program. The chapter also provides a step-by-step and simplifi ed approach on how to learn advanced concepts. Appendix A on practical lab problems will facilitate better understanding of the concepts explained in the book. Appendix B includes a list of interview questions along with their answers that provides an overview of the industry scenario and their requirements. ACKNOWLEDGEMENTS Several people have been instrumental throughout this tiring yet wonderful journey. First of all, we would like to express our sincere gratitude to our families without whose support, patience, and cooperation, this would not have been possible and we would not have been what we are today. We are also thankful to our colleagues and friends for their endless support and suggestions during the entire process of writi ng this book. Lastly, we would also like to thank all our readers /students who have supported us, encouraged us, and provided feedback to us regularly which has helped us in shaping this edition. Sachin Malhotra Saurabh Choudhary
Preface to the Second Edition vi Preface to the First Edition x Detailed Contents xiii 1. Introduction to OOP 1 2. Getting Started With Java 12 3. Java Programming Constructs 42 4. Classes and Objects 74 5. Inheritance 132 6. Interfaces, Packages, and Enumeration 156 7. Exception, Assertions, and Logging 199 8. Multithreading in Java 224 9. Input/Output, Serialization and Cloning 256 10. Generics, java.util and other API 296 11. Network Programming 336 12. Applets 354 13. Event Handling in Java 394 14. Abstract Window Toolkit 429 15. Swing 495 16. Introduction to Advanced Java 553 Appendix A: Lab Manual 628 Appendix B: Interview Questions 650 Index 657 Brief Contents
Preface to the Second Edition vi Preface to the First Edition x 1. Introduction to OOP 1 1.1 Introduction 1 1.2 Need of Object-Oriented Programming 2 1.2.1 Procedural Languages 2 1.2.2 Object-Oriented Modeling 2 1.3 Principles of Object-Oriented Languages 3 1.3.1 Classes 3 1.3.2 Objects 3 1.3.3 Abstraction 3 1.3.4 Inheritance 4 1.3.5 Encapsulation 4 1.3.6 Polymorphism 5 1.4 Procedural Language vs OOP 5 1.5 OOAD Using UML 6 1.6 Applications of OOP 9 2. Getting Started With Java 12 2.1 Introduction 12 2.2 History of Java 13 2.3 Java’s Journey: From Embedded Systems To Middle-Tier Applications 13 2.4 Java Essentials 14 2.5 Java Virtual Machine 15 2.6 Java Features 16 2.6.1 Platform Independence 16 2.6.2 Object Oriented 16 2.6.3 Both Compiled and Interpreted 17 2.6.4 Java is Robust 18 2.6.5 Java Language Security Features 18 2.6.6 Java is Multithreaded 20 2.6.7 Other Features 20 2.7 Program Structure 21 2.7.1 How to Execute a Java Program 21 2.7.2 Why Save as Example.Java? 22 2.7.3 Explanation 22 2.8 Java Improvements 23 2.8.1 Java 5.0 Features 23 2.8.3 Java 6 Features 25 2.8.4 Java 7 Features 26 2.8.4 Brief Comparison of Different Releases 27 2.9 Differences between Java and C++ 28 2.10 Installation of JDK 1.7 29 2.10.1 Getting Started With the JDK 29 2.10.2 JDK Installation Notes 29 2.10.3 Exploring the JDK 37 2.11 Integrated Development Environment 39 3. Java Programming Constructs 42 3.1 Variables 42 3.2 Primitive Data Types 42 3.3 Identifi er 44 3.3.1 Rules for Naming 44 3.3.2 Naming Convention 44 3.3.3 Keywords 45 3.4 Literals 45 3.5 Operators 48 3.5.1 Binary Operators 48 3.5.2 Unary Operators 54 3.5.3 Ternary Operator 54 Detailed Contents
xiv Detailed Contents 3.6 Expressions 55 3.7 Precedence Rules and Associativity 55 3.8 Primitive Type Conversion and Casting 57 3.9 Flow of Control 61 3.9.1 Conditional Statements 62 3.9.2 Loops 65 3.9.3 Branching Mechanism 68 4. Classes and Objects 74 4.1 Classes 74 4.2 Objects 75 4.2.1 Difference between Objects and Classes 76 4.2.2 Why Should We Use Objects and Classes? 76 4.3 Class Declaration in Java 77 4.3.1 Class Body 78 4.4 Creating Objects 79 4.4.1 Declaring an Object 79 4.4.2 Instantiating an Object 79 4.4.3 Initializing an Object 80 4.5 Methods 82 4.5.1 Why Use Methods? 82 4.5.2 Method Types 82 4.5.3 Method Declaration 83 4.5.3 Instance Method Invocation 86 4.5.4 Method Overloading 87 4.6 Constructors 90 4.6.1 Parameterized Constructors 93 4.6.2 Constructor Overloading 94 4.7 Cleaning Up Unused Objects 96 4.7.1 The Garbage Collector 96 4.7.2 Finalization 97 4.7.3 Advantages and Disadvantages 97 4.8 Class Variable and Methods—Static Keyword 97 4.8.1 Static Variables 98 4.8.2 Static Methods 99 4.8.3 Static Initialization Block 101 4.9 this Keyword 103 4.10 Arrays 105 4.10.1 One-Dimensional Arrays 105 4.10.2 Two-Dimensional Arrays 110 4.10.3 Using for-each With Arrays 115 4.10.4 Passing Arrays to Methods 115 4.10.5 Returning Arrays from Methods 116 4.10.6 Variable Arguments 117 4.11 Command-line Arguments 118 4.12 Nested Classes 119 4.12.1 Inner Class 119 4.12.2 Static Nested Class 122 4.12.3 Why Do We Create Nested Classes? 124 4.13 Practical Problem: Complex Number Program 124 5. Inheritance 132 5.1 Inheritance vs Aggregation 132 5.1.1 Types of Inheritance 133 5.1.2 Deriving Classes Using Extends Keyword 135 5.2 Overriding Method 137 5.3 super Keyword 141 5.4 fi nal Keyword 146 5.5 Abstract Class 147 5.6 Shadowing vs Overriding 149 5.7 Practical Problem: Circle and Cylinder Class 151 6. Interfaces, Packages, and Enumeration 156 6.1 Interfaces 156 6.1.1 Variables in Interface 158 6.1.2 Extending Interfaces 160 6.1.3 Interface vs Abstract Classes 160 6.2 Packages 161 6.2.1 Creating Packages 162 6.2.2 Using Packages 164 6.2.3 Access Protection 168
Detailed Contents xv 6.3 java.lang Package 169 6.3.1 java.lang.Object Class 169 6.3.2 Java Wrapper Classes 170 6.3.3 String Class 174 6.3.4 StringBuffer Class 179 6.3.5 StringBuilder Class 180 6.3.6 Splitting Strings 181 6.4 Enum Type 183 6.4.1 Using Conditional Statements with an Enumerated Variable 185 6.4.2 Using for Loop for Accessing Values 185 6.4.3 Attributes and Methods Within Enumeration 186 6.5 Practical Problem: Banking Example 187 7. Exception, Assertions, and Logging 199 7.1 Introduction 199 7.1.1 Exception Types 201 7.2 Exception Handling Techniques 202 7.2.1 try…catch 203 7.2.2 throw Keyword 206 7.2.3 throws 207 7.2.4 fi nally Block 209 7.2.5 try-with-resources Statement 210 7.2.6 Multi Catch 212 7.2.7 Improved Exception Handling in Java 7 213 7.3 User-Defi ned Exception 215 7.4 Exception Encapsulation and Enrichment 216 7.5 Assertions 217 7.6 Logging 219 8. Multithreading in Java 224 8.1 Introduction 224 8.2 Multithreading in Java 225 8.3 java.lang.Thread 225 8.4 Main Thread 227 8.5 Creation of New Threads 228 8.5.1 By Inheriting the Thread Class 228 8.5.2 Implementing the Runnable Interface 231 8.6 Thread.State in Java 234 8.6.1 Thread States 235 8.7 Thread Priority 240 8.8 Multithreading—Using isAlive() and join() 243 8.9 Synchronization 245 8.9.1 Synchronized Methods 246 8.9.2 Synchronized Statements 246 8.10 Suspending and Resuming Threads 246 8.11 Communication between Threads 248 8.12 Practical Problem: Time Clock Example 251 9. Input/Output, Serialization and Cloning 256 9.1 Introduction 256 9.1.1 java.io.InputStream and java io.OutputStream 257 9.2 java.io.File Class 258 9.3 Reading and Writing Data 261 9.3.1 Reading/Writing Files Using Byte Stream 261 9.3.2 Reading/Writing Console (User Input) 264 9.3.3 Reading/Writing Files Using Character Stream 269 9.3.4 Reading/Writing Using Buffered Byte Stream Classes 270 9.3.5 Reading/Writing Using Buffered Character Stream Classes 272 9.4 Randomly Accessing a File 273 9.5 Reading and Writing Files Using New I/O Package 276 9.6 Java 7 Nio Enhancements 278
xvi Detailed Contents 9.7 Serialization 283 9.8 Cloning 285 10. Generics, java.util and other API 296 10.1 Introduction 296 10.2 Generics 301 10.2.1 Using Generics in Arguments and Return Types 304 10.2.2 Wildcards 304 10.2.3 Bounded Wildcards 306 10.2.4 Defi ning Your Own Generic Classes 307 10.3 Linked List 309 10.4 Set 311 10.4.1 Hashset Class 312 10.4.2 Treeset Class 314 10.5 Maps 315 10.5.1 Hashmap Class 315 10.5.2 Treemap Class 317 10.6 Collections Class 318 10.7 Legacy Classes and Interfaces 319 10.7.1 Difference between Vector and Arraylist 319 10.7.2 Difference between Enumerations and Iterator 320 10.8 Utility Classes: Random Class 320 10.8.1 Observer and Observable 322 10.9 Runtime Class 326 10.10 Refl ection API 328 11. Network Programming 336 11.1 Introduction 336 11.1.1 TCP/IP Protocol Suite 336 11.2 Sockets 337 11.2.1 TCP Client and Server 338 11.2.2 UDP Client and Server 342 11.3 URL Class 344 11.4 Multithreaded Sockets 346 11.5 Network Interface 349 12. Applets 354 12.1 Introduction 354 12.2 Applet Class 355 12.3 Applet Structure 356 12.4 Example Applet Program 357 12.4.1 How to Run an Applet? 358 12.5 Applet Life Cycle 359 12.6 Common Methods Used in Displaying the Output 361 12.7 paint(), update(), and repaint() 364 12.7.1 paint() Method 364 12.7.2 update() Method 365 12.7.3 repaint() Method 366 12.8 More About Applet Tag 366 12.9 getDocumentbase() and getCodebase() Methods 369 12.10 Appletcontext Interface 370 12.10.1 Communication between Two Applets 371 12.11 How To Use An Audio Clip? 372 12.12 Images in Applet 373 12.12.1 Mediatracker Class 375 12.13 Graphics Class 377 12.13.1 An Example Applet Using Graphics 379 12.14 Color 380 12.15 Font 382 12.16 Fontmetrics 386 12.17 Practical Problem: Digital Clock 390 13. Event Handling in Java 394 13.1 Introduction 394 13.2 Event Delegation Model 395 13.3 java.awt.Event Description 395 13.3.1 Event Classes 395 13.4 Sources of Events 404 13.5 Event Listeners 404 13.6 How Does The Model Work? 406 13.7 Adapter Classes 410 13.7.1 How To Use Adapter Classes 410
Detailed Contents xvii 13.7.2 Adapter Classes in Java 412 13.8 Inner Classes in Event Handling 413 13.9 Practical Problem: Cartoon Applet 416 13.9.1 Smiling Cartoon With Blinking Eyes (Part 1) 416 13.9.2 Smiling Cartoon With Blinking Eyes (Part 2) 420 13.9.3 Smiling Cartoon (Part 3) 423 14. Abstract Window Toolkit 429 14.1 Introduction 429 14.1.1 Why Awt? 429 14.1.2 java.awt Package 430 14.2 Components and Containers 432 14.2.1 Component 432 14.2.2 Components as Event Generator 433 14.3 Button 434 14.4 Label 437 14.5 Checkbox 438 14.6 Radio Buttons 441 14.7 List Boxes 444 14.8 Choice Boxes 448 14.9 Textfi eld and Textarea 451 14.10 Container Class 455 14.10.1 Panels 455 14.10.2 Window 456 14.10.3 Frame 456 14.11 Layouts 458 14.11.1 FlowLayout 459 14.11.2 BorderLayout 462 14.11.3 CardLayout 465 14.11.4 GridLayout 469 14.11.5 GridbagLayout 471 14.12 Menu 478 14.13 Scrollbar 483 14.14 Practical Problem: City Map Applet 487 15. Swing 495 15.1 Introduction 495 15.1.1 Features of Swing 496 15.1.2 Differences between Swing and AWT 496 15.2 JFrame 497 15.3 JApplet 500 15.4 JPanel 501 15.5 Components in Swings 502 15.6 Layout Managers 506 15.6.1 Springlayout 506 15.6.2 Boxlayout 509 15.7 JList and JScrollPane 510 15.8 Split Pane 513 15.9 JTabbedPane 514 15.10 JTree 516 15.11 JTable 521 15.12 Dialog Box 525 15.13 JFileChooser 529 15.14 JColorChooser 530 15.15 Pluggable Look and Feel 531 15.16 Inner Frames 539 15.17 Practical Problem: Mini Editor 545 16. Introduction to Advanced Java 553 16.1 Introduction to J2ee 553 16.2 Database Handling Using JDBC 553 16.2.1 Load the Driver 554 16.2.2 Establish Connection 556 16.2.3 Create Statement 556 16.2.4 Execute Query 557 16.2.5 Iterate Resultset 557 16.2.6 Scrollable Resultset 559 16.2.7 Transactions 560 16.3 Servlets 562 16.3.1 Lifecycle of Servlets 562 16.3.2 First Servlet 563 16.3.3 Reading Client Data 567 16.3.4 Http Redirects 571 16.3.5 Cookies 572
xviii Detailed Contents 16.3.6 Session Management 574 16.4 Practical Problem: Login Application 577 16.5 Introduction to Java Server Pages 589 16.5.1 JSP Life Cycle 589 16.5.2 Steps in JSP Page Execution 590 16.5.3 JSP Elements 590 16.5.4 Placing Your JSP in the Webserver 593 16.6 Java Beans 597 16.6.1 Properties of a Bean 597 16.6.2 Using Beans Through JSP 601 16.6.3 Calculatebean Example 602 16.7 Jar Files 605 16.7.1 Creating a Jar File 605 16.7.2 Viewing the Contents of a Jar File 606 16.7.3 Extracting the Contents of Jar 607 16.7.4 Manifest Files 607 16.8 Remote Method Invocation 609 16.8.1 RMI Networking Model 609 16.8.2 Creating an Rmi Application 610 16.9 Introduction to EJB 613 16.9.1 Types of EJB 614 16.9.2 EJB Architecture 615 16.10 Hello World—EJB Example 616 Appendix A: Lab Manual 628 Appendix B: Interview Questions 650 Index 657
Beauty is our weapon against nature; by it we make objects, giving them limit, symmetry, proportion. Beauty halts and freezes the melting flux of nature. Camille Paglia After reading this chapter, the readers will be able to  know what is object-oriented programming  understand the principles of OOP  understand how is OOP different from procedural languages  comprehend the problems in procedural programming and how OOP overcomes them  learn the applications of OOP  use UML notations 1.1 INTRODUCTION Object-oriented programming (OOP) is one of the most interesting and useful innovations in software development. OOP has strong historical roots in programming paradigms and practices. It addresses the problems commonly known as the software crisis. Software have become inherently complex which has led to many problems within the development of large software projects. Many software have failed in the past. The term ‘software crisis’ describes software failure in terms of  Exceeding software budget  Software not meeting clients’ requirements  Bugs in the software OOP is a programming paradigm which deals with the concepts of object to build programs and software applications. It is modeled around the real world. The world we live in is full of objects. Every object has a well-defined identity, attributes, and behavior. Objects exhibit the same behavior in programming. The features of object-oriented programming also map closely to the real-world features like inheritance, abstraction, encapsulation, and polymorphism. We will discuss them later in the chapter. Introduction to OOP 1
2 Programming in Java 1.2 NEED OF OBJECT-ORIENTED PROGRAMMING There were certain limitations in earlier programming approaches and to overcome these limitations, a new programming approach was required. We first need to know what these limitations were. 1.2.1 Procedural Languages In procedural languages, such as C, FORTRAN, and PASCAL, a program is a list of instructions. The programmer creates a list of instructions to write a very small program. As the length of a program increases, its complexity increases making it difficult to maintain a very large program. In the structured programming, this problem can be overcome by dividing a large program into different functions or modules, but this gives birth to other problems. Large programs can still become increasingly complex. There are two main problems in procedural language—(i) the functions have unrestricted access to global data and (ii) they provide poor mapping to the real world. Here are some other problems in the procedural languages. Computer languages generally have built-in data types: integers, character, float, and so on. It is very difficult to create a new data type or a user-defined data type. For example, if we want to work with dates or complex numbers, then it becomes very difficult to work with built-in types. Creating our own data types is a feature called extensibility: we can extend the capabilities of a language. Procedural languages are not extensible. In the traditional languages, it is hard to write and maintain complex results. 1.2.2 Object-Oriented Modeling In the physical world, we deal with objects like person, plane, or car. Such objects are not like data and functions. In the complex real-world situations, we have objects which have some attributes and behavior. We deal with similar objects in OOP. Objects are defined by their unique identity, state, and behavior. The state of an object is identified by the value of its attributes and behavior by methods. Attributes Attributes define the data for an object. Every object has some attributes. Different types of objects contain different attributes or characteristics. For example, the attributes of a student object are name, roll number, and subject; and the attributes for a car object would be color, engine power, number of seats, etc. These attributes will have specific values, such as Peter (for name) or 23 (for roll number). Behavior The response of an object when subjected to stimulation is called its behavior. Behavior defines what can be done with the objects and may manipulate the attributes of an object. For example, if a manager orders an employee to do some task, then he responds either by doing it or not doing it. The wings of a fan start moving only when the fan is switched ON. Behavior actually determines the way an object interacts with other objects. We can say that behavior is synonym to functions or methods: we call a function to perform some task. For example, an Employee class will have functions such as adding an employee, updating an employee details, etc.