Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
100% found this document useful (17 votes)
67 views

Programming in Java 2nd Edition Edition Choudhary Download PDF

ebook

Uploaded by

muiremzaiin
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (17 votes)
67 views

Programming in Java 2nd Edition Edition Choudhary Download PDF

ebook

Uploaded by

muiremzaiin
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 84

Full download ebook at ebookgate.

com

Programming in Java 2nd edition Edition


Choudhary

https://ebookgate.com/product/programming-in-
java-2nd-edition-edition-choudhary/

Download more ebook from https://ebookgate.com


More products digital (pdf, epub, mobi) instant
download maybe you interests ...

A Guide To Programming in Java Java 2 Platform Standard


Edition 5 Beth Brown

https://ebookgate.com/product/a-guide-to-programming-in-java-
java-2-platform-standard-edition-5-beth-brown/

Java Programming 8th Edition Joyce Farrell

https://ebookgate.com/product/java-programming-8th-edition-joyce-
farrell/

Java Programming 6th Edition Joyce Farrell

https://ebookgate.com/product/java-programming-6th-edition-joyce-
farrell/

Functional Programming in Java Harnessing the Power Of


Java 8 Lambda Expressions 1st Edition Venkat
Subramaniam

https://ebookgate.com/product/functional-programming-in-java-
harnessing-the-power-of-java-8-lambda-expressions-1st-edition-
venkat-subramaniam/
JXTA Java P2P Programming 1st Edition Daniel Brookshier

https://ebookgate.com/product/jxta-java-p2p-programming-1st-
edition-daniel-brookshier/

Java Network Programming Third Edition Elliotte Rusty


Harold

https://ebookgate.com/product/java-network-programming-third-
edition-elliotte-rusty-harold/

Beginning Programming with Java For Dummies 3rd Edition


Barry Burd

https://ebookgate.com/product/beginning-programming-with-java-
for-dummies-3rd-edition-barry-burd/

Programming in C 2nd Edition Safari

https://ebookgate.com/product/programming-in-c-2nd-edition-
safari/

Programming in Scala 2nd 2nd Edition Martin Odersky

https://ebookgate.com/product/programming-in-scala-2nd-2nd-
edition-martin-odersky/
Programming in
Java
Second Edition

SACHIN MALHOTRA
Associate Professor
IMS, Ghaziabad

SAURABH CHOUDHARY
Formerly, Head
IT Department
IMS, Ghaziabad

1
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
About the Authors

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 field 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 aerospace, 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 definitely 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 influenced 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 first Java book if you are learning
from scratch.
Pankaj Jain | Senior Manager | Bank of America
When you go through this book, you will gain confidence 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.
Preface to the First Edition

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 firewall 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, figures, 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 theLab
Appendix A: Lab Manual—Java First Edition XIxi
Exercises

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
Preface to the Second Edition

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 confirms to Java Standard Edition 7, the latest
release since Oracle took over Sun Microsystems. It is significant 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 files, 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 confirmation to Java 7. Practically
every chapter, with the exception of Chapter 11, has been revisited to refine 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 files 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 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 reflection 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 five buttons, namely, Hospitals,
Shopping Malls, Police station, Post Office, and Stadium. If a user presses the Hospital button,
all the hospitals are shown on the map with a specific color and likewise for Malls, Police station,
Post office 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
files 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 Unified 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, identifiers, 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 sufficient 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 define 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 predefined 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 five keywords
(try, catch, throw, throws, and finally) 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 figures showing how to install the necessary softwares required for executing an
advanced Java program. The chapter also provides a step-by-step and simplified 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 writing 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
Brief Contents
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
Detailed Contents
Preface to the Second Edition vi
Preface to the First Edition x

1. Introduction to OOP 1 2.6.6 Java is Multithreaded 20


2.6.7 Other Features 20
1.1 Introduction 1
2.7 Program Structure 21
1.2 Need of Object-Oriented
Programming 2 2.7.1 How to Execute a Java
Program 21
1.2.1 Procedural Languages 2
2.7.2 Why Save as Example.Java? 22
1.2.2 Object-Oriented Modeling 2
2.7.3 Explanation 22
1.3 Principles of Object-Oriented
2.8 Java Improvements 23
Languages 3
2.8.1 Java 5.0 Features 23
1.3.1 Classes 3
2.8.3 Java 6 Features 25
1.3.2 Objects 3
2.8.4 Java 7 Features 26
1.3.3 Abstraction 3
2.8.4 Brief Comparison of Different
1.3.4 Inheritance 4
Releases 27
1.3.5 Encapsulation 4
2.9 Differences between Java and C++ 28
1.3.6 Polymorphism 5
2.10 Installation of JDK 1.7 29
1.4 Procedural Language vs OOP 5
2.10.1 Getting Started With the JDK 29
1.5 OOAD Using UML 6
2.10.2 JDK Installation Notes 29
1.6 Applications of OOP 9
2.10.3 Exploring the JDK 37
2. Getting Started With Java 12 2.11 Integrated Development
Environment 39
2.1 Introduction 12
2.2 History of Java 13 3. Java Programming Constructs 42
2.3 Java’s Journey: From Embedded Systems
3.1 Variables 42
To Middle-Tier Applications 13
3.2 Primitive Data Types 42
2.4 Java Essentials 14
3.3 Identifier 44
2.5 Java Virtual Machine 15 3.3.1 Rules for Naming 44
2.6 Java Features 16 3.3.2 Naming Convention 44
2.6.1 Platform Independence 16 3.3.3 Keywords 45
2.6.2 Object Oriented 16 3.4 Literals 45
2.6.3 Both Compiled and Interpreted 17 3.5 Operators 48
2.6.4 Java is Robust 18 3.5.1 Binary Operators 48
2.6.5 Java Language Security 3.5.2 Unary Operators 54
Features 18 3.5.3 Ternary Operator 54
xiv Detailed Contents

3.6 Expressions 55 4.9 this Keyword 103


3.7 Precedence Rules and 4.10 Arrays 105
Associativity 55 4.10.1 One-Dimensional Arrays 105
3.8 Primitive Type Conversion 4.10.2 Two-Dimensional Arrays 110
and Casting 57 4.10.3 Using for-each With Arrays 115
3.9 Flow of Control 61 4.10.4 Passing Arrays to Methods 115
3.9.1 Conditional Statements 62 4.10.5 Returning Arrays from
3.9.2 Loops 65 Methods 116
3.9.3 Branching Mechanism 68 4.10.6 Variable Arguments 117
4.11 Command-line Arguments 118
4. Classes and Objects 74 4.12 Nested Classes 119
4.1 Classes 74 4.12.1 Inner Class 119
4.2 Objects 75 4.12.2 Static Nested Class 122
4.2.1 Difference between Objects 4.12.3 Why Do We Create Nested
and Classes 76 Classes? 124
4.2.2 Why Should We Use 4.13 Practical Problem: Complex
Objects and Classes? 76 Number Program 124
4.3 Class Declaration in Java 77
4.3.1 Class Body 78 5. Inheritance 132
4.4 Creating Objects 79 5.1 Inheritance vs Aggregation 132
4.4.1 Declaring an Object 79 5.1.1 Types of Inheritance 133
4.4.2 Instantiating an Object 79 5.1.2 Deriving Classes Using
4.4.3 Initializing an Object 80 Extends Keyword 135
4.5 Methods 82 5.2 Overriding Method 137
4.5.1 Why Use Methods? 82 5.3 super Keyword 141
4.5.2 Method Types 82 5.4 final Keyword 146
4.5.3 Method Declaration 83 5.5 Abstract Class 147
4.5.3 Instance Method Invocation 86 5.6 Shadowing vs Overriding 149
4.5.4 Method Overloading 87 5.7 Practical Problem: Circle
4.6 Constructors 90 and Cylinder Class 151
4.6.1 Parameterized Constructors 93
6. Interfaces, Packages, and
4.6.2 Constructor Overloading 94
Enumeration 156
4.7 Cleaning Up Unused Objects 96
4.7.1 The Garbage Collector 96 6.1 Interfaces 156
4.7.2 Finalization 97 6.1.1 Variables in Interface 158
4.7.3 Advantages and Disadvantages 97 6.1.2 Extending Interfaces 160
4.8 Class Variable and 6.1.3 Interface vs Abstract Classes 160
Methods—Static Keyword 97 6.2 Packages 161
4.8.1 Static Variables 98 6.2.1 Creating Packages 162
4.8.2 Static Methods 99 6.2.2 Using Packages 164
4.8.3 Static Initialization Block 101 6.2.3 Access Protection 168
Detailed Contents xv

6.3 java.lang Package 169 8.4 Main Thread 227


6.3.1 java.lang.Object Class 169 8.5 Creation of New Threads 228
6.3.2 Java Wrapper Classes 170 8.5.1 By Inheriting the Thread
6.3.3 String Class 174 Class 228
6.3.4 StringBuffer Class 179 8.5.2 Implementing the Runnable
6.3.5 StringBuilder Class 180 Interface 231
6.3.6 Splitting Strings 181 8.6 Thread.State in Java 234
6.4 Enum Type 183 8.6.1 Thread States 235
6.4.1 Using Conditional Statements with 8.7 Thread Priority 240
an Enumerated Variable 185 8.8 Multithreading—Using isAlive()
6.4.2 Using for Loop for Accessing and join() 243
Values 185 8.9 Synchronization 245
6.4.3 Attributes and Methods Within 8.9.1 Synchronized Methods 246
Enumeration 186 8.9.2 Synchronized Statements 246
6.5 Practical Problem: Banking 8.10 Suspending and Resuming Threads 246
Example 187 8.11 Communication between
Threads 248
7. Exception, Assertions, 8.12 Practical Problem: Time
and Logging 199 Clock Example 251
7.1 Introduction 199
7.1.1 Exception Types 201 9. Input/Output, Serialization
and Cloning 256
7.2 Exception Handling Techniques 202
7.2.1 try…catch 203 9.1 Introduction 256
7.2.2 throw Keyword 206 9.1.1 java.io.InputStream and
7.2.3 throws 207 java io.OutputStream 257
7.2.4 finally Block 209 9.2 java.io.File Class 258
7.2.5 try-with-resources 9.3 Reading and Writing Data 261
Statement 210 9.3.1 Reading/Writing Files Using Byte
7.2.6 Multi Catch 212 Stream 261
7.2.7 Improved Exception Handling 9.3.2 Reading/Writing Console
in Java 7 213 (User Input) 264
7.3 User-Defined Exception 215 9.3.3 Reading/Writing Files Using
7.4 Exception Encapsulation Character Stream 269
and Enrichment 216 9.3.4 Reading/Writing Using Buffered
7.5 Assertions 217 Byte Stream Classes 270
7.6 Logging 219 9.3.5 Reading/Writing Using Buffered
Character Stream Classes 272
8. Multithreading in Java 224
9.4 Randomly Accessing a File 273
8.1 Introduction 224 9.5 Reading and Writing Files
8.2 Multithreading in Java 225 Using New I/O Package 276
8.3 java.lang.Thread 225 9.6 Java 7 Nio Enhancements 278
xvi Detailed Contents

9.7 Serialization 283 12. Applets 354


9.8 Cloning 285 12.1 Introduction 354
12.2 Applet Class 355
10. Generics, java.util and other API 296
12.3 Applet Structure 356
10.1 Introduction 296 12.4 Example Applet Program 357
10.2 Generics 301 12.4.1 How to Run an Applet? 358
10.2.1 Using Generics in Arguments and 12.5 Applet Life Cycle 359
Return Types 304 12.6 Common Methods Used in
10.2.2 Wildcards 304 Displaying the Output 361
10.2.3 Bounded Wildcards 306 12.7 paint(), update(), and repaint() 364
10.2.4 Defining Your Own 12.7.1 paint() Method 364
Generic Classes 307 12.7.2 update() Method 365
10.3 Linked List 309 12.7.3 repaint() Method 366
10.4 Set 311 12.8 More About Applet Tag 366
10.4.1 Hashset Class 312 12.9 getDocumentbase() and
10.4.2 Treeset Class 314 getCodebase() Methods 369
10.5 Maps 315 12.10 Appletcontext Interface 370
10.5.1 Hashmap Class 315 12.10.1 Communication between Two
Applets 371
10.5.2 Treemap Class 317
12.11 How To Use An Audio Clip? 372
10.6 Collections Class 318
12.12 Images in Applet 373
10.7 Legacy Classes and Interfaces 319
12.12.1 Mediatracker Class 375
10.7.1 Difference between Vector
12.13 Graphics Class 377
and Arraylist 319
12.13.1 An Example Applet Using
10.7.2 Difference between Enumerations
Graphics 379
and Iterator 320
12.14 Color 380
10.8 Utility Classes: Random Class 320
12.15 Font 382
10.8.1 Observer and Observable 322
12.16 Fontmetrics 386
10.9 Runtime Class 326
12.17 Practical Problem: Digital Clock 390
10.10 Reflection API 328
13. Event Handling in Java 394
11. Network Programming 336
13.1 Introduction 394
11.1 Introduction 336 13.2 Event Delegation Model 395
11.1.1 TCP/IP Protocol Suite 336 13.3 java.awt.Event Description 395
11.2 Sockets 337 13.3.1 Event Classes 395
11.2.1 TCP Client and Server 338 13.4 Sources of Events 404
11.2.2 UDP Client and Server 342 13.5 Event Listeners 404
11.3 URL Class 344 13.6 How Does The Model Work? 406
11.4 Multithreaded Sockets 346 13.7 Adapter Classes 410
11.5 Network Interface 349 13.7.1 How To Use Adapter Classes 410
Detailed Contents xvii

13.7.2 Adapter Classes in Java 412 15. Swing 495


13.8 Inner Classes in Event Handling 413
15.1 Introduction 495
13.9 Practical Problem: Cartoon
15.1.1 Features of Swing 496
Applet 416
15.1.2 Differences between
13.9.1 Smiling Cartoon With Blinking Swing and AWT 496
Eyes (Part 1) 416
15.2 JFrame 497
13.9.2 Smiling Cartoon With Blinking
15.3 JApplet 500
Eyes (Part 2) 420
15.4 JPanel 501
13.9.3 Smiling Cartoon (Part 3) 423
15.5 Components in Swings 502
14. Abstract Window Toolkit 429 15.6 Layout Managers 506
15.6.1 Springlayout 506
14.1 Introduction 429 15.6.2 Boxlayout 509
14.1.1 Why Awt? 429 15.7 JList and JScrollPane 510
14.1.2 java.awt Package 430 15.8 Split Pane 513
14.2 Components and Containers 432 15.9 JTabbedPane 514
14.2.1 Component 432 15.10 JTree 516
14.2.2 Components as Event 15.11 JTable 521
Generator 433 15.12 Dialog Box 525
14.3 Button 434 15.13 JFileChooser 529
14.4 Label 437 15.14 JColorChooser 530
14.5 Checkbox 438 15.15 Pluggable Look and Feel 531
14.6 Radio Buttons 441 15.16 Inner Frames 539
14.7 List Boxes 444 15.17 Practical Problem: Mini Editor 545
14.8 Choice Boxes 448
16. Introduction to Advanced Java 553
14.9 Textfield and Textarea 451
14.10 Container Class 455 16.1 Introduction to J2ee 553
14.10.1 Panels 455 16.2 Database Handling Using JDBC 553
14.10.2 Window 456 16.2.1 Load the Driver 554
16.2.2 Establish Connection 556
14.10.3 Frame 456
16.2.3 Create Statement 556
14.11 Layouts 458
16.2.4 Execute Query 557
14.11.1 FlowLayout 459
16.2.5 Iterate Resultset 557
14.11.2 BorderLayout 462
16.2.6 Scrollable Resultset 559
14.11.3 CardLayout 465
16.2.7 Transactions 560
14.11.4 GridLayout 469 16.3 Servlets 562
14.11.5 GridbagLayout 471 16.3.1 Lifecycle of Servlets 562
14.12 Menu 478 16.3.2 First Servlet 563
14.13 Scrollbar 483 16.3.3 Reading Client Data 567
14.14 Practical Problem: City 16.3.4 Http Redirects 571
Map Applet 487 16.3.5 Cookies 572
xviii Detailed Contents

16.3.6 Session Management 574 16.7.1 Creating a Jar File 605


16.4 Practical Problem: Login Application 577 16.7.2 Viewing the Contents of
16.5 Introduction to Java a Jar File 606
Server Pages 589 16.7.3 Extracting the Contents
16.5.1 JSP Life Cycle 589 of Jar 607
16.5.2 Steps in JSP Page Execution 590 16.7.4 Manifest Files 607
16.5.3 JSP Elements 590 16.8 Remote Method Invocation 609
16.5.4 Placing Your JSP in the 16.8.1 RMI Networking Model 609
Webserver 593
16.8.2 Creating an Rmi Application 610
16.6 Java Beans 597
16.9 Introduction to EJB 613
16.6.1 Properties of a Bean 597
16.9.1 Types of EJB 614
16.6.2 Using Beans Through JSP 601
16.6.3 Calculatebean Example 602 16.9.2 EJB Architecture 615
16.7 Jar Files 605 16.10 Hello World—EJB Example 616

Appendix A: Lab Manual 628


Appendix B: Interview Questions 650
Index 657
Introduction to
OOP 1
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.
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.
Introduction to OOP 3

Note If we try to represent the CPU of a computer in OOP terminology, then CPU is the object.
The CPU is responsible for fetching the instructions and executing them. So fetching and
executing are two possible functions (methods or behavior) of CPU. The place (attributes)
where CPU stores the retrieved instructions, values and result of the execution (registers) will
then be the attributes of the CPU.

1.3 PRINCIPLES OF OBJECT-ORIENTED LANGUAGES


OOP languages follow certain principles such as class, object, and abstraction. These principles
map very closely to the real world.
1.3.1 Classes
A class is defined as the blueprint for an object. It serves as a plan or a template. The description
of a number of similar objects is also called a class. An object is not created by just defining a
class. It has to be created explicitly. Classes are logical in nature. For example, furniture does
not have any existence but tables and chairs do exist. A class is also defined as a new data type,
a user-defined type which contains two things: data members and methods.
1.3.2 Objects
Objects are defined as the instances of a class, e.g. table, chair are all instances of the class
Furniture. Objects of a class will have same attributes and behavior which are defined in that
class. The only difference between objects would be the value of attributes, which may vary.
Objects (in real life as well as programming) can be physical, conceptual, or software. Objects
have unique identity, state, and behavior. There may be several types of objects:
 Creator objects: Humans, Employees, Students, Animal

 Physical objects: Car, Bus, Plane

 Objects in computer system: Monitor, Keyboard, Mouse, CPU, Memory

1.3.3 Abstraction
Can you classify the following items?
 Elephant  CD player

 Television  Chair

 Table  Tiger

How many classes do you identify here? The obvious answer anybody would give is three, i.e.,
Animal, Furniture, and Electronic items. But how do you come to this conclusion? Well, we
grouped similar items like Elephant and Tiger and focused on the generic characteristics rather
than specific characteristics. This is called abstraction. Everything in this world can be classified
as living or non-living and that would be the highest level of abstraction.
Another well-known analogy for abstraction is a car. We drive cars without knowing the
internal details about how the engine works and how the car stops on applying brakes. We are
happy with the abstraction provided to us, e.g., brakes, steering, etc. and we interact with them.
In real life, human beings manage complexity by abstracting details away. In programming,
we manage complexity by concentrating only on the essential characteristics and suppressing
implementation details.
4 Programming in Java

1.3.4 Inheritance
Inheritance is the way to adopt the characteristics of one class into another class. Here we have
two types of classes: base class and subclass. There exists a parent–child relationship among
the classes. When a class inherits another class, it has all the properties of the base class and it
adds some new properties of its own. We can categorize vehicles into car, bus, scooter, ships,
planes, etc. The class of animals can be divided into mammals, amphibians, birds, and so on.
The principle of dividing a class into subclass is that each subclass shares common
characteristics with the class from where they are inherited or derived. Cars, scooters, planes,
and ships all have an engine and a speedometer. These are the characteristics of vehicles. Each
subclass has its own characteristic feature, e.g., motorcycles have disk braking system, while
planes have hydraulic braking system. A car can run only on the surface, while a plane can fly
in air and a ship sails over water (see Fig. 1.1).

Vehicle

Road vehicle Air vehicle Water vehicle

Bus Motor bike Aeroplane Boat

Fig. 1.1 Inheritance

Inheritance aids in reusability. When we create a class, it can be distributed to other


programmers which they can use in their programs. This is called reusability. Suppose someone
wants to make a program for a calculator, he can use a predefined class for arithmetic operations,
and then he need not define all the methods for these operations. This is similar to using library
functions in procedural language. In OOP, this can be done using the inheritance feature. A
programmer can use a base class with or without modifying it. He can derive a child class from
a parent class and then add some additional features to his class.
1.3.5 Encapsulation
Encapsulation is one of the features of object-oriented methodology. The process of binding
the data procedures into objects to hide them from
the outside world is called encapsulation (see Fig.
1.2). It provides us the power to restrict anyone from
directly altering the data. Encapsulation is also known Method
as data hiding. An access to the data has to be through
the methods of the class. The data is hidden from the Method Data
outside world and as a result, it is protected. The details Accessing
that are not useful for other objects should be hidden data Method
from them. This is called encapsulation. For example,
an object that does the calculation must provide an
interface to obtain the result. However, the internal
coding used to calculate need not be made available Fig. 1.2 Diagrammatic Illustration of a
to the requesting object. Class to Show Encapsulation
Introduction to OOP 5

1.3.6 Polymorphism
Polymorphism simply means many forms. It can be defined as the same thing being used in
different forms. For example, there are certain bacteria that exhibit in more than one morphological
form. In programming, polymorphism is of two types: compile-time and runtime polymorphism.
Runtime polymorphism, also known as dynamic binding or late binding, is used to determine
which method to invoke at runtime. The binding of method call to its method is done at runtime
and hence the term late binding is used. In case of compile-time polymorphism, the compiler
determines which method (from all the overloaded methods) will be executed. The binding of
method call to the method is done at compile time. So the decision is made early and hence
the term early binding. Compile-time polymorphism in Java is implemented by overloading
and runtime polymorphism by overriding. In overloading, a method has the same name with
different signatures. (A signature is the list of formal argument that is passed to the method.)
In overriding, a method is defined in subclass with the same name and same signature as that
of parent class. This distinction between compile-time and runtime polymorphism is of method
invocation. Compile-time polymorphism is also implemented by operator overloading which
is a feature present in C++ but not in Java. Operator overloading allows the user to define new
meanings for that operator so that it can be used in different ways. The operator (+) in Java is
however an exception as it can be used for addition of two integers as well as concatenation of
two strings or an integer with a string. This operator is overloaded by the language itself and
the Java programmer cannot overload any operator.

1.4 PROCEDURAL LANGUAGE VS OOP


Table 1.1 highlights some of the major differences between procedural and object-oriented
programming languages.
Table 1.1 Procedural Language vs OOP
Procedural Language OOP
 Separate data from functions that operate on them.  Encapsulate data and methods in a class.
 Not suitable for defining abstract types.  Suitable for defining abstract types.
 Debugging is difficult.  Debugging is easier.
 Difficult to implement change.  Easier to manage and implement change.
 Not suitable for larger programs and applications.  Suitable for larger programs and applications.
 Analysis and design not so easy.  Analysis and design made easier.
 Faster.  Slower.
 Less flexible.  Highly flexible.
 Data and procedure based.  Object oriented.
 Less reusable.  More reusable.
 Only data and procedures are there.  Inheritance, encapsulation, and polymorphism are the
key features.
 Use top-down approach.  Use bottom-up approach.
 Only a function call another.  Object communication is there.
 Example: C, Basic, FORTRAN.  Example: JAVA, C++, VB.NET, C#.NET.
6 Programming in Java

1.5 OOAD USING UML


An object-oriented system comprises of objects. The behavior of a system results from its objects
and their interactions. Interaction between objects involves sending messages to each other.
Every object is capable of receiving messages, processing them, and sending to other objects.
Object-oriented Analysis and Design (OOAD)
It is an approach that models software as a group of interacting objects. A model is a description
of the system that we intend to build. Each object is characterized by its class having its own state
(attributes) and behavior. Object-oriented analysis (OOA) analyzes the functional requirements
of a system and focuses on what the system should do. Object-oriented design (OOD) focuses on
how the system does it. The most popular modeling language for OOAD is the unified modeling
language (UML).
UML is a standard language for OOAD. It contains graphical notations for all entities (class,
object, etc.) used in the object-oriented languages along with the relationship that exists among
them. These notations are used to create models. UML helps in visualizing the system, thereby
reducing complexity and improving software quality. The notations used for class and object are
shown in Fig. 1.3. For example, consider an Employee class with attributes name, designation,
salary, etc. and operations such as addEmployee, deleteEmployee, and searchEmployee.
The notation for employee class and its object is as follows:

Employee Class
name
address
designation Attributes
salary

addEmployee
deleteEmployee Behavior
searchEmployee

Fig. 1.3 UML Notation for Class


The notation for an object is very much similar to the class notation. The class name underlined
and followed by a colon represents an object (Fig. 1.4).

:Employee Object
name=peter
address=NY
designation=manager Attributes
salary=10000

addEmployee
deleteEmployee
searchEmployee

Fig. 1.4 UML Notation for Object


Introduction to OOP 7

An instance of a class can be related to any number of instances of other class known as
multiplicity of the relation. One-to-one, one-to-many, and many-to-many are different types
of multiplicities that exist among objects. The multiplicities along with their examples and
respective notations are shown below. Figure 1.5(a) illustrates the generic notation for representing
multiplicity in object-oriented analysis and design. One-to-one mapping is shown as a straight
line between the two classes. Figure 1.5(b) shows the UML notation for demonstrating the one-
to-one mapping. The 1..1 multiplicity depicted on the straight line (both ends) indicates a single
instance of a class is associated with single instance of other class. Figure 1.5 shows that each
country has a president and a president is associated with a country.

Country has Country 1.1 has 1.1


President President

(a) (b)

Fig. 1.5 One-to-one Relationship

A country has many states and many states belong to a country. So there exists a one-to-many
relationship between the two. This relationship is shown in Fig. 1.6. Part (a) of this figure shows
the generic notation where a solid dot is indicated on the many side and both classes are joined
by a straight line. Figure 1.6(b) shows the UML notation where 1..* indicates the one to many
relationship between country and states. On the country end, a 1..1 multiplicity is placed to
indicate one country and on states end, a 1..* is placed to indicate many states.

has 1..1 has 1..*


Country States Country States

(a) (b)

Fig. 1.6 One-to-many Relationship

Let us take another example to explain many-to-many relationship. A teacher teaches many
students and a student can be taught by many teachers. There exists a many-to-many relationship
between them. Many-to-many relationship (Generic notation in OOAD) are represented by
placing solid dots on both ends joined by a straight line as shown in Fig. 1.7(a). The respective
notation in UML is shown in Fig. 1.7(b) where 1..* on both ends is used to signify many-to-
many relationship.

teaches 1..* teaches 1..*


Teacher Student Teacher Student

(a) (b)

Fig. 1.7 Many-to-many Relationship


8 Programming in Java

Besides multiplicity of relations, the relationships can be of various types: inheritance,


aggregation, composition. These relationships can be denoted in UML with links and associations.
The links represent the connection between the objects and associations represent groups of links
between classes. If a class inherits another class, then there exists a parent-child relationship
between them. This relationship is depicted in UML as shown in Fig. 1.8. For example, Shape
is the superclass, and the subclasses of Shape can take any shape, e.g., Square, Triangle, etc.

Shape

Triangle Square

Fig. 1.8 UML Diagram Depicting Inheritance


The above diagram can be extended to depict the OOP principle of polymorphism. Every shape
will have a method named area() which would calculate the area of that shape. The implementation
of area() method would be different for different shapes. For example, the formula for calculating
area of a triangle is different from a square. So the implementation is different but the name of
the method is same. This is polymorphism (one name many implementations). In Fig 1.9 below,
the area() method is overridden by Triangle and Square classes.

Shape

area( )

Triangle Square Rectangle

area( ) area( ) area( )

Fig. 1.9 UML Diagram Depicting Polymorphism

Another kind of relationship that exists among objects is the part-of-relationship. When a
particular object is a part of another object then we say that it is aggregation. For example, car is
Introduction to OOP 9

an aggregation of many objects: engine, door, etc. and engine in turn is an aggregation of many
objects, e.g., cylinder, piston, valves, etc. as shown in Fig. 1.10(a). A special kind of aggregation
is composition where one object owns other objects. If the owner object does not exist, the
owned objects also ceases to exist. For example, the human body is a very good example of
composition. It is a composition of different organs. The hands, feet, and internal organs such
as the lung and intestine are also parts of the body owned by the body.

Car

Human body
Engine Door

Cylinder Radiator Liver Lungs

(a) (b)

Fig. 1.10 (a) Aggregation and (b) Composition

1.6 APPLICATIONS OF OOP


The basic thought behind object-oriented language is to make an object by combining data and
functions as a single unit and then operate on that data. In procedural approach, the focus is on
business process and the data needed to support the process. For example, in the last decade, a
problem bothered every programmer, popularly known as the Y2K problem. Everybody related
to the computer industry was afraid of what will happen past midnight 31 December 1999. The
problem arises due to the writing convention of the year attribute. In early programming days,
a programmer wrote a year in two digits, so there was a problem to distinguish the year 1900
from 2000 because if we write only the last two digits of a year, the computer cannot differentiate
between the two. Nobody perceived this problem and used the date and year code as and when
required, thus aggravating the problem. The solution to this problem was to analyze multiple
lines of codes everywhere and change the year to four digits rather than two. It seems simple to
change the state variable of year but analyzing a code of several thousands of lines to find how
many times you have used date in your code is not an easy task.
If object-oriented programming language had been used, we could have created a Date class
with day, month, and year attributes in it. Wherever the date functionality would be required,
10 Programming in Java

a Date object would be created and used. At a later point of time, if a change is required, for
example, the year of Date class needs to be changed to four digits, then this change would be
incorporated in the class only and this change would automatically be reflected in all the objects
of the Date class whenever they are created and used. So, the change would have to be done at
one place only, i.e., the class and wherever the objects of the class are being used, the changes
would be reflected automatically. There is no need to analyze the whole code and change it.
In OOP, we access data with the help of objects, so it is very easy to overcome a problem
without modifying the whole system. Likewise, OOP is used in various fields, such as
 Real-time systems  Neural networks

 Artificial intelligence  Database management

 Expert systems

SUMMARY
Object-oriented languages have become an ubiquitous large projects, a technique known as OOAD is used.
standard for programming. They have been derived Object-oriented analysis and design deals with how a
from the real world. OOP revolves around objects and system is modeled. OOA deals with what the system
classes. A class is defined as a group of objects with should do and OOD deals with how the system
similar attributes and behavior. OOP is a programming achieves what has been specified by OOA.
paradigm which deals with the concepts of objects to OOAD is realized with the help of a language known
develop software applications. Certain principles have as UML. UML stands for unified modeling language;
been laid down by OOP which are followed by every it is a standard language used for visualizing the
OOP language. These principles are: inheritance, software. An abstract model is created for the entire
abstraction, encapsulation, and polymorphism. software using graphical notations provided by UML.
We have presented a detailed comparison of
procedural and object-oriented languages. For building

EXERCISES
Objective Questions
1. In an object model, which one of the following is (c) Polymorphism (d) None of the above
true? 4. Which one of the following terms must relate to
(a) Abstraction, encapsulation, and multitasking polymorphism?
are the major principles (a) Static allocation (b) Static typing
(b) Hierarchy, concurrency, and typing are the
(c) Dynamic binding (d) Dynamic allocation
major principles
5. Providing access to an object only through its
(c) Abstraction, encapsulation, and polymor-
phism are the major principles member functions, while keeping the details
(d) Typing is the major principle private is called
(a) Information hiding (b) Encapsulation
2. Which one of the following is not an object-
(c) Modularity (d) Inheritance
oriented language?
(a) Simula (b) Java 6. The concept of derived classes is involved in
(c) C++ (d) C (a) Inheritance
3. The ability to hide many different implementations (b) Encapsulation
behind an interface is. (c) Data hiding
(a) Abstraction (b) Inheritance (d) Abstract data types
Introduction to OOP 11

7. Inheritance is a way to (d) All the above


(a) Organize data 9. Which of the following is true about class?
(b) Pass arguments to objects of classes (a) Class possesses data and methods
(c) Add features to existing classes without (b) Classes are physical in nature
rewriting them (c) Collection of similar type of objects is a class
(d) Improve data-hiding and encapsulation (d) Both (a) and (c)
8. UML is used for 10. Which of the following is true about procedural
(a) Creating models languages?
(b) Representing classes, objects and their (a) Debugging is easier
(b) analysis and design is easy
relationships pictorially
(c) less reusable
(c) Reducing complexity and improving software
(d) difficult to implement changes
quality

Review Questions
1. Explain the importance of object-oriented pro- 4. Write short notes on: (a) inheritance, (b) poly-
gramming languages. morphism, (c) abstraction, (d) encapsulation.
2. Explain the difference between class and object. 5. Differentiate between runtime and compite-time
3. Differentiate between procedural languages and polymorphism.
OOP languages.

Programming Exercises
1. Identify the relevant classes along with their A hospital wants to keep track of scheduled
attributes for the following: A departmental store appointments of a patient with his doctor. When
needs to maintain an inventory of cosmetic items a patient is given an appointment, he should be
which might be found there. You should include given a confirmation that states the time and date
female as well as male cosmetic items. Keep of appointment along with the doctor’s name.
information on all items such as item name, Meanwhile the doctor should also be informed
category, manufacturer, cost, date purchased, about the patient details. Each doctor has one
and serial number. weekday as off-day and no patients should be
2. Identify the relevant classes along with their assigned to a doctor on that day.
attributes from the following problem specification:

Answers to Objective Questions


1. (c) 2. (d) 3. (c) 4. (c)
5. (b) 6. (a) 7. (c) 8. (d)
9. (d) 10. (c) and (d)
Getting Started
with Java 2
The road of life can only reveal itself as it is traveled; each turn in the road reveals a
surprise. Man’s future is hidden. Anon

After reading this chapter, the readers will be able to


 know the history of Java

 understand the features of Java and its runtime environment

 know the basic structure of a Java program

 know the details about JDK installation

 understand various constituents of JDK and its development environments

2.1 INTRODUCTION
Java is a popular and powerful language. Although it is a very simple language, there are a
number of subtleties that can trip up less-experienced programmers. Java is an object-oriented
programming language with a built-in application programming interface (API) that can handle
graphical user interfaces (GUI) used to create applications or applets. Java provides a rich set
of APIs apart from being platform-independent.
Much of the syntax in Java is similar to C and C++. One of the major differences between
Java and other languages is that it does not have pointers. However, the biggest difference is that
you are forced to write object-oriented code in Java. Procedural code is embedded in objects.
In Java, we distinguish between applications and applets, applications being programs that
perform functions similar to those written in other programming languages and applets are
programs that are meant to be embedded in a web page and downloaded over the Internet.
When a program is compiled, a byte code is generated which can be executed on any platform,
provided the runtime environment exists on the destination platform.
This chapter guides the readers to a step-by-step introduction to Java programming. An
important thrust of this chapter is to cover the features of Java from an object-oriented perspective.
It also gives an insight about the installation of Java runtime environment and the various
integrated development environments (IDEs) of Java.
This chapter also focusses on the different versions of Java (including the latest Java 7) and
the Core API’s (Java 7 is also known as Java 1.7).
Getting Started with Java 13

2.2 HISTORY OF JAVA


It is often believed that the Java was developed specifically for the World Wide Web. Java as it
was initially developed was intended for the Web. However, it was improved to be a standard
programming language for the Internet application.
Bill Joy, the Vice President at Sun Micro systems, was thought to be the main person to
conceive the idea of a programming language that later became Java. In late 1970s, Bill Joy
wanted to design a language that could contain the best features of languages like MESA and
C. He found that C++ was inefficient for rewriting Unix operating system. In 1991, it was this
desire to invent a better programming tool that propelled Joy in the direction of Sun’s mammoth
project called as the ‘Stealth Project.’ This name was given by Scott McNealy, Sun’s president.
In January 1991, a formal team of persons like Bill Joy, James Gosling, Mike Sheradin, Patrick
Naughton (formerly the project leader of Sun’s Open Windows user environment), and several
other individuals met in Aspen, Colorado for the first time to plan for the Stealth Project.
Stealth Project was all about developing consumer electronic devices that could all be centrally
controlled and programmed from a handheld remote control like device.
James Gosling was made responsible for suggesting a proper programming language for the
project. Initially he thought of using C++, but soon after was convinced about the inadequacy of
C++ for this particular project. He took the first step towards the development of an independent
language that would fit the project objectives by extending and modifying C++.
The idea of naming the language as ‘Oak’ struck Gosling while staring at an oak tree outside his
office window. Unfortunately, this name had already been patented by some other programming
language. Owing to the fear of copyright violation, the name ‘Oak’ was dropped. The team
struggled to find a proper name for the language for many days. After so many brainstorming
sessions, one day finally a thought struck their mind during a trip to the local coffee shop as
recalled by Gosling. The term ‘Java’ in USA is generally a slang used for coffee. Java is also the
name of a coffee produced on the islands of Java in Indonesia. There are some other views also
towards the naming convention used for naming the language as Java. One of it speculates that
the name Java came from several individuals involved in the project: James Gosling, Arthur
Van Goff, Andy Bechtolsheim.

2.3 JAVA’S JOURNEY: FROM EMBEDDED SYSTEMS TO


MIDDLE-TIER APPLICATIONS
Java was designed to run standalone in small devices. The Java language was derived from C++
but with many differences. Java’s platform-independence originally addressed the problem that
applications for embedded devices must run on a wide variety of hardware. But later with the
advent of Internet in 1995, Java was soon adopted, as it could run on heterogeneous operating
systems. Netscape Navigator started using Java in its browser. Many applets (which run inside
a browser) were built and Java achieved popularity and acceptance.
Microsoft developed its own virtual machine that it used in its Internet Explorer which differed
from the specifications laid down. Therefore, Sun and Microsoft ran into a dispute, that was
settled later. Sun saw a potential for Java beyond the browser (see Fig. 2.1).
14 Programming in Java

Client
Browser Internet
(running Web server
Java applet)

Fig. 2.1 Java Applets Running on the Client System


Still Java was not popular for the client-side because of the following reasons:
 Less Impressive GUI Java’s early GUI (AWT) was primitive. The newer GUI (Swing)
was not shipped until the late 90’s (and Swing is still not supported by most modern
browsers without plug-ins).
  Microsoft’s Strong Presence Nearly 95% of the desktop world uses Microsoft.
  Clients’ Software Upgradation Good alternative methods were found to update clients’
software automatically (without having to download Java on-the-fly application code
each time).
  Success of DHTML Browsers have their own dynamic capabilities and many developers
found it easier to code in DHTML. In addition, DHTML pages tend to download and
start faster than Java applets.
Figure 2.2 shows how Java could be used as middle-tier services between the database and a
client browser. In 1997, Sun developed servlets, so that Java could be used to generate dynamic
content based on clients’ request. In 1999, Sun released its Java 2 Enterprise Edition (J2EE).

Web application Client browser


Database

Java in Middle Tier

Fig. 2.2 Middle-tier Capabilities of Java to Run in Web/Application Server


Enterprise Java described how to build middle-tier components. Sun defined Enterprise Java
Beans for developing business logic. The J2EE framework allows developers to concentrate on
building applications rather than mulling over scalability, reliability, and security issues which
are handled by the Web/application server vendors.

2.4 JAVA ESSENTIALS


Java is a platform-independent, object-oriented programming language. Java encompasses the
following features:
  A High-level Language Java is a high-level language that looks very similar to C and

C++ but offers many unique features of its own.


  J
 ava Bytecode Bytecode in Java is an intermediate code generated by the compiler,
such as Sun’s javac, that is executed by the JVM.
  J
 ava Virtual Machine (JVM) JVM acts as an interpreter for the bytecode, which takes
bytecodes as input and executes it as if it was a physical process executing machine
code.
Getting Started with Java 15

Java is designed to be architecturally neutral so that it can run on multiple platforms. The
same runtime code can run on any platform that supports Java. To achieve its cross-architecture
capabilities, the Java compiler generates architecturally neutral bytecode instructions. These
instructions are designed to be both easily interpreted on any machine and easily translated into
native machine code on-the-fly, as shown in Fig. 2.3. Java Runtime Environment (JRE) includes
JVM, class libraries, and other supporting files.
JRE = JVM + Core Java API libraries
JDK = JRE + development tools like compilers

Source code resembles C++ but is simpler to


JAVA source code develop and understand

Same bytecode runs on any JVM (i.e. across


JAVA bytecode many platforms, so it is called write once run
anywhere (WORA)

All major platforms have a JVM. Each JVM


JVM Interprets bytecode to machine code on-the-fly

Fig. 2.3 Java Runtime Environment

Tools such as javac (compiler), java (interpreter), and others are provided in a bundle, popularly
known as Java Development Kit (JDK). JDK comes in many versions (enhanced in each version)
and is different for different platforms such as Windows and Linux. A runtime bundle is also
provided as a part of JDK (popularly known as Java Runtime Environment).

2.5 JAVA VIRTUAL MACHINE


At the heart of the Java platform lies the JVM. Most programming languages compile the source
code directly into machine code, suitable for execution on a particular microprocessor architecture.
The difference with Java is that it uses bytecode, an intermediate code.
Java bytecode executes on a virtual machine. Actually, there wasn’t a hardware implementation
of this microprocessor available when Java was first released. Instead, the processor architecture
is emulated by software known as the virtual machine. This virtual machine is an emulation of
a real Java processor—a machine within a machine (Fig. 2.4). The virtual machine runs on top
of the operating system, which is demonstrated in Fig. 2.5.
The JVM is responsible for interpreting Java bytecode, and
translating this into actions or operating system calls. The JVM
is responsible for catering to the differences between different
platforms and architectures in a way that the developers need not
Physical Machine
be bothered about it.
JVM The JVM forms a part of a large system, the JRE. JRE varies
according to the underlying operating system and computer
Fig. 2.4 JVM Emulation Run on a architecture. If JRE for a given environment is not available, it is
Physical CPU impossible to run the Java software.
16 Programming in Java

Java Runtime Environment


(JRE)

Java Virtual Machine (JVM)

Operating Systems
(Window, Unix, etc)

Hardware
(Intel, Motorola, Alpha, etc.)

Fig. 2.5 JVM Handles Translations

2.6 JAVA FEATURES


Here we list the basic features that make Java a powerful, object-oriented, and popular
programming language.
2.6.1 Platform Independence
Java was designed not only to be cross-platform in source form, like the previous languages
(C, C++), but also in compiled binary form. To achieve this, Java is compiled to an intermediate
form called the bytecode (see Figs 2.3 and 2.4). This bytecode is a platform-independent code
that is read by a special native program called the Java interpreter that executes the corresponding
native machine instructions. The Java compiler is also written in Java. The bytecodes are precisely
defined to remain uniform on all platforms.
The second important part of making Java cross-platform is the uniform definition of
architecture-dependent constructs. In contradiction to other languages, integers in Java are
always four bytes long, and floating point variables follow the IEEE floating point arithmetic
754 standard. You don’t have to worry about the meaning of any type, as it is not going to change
when you transit between different architectures, e.g., Pentium to Sparc. In Java, everything is
well defined. However, the virtual machine and some of its parts have to be written in native
code, thus making it platform-dependent.
2.6.2 Object Oriented
It is conceived that Java is a pure object-oriented language, meaning that the outermost level
of data structure in Java is the object. Everything in Java (constants, variables, and methods)
are defined inside a class and accessed through objects. Java has been developed in a way that
it allows the user to not only learn object-oriented programming but to apply and practise it.
But there are some constraints that violate the purity of Java. It was designed mainly for OOP,
but with some procedural elements. For example, Java supports primitive data types that are
not objects.
Getting Started with Java 17

2.6.3 Both Compiled and Interpreted


Java incorporates the elements of both interpretation and compilation. Here is more information
on these two approaches.
Interpretation
An interpreter reads one line of a program and executes it before going to the next line. The line
is parsed to its smallest operations, the corresponding machine-level code is found, and then
the instruction is executed (this could be done with something like the switch statement in C
with every possible operation-case listed). Basic was one of the earliest interpreted languages
where each text line was interpreted. Similarly, scripting languages like JavaScript, VBScript,
and PHP are also interpreted.
In interpretation, there are no intermediate steps between writing/modifying the code and
running it. The best part is: debugging is fast. Also, the programs are easily transportable to other
platforms (if an interpreter is available). The drawback is its slow performance.
Compilation
The program text file is first converted to native machine code with a program called a compiler.
A linker may also be required to connect together multiple code files together. The output of the
compiler is an executable code. C and C++ are both compiled languages.
The biggest advantage of a compiled language is its fast performance, since the machine
language code instructions load directly into the processor and get executed. In addition, the
compiler can perform certain optimization operations because it looks at the program as a whole
and not line by line. The disadvantages include slower debugging and reduced portability to
other platforms. The source code must be recompiled on the destination platform.
Java Approach
Java incorporates both interpretation and compilation. The text program is compiled to the
intermediate code, called bytecode, for the JVM. The JVM executes the bytecode instructions.
In other words, JVM interprets the bytecode. The bytecode can run on any platform on which a
JVM has been deployed. The program runs inside the JVM, so it does not bother which platform
it is getting executed on.
Thus, Java offers the best of both worlds. The compilation step allows for code optimization
and the JVM makes way for portability. Figure 2.4 will give you an idea about the two phases
involved in the execution of a Java source program, i.e., compile time and execution time (runtime).
Once the source code is converted to bytecode or class file, it is loaded so that it can be
processed by the execution engine of the JVM. Bytecode is loaded either through the bootstrap
class loader (sometimes referred to as the primordial class loader) or through a user-defined
class loader (sometimes referred to as the custom class loader). The bootstrap class loader (part
of the JVM) is responsible for loading trusted classes (e.g., basic Java class library classes).
User-defined class loaders (not part of JVM) are the subclasses of java.util.Class Loader class
that are compiled and instantiated just like any other Java class. The bytecode verifier verifies
the code and ensures that the code is fit to be executed by the JVM. Figure 2.6 shows the flow
of data and control from Java source code through the Java compiler to the JVM. The code is
not allowed to execute until it has passed the verifier’s test.
18 Programming in Java

Compile-Time Runtime

Java Class loader


source (Bytecode
loader)

Bytecode
Bytecode
moves through
Java compiler verifier
network or
file system

Machine code
Interpreter
generator
Java
bytecode
Operating system

Hardware

Fig. 2.6 Compilation and Interpretation in Java

But there remains the drawback of an extra compilation step after every correction during
debugging. Also, the interpretation of bytecode is still slower in many cases than a program in
local machine code. Advanced JVM can ameliorate this, and in many cases, reach speeds similar
to programs compiled to local machine code.
2.6.4 Java is Robust
The type checking of Java is at least as strong as that of C++. The compile-time and runtime
checks in Java catch many errors and make them crash-proof. The program cannot crash the
system. To sum up, Java is one of the most robust languages to have ever evolved. Automatic
garbage collection of allocated memory is the biggest contributor here.
2.6.5 JAVA Language Security Features
Java has several language features that protect the integrity of the security system and prevent
several common attacks.
Security Through Definition Java is strict in its definition of the language:
  All primitive data types in the language have a specific size.

  All operations are defined to be performed in a specific order.


Security Through Lack of Pointer Arithmetic Java does not have pointer arithmetic, so Java
programmers cannot forge a pointer to memory. All methods and instance variables are referred
to with their symbolic names. Users cannot write a code that interprets system variables or
accesses private information stored in a system.
Security Through Garbage Collection Garbage collection makes Java programs more secure
and robust by automatically freeing memory, once it is no longer needed.
Getting Started with Java 19

Security Through Strict Compile-Time Checking The Java compiler performs extensive,
stringent compile-time checking so that as many errors as possible can be detected by the
compiler. The Java language is strongly typed, that is:
  Objects cannot be cast to a subclass without an explicit runtime check.

  References to methods and variables of a class are checked to ensure that the objects

are of the same class.


  Primitives and objects are not interconvertible.

Strict compilation checks make Java programs more robust and avoid runtime errors. The
bytecode verifier runs the bytecode generated by the compiler when an applet is loaded and
makes security checks. The compiler also ensures that a program does not access any uninitialized
variables.
Java Security Model
Java’s security model is focused on protecting users from hostile programs downloaded from
untrusted sources across a network. Programs downloaded over the Internet are executed in a
sandbox. It cannot take any action outside the boundaries specified by the sandbox.
The sandbox for untrusted Java applets, for example, prohibits many activities, including
  Reading or writing to the local disk

  Making a network connection to any host, except the host from which the applet came

  Creating a new process

  Loading a new dynamic library and directly calling a native method

By making it impossible for the downloaded code to perform certain actions, Java’s security
model protects the user from the threat of hostile codes.
Sandbox—Definition
Traditionally, you had to trust a software before you ran it. You achieved security by allowing
a software from trusted sources only, and by regularly scanning for viruses. Once a software
gets access to your system, it has full control and if it is malicious, it can damage your system
because there are no restrictions placed on the software by the computer. So, in the first place,
you prevent malicious code from ever gaining access to your system.
The sandbox security model makes it easier to work with the software that comes from untrusted
sources by restricting codes from untrusted sources from taking any actions that could possibly
harm your system. The advantage is—you don’t need to figure out what code is trusted and what
is not. In addition to that, you don’t need to scan for viruses as well. The sandbox is made up of
the following components operating together.
Class Loader It is the first link in the security chain. It fetches executable codes from the
network and enforces the namespace hierarchy.
Bytecode Verifier The verifier checks that the applet conforms to the Java language guarantees
and that there are no violations like stack overflows, namespace violations, illegal data type
casts, etc.
Security Manager It enforces the boundary of the sandbox. Whenever an applet performs an
action which is a potential violation, the security manager decides whether it is approved or not.
20 Programming in Java

2.6.6 Java is Multithreaded


To explore this property, you must know the meaning of multithreading.It can be explained well
with the help of an example. Consider a four-gas burner on which food is cooked. The cook,
in order to save time, puts milk to boil on one gas burner, rice on the other, makes chapattis on
the third, and vegetable on the fourth. The cook switches between all the items to be cooked so
that neither of the items are red-heated to lose their taste. He may lower/brighten up the gas as
and when required. Here the cook is the processor and the four items being cooked are threads.
The processor (cook) switches from one thread to another.
A thread can be loosely defined as a separate stream of execution that takes place simultaneously
and independent of everything else that might be happening. Threads are independent parts of a
process that run concurrently. Using threads, a program cannot hold the CPU for a long duration
intentionally (e.g. infinite loop). The beauty of multithreading is that the other tasks that are not
stuck in the loop can continue processing without having to wait for the stuck task to finish.
Threads in Java can place locks on shared resources so that while one thread is using it, no other
thread is allowed to access it. This is achieved with the help of synchronization.
More about threads and its implementation will be taken up later in Chapter 8.
2.6.7 Other Features
Automatic Memory Management
Automatic garbage collection (memory management) is handled by the JVM. To create an instance
of a class, the ‘new’ operator is used (refer to Chapter 4). However, Java automatically removes
objects that are not being referenced. This is known as garbage collection. The advantages and
disadvantages of garbage collection are listed below.
Advantages
  Reduces the possibility of memory leaks, since memory is freed as needed. A memory leak
occurs when the memory allocated is not released, resulting in an unnecessary consumption
of all the available memory.
  Memory corruption does not occur.
Disadvantage
  Garbage collection is considered one of the greatest bottlenecks in the speed of execution.
Dynamic Binding
The linking of data and methods to where they are located is done at runtime. New classes can
be loaded at runtime. Linking is done on-the-fly, i.e., on-demand.
Good Performance
Interpretation of byte code slowed performance in early versions, but advanced virtual machines
with adaptive optimization and just-in-time compilation (combined with other features) provide
high speed code execution.
Built-in Networking
Java was designed with networking in mind and comes with many classes to develop sophisticated
Internet communications. A detailed discussion on this topic is taken up later in Chapter 11.
Getting Started with Java 21

No Pointers
Java uses references instead of pointers. A reference provides access to objects. The programmer
is relieved from the overhead of pointer manipulation.
No Global Variables
In Java, the global namespace is the class hierarchy and so, one cannot create a variable outside
the class. It is extremely difficult to ensure that a global variable is manipulated in a consistent
manner. Java allows a modified type of the global variable called static variable.

class Example 2.7 PROGRAM STRUCTURE


Class and Instance A Java application consists of a collection of classes. A class is
variables
a template. An object is defined as an instance of the class. Each
Method ABC instance (object) contains the members (fields and methods)
Local variables specified in the class. A field is one that holds a value. A method
Instruction
defines operations on the fields and values that are passed as
Method XYZ arguments to the method (see Fig. 2.7).
Local variables Let us now create our first Java program. Example 2.1 below
Instruction shows a very simple Java program which displays a string on the
console. It has just one print statement (the program is explained
Fig. 2.7 Program Structure in Section 2.7.3).

Example 2.1 First Java Program


L1 /* Call this file"Example.java".*/
L2 class Example {
L3 //your program starts execution with a call to main()
L4 public static void main (String args[ ]){
L5 System.out.println(“This is a simple Java program”);
L6 }
L7 }

2.7.1 How to Execute a Java Program?


There are three easy steps for successfully executing the Java program:
1. Entering the Source Code The above program (Example 2.1) can be written in any
text editor (like Notepad) but make sure it is written exactly the same way it is shown.
2. Saving the Source Code Now that you’ve written the code in Notepad, this is how
you’ll save it
  Select File | Save As from the notepad menu.
  In the ‘File name’ field, type “Example.java” within double quotes.
  In the ‘Save as type’ field select All Files (*.*).

  Click enter to save the file.


22 Programming in Java

3. Compiling and Running the Source Java programs are compiled using DOS. For
opening OS, type cmd at the run prompt and move to the folder that contains the saved
Example.java file. Now compile the program using javac, specifying the name of the
source file on the command line as shown below. (Assuming the file was saved in a
folder ‘javaeg’ in the C drive.)
C:\>cd javaeg // change to directory javaeg using cd command
C:\javaeg\>javac Example.java

The javac compiler creates a file called Example.class (in the same directory). This class
contains the bytecode version of the program. This bytecode will be executed by the Java
interpreter using java followed by the class name as shown below.
C:\javaeg\>java Example

Output
This is a simple Java program

2.7.2 Why Save as Example.java?


When the Java source code is compiled, each individual class is put in its own output file named
after the class and using the .class extension. That is why it is a good idea to give the Java
source files the same name as that of the class they contain. The name of the .class file will
match exactly with the name of the source file.
In many programming languages, the name of the source code file can be arbitrary. This is
not so with Java. In the above example, the name of the source file should be Example.java. In
Java, a source file is a normal text file that contains one or more class definitions.
The extension for the source file must be .java. By convention, the name of the file and the
name of class should be same (even the case should match) and that is why we named the above
example as Example.java. Java is case-sensitive. So example and Example are two different
class names.

Note You can also provide a different name for naming a source file. For example, the above
example can be saved as First.java. But in that case, when you compile the file, the .class
that will be generated will have the name Example.class. So for executing the program, you
have to mention java Example on the command line. This may lead to confusion, so it is
advised that the name of the Java file should match with the name of the class defined in the
file (case-wise also). Also note that in case the source file contains more than one classes
defined within itself, the java file name should match exactly with the class name that contains
the main method.

2.7.3 Explanation
L1 The program begins with the comment:
/* Call this file “Example.java”.*/
The comments are ignored by the compiler. Comments are a good way to induce documentation
in programming.
L2 The next line of code in the program is
class Example {
Getting Started with Java 23

This line uses the keyword class to declare that a new class is being defined followed by the
class name, i.e., Example. The entire class definition, including all its members, will be between
the opening curly brace ({ ) and the closing curly brace ( }).
L3 Another type of comment is used in this line.
// your program starts execution with a call to main()

This type of comment is called a single-line comment, and it begins with a double slash //.
L4 This line shows the main method for the class.
public static void main (String args []) {

This is the line from where the program will start its execution. All applications in Java start
execution from main(). Every complete Java Application must contain a root class where the
execution can begin. A root class must contain a main method defined with the header, as shown
in this line. Let us take a brief look at the attributes of main().
public It is an access specifier used to specify that the code can be called from anywhere.main()is
declared public because it is called by codes outside the class it is a part of. It is called by the JVM.
static It is declared static because it allows main()to be called without having to instantiate
the class. JVM need not create an instance of the class (i.e. object of the class) for calling the
main()method.
void It does not return a value. The keyword void simply tells the compiler that main()does not
return anything back to the caller, i.e., JVM.
String args[]It holds optional command line arguments passed to the class through the java
command line. The curly bracket at the end marks the beginning of the main method and it
ends in L6.

Note The Java compiler will compile classes that do not contain a main () method, but the
Java interpreter has no way to run these classes.

L5 It shows a print statement. If you want to display anything on the standard output, this
statement is used.
System.out.println ("This is a simple Java program");

This line prints the string "This is a simple Java Program" on the standard output. System is
a predefined class. The string (mentioned in double quotes) passed to the println method is
displayed as it is on the standard output. All statements in Java are terminated by a semicolon (;).
Lines other than println()don’t end with a semicolon because they are technically not statements.
L6 The closing curly bracket marks the closing of the main method.
L7 The closing curly bracket marks the closing of the class.

2.8 JAVA IMPROVEMENTS


Features of different versions of Java are discussed in the following sections.
2.8.1 Java 5.0 Features
We present a host of features in Java 5 and later discuss some of the improvements in Java 5.
24 Programming in Java

Autoboxing and Unboxing


Chapter 3 explains that Java has primitive types like int for integers, and Chapter 4 explains
classes and objects. The difference between the two types is very important. In Chapter 6, we
examine the so-called autoboxing and unboxing features added to J2SE 5.0 that removes the
need for explicit conversions in most cases and thus improves code readability and removes
boilerplate codes and sources of errors.
Enhanced for Loop
Chapter 3 looks at several types of looping structures available in Java, one of which is the for
loop (quite similar to the C/C++ for loop). Version 5.0 includes an enhanced for loop syntax
that reduces code complexity and enhances readability. We introduce the enhanced for loop in
Chapter 4 and describe the object types with which the enhanced for loop works.
Enumerated Types
Chapter 6 presents a feature of C/C++ that many programmers have missed in Java. An
enumerated type has been added with the enum keyword. The new enumerated type includes all
the features of C/C++ enum including type safety.
StringBuilder Class
We will be discussing this class in Chapter 6, along with the older StringBuffer class. It offers
better performance than StringBuffer class.
Static Import
Release 5.0 includes a new technique for accessing Java static methods and constants in another
class without the need to include the full package and class name every time they are used. (We
will explain the terms class, package, static, import, etc. in Chapters 4 and 7). The ‘static
import’ facility makes your code easier to write and less error-prone. We will discuss static
import in more detail in Chapter 7 after discussing import in general.
Metadata
The metadata facility (annotation) is designed to reduce much of the boilerplate code that would
be required in the earlier versions of Java. Annotations, though not a part of the program, provide
information about the program to the compiler. This information can be used to detect errors and
supply warnings. Annotations begin with ‘@’. The javac compiler processes some annotations
and some require the annotation-processing tool, apt.
Formatted I/O and Varargs
In Chapter 9, we discuss how to format numerical output with Java. Version 5.0 adds the ability
to produce formatted output easily in the form of a printf()method that behaves similar to
the printf() function in C/C++. There is also a formatted input feature (Scanner class) that is
described in Chapter 9. Both these features rely on ‘varargs,’ which stands for variable argument
list in which the number of parameters passed to a Java method is not known when the source
is constructed (also known as variable arity methods) (see Chapter 4 for varargs).
Getting Started with Java 25

Graphics System Improvements


Release 5.0 includes numerous bug fixes and minor tweaks to Java’s graphics subsystems known
as AWT and Swing, including reduced memory usage. The biggest improvement is that it is no
longer necessary to call getContentPane() when adding Swing components.
New Concurrency Features
Chapter 8 discusses Java’s multithreading support that has been present since Version 1.0.
Release 5.0 enhances the multithreading features of Java. Some of these additions depend upon
the generics concept, so we wait until Chapter 10 to introduce these important new capabilities.
Generics
In Chapter 10, we introduce the new generics feature, an important subject that we will cover
in detail. Java is type-safe, which simply means that every variable has a well-defined type and
that only compatible types can be assigned to each other. However, the use of generics adds a
greater amount of compile-time safety to the Java language. The use of generics allows objects
of only a specified type to be added to a collection, thereby enhancing the runtime safety and
correctness of the program; otherwise a compile-time error occurs.
Other new features in J2SE 5.0 include core XML support, improvements to Unicode,
improvements to Java’s database connectivity package known as JDBC, and an improved,
high-compression format for JAR files that can greatly reduce download times for applets and
other networking applications.
Java 2 platform Standard Edition 5.0 (J2SE 5.0) dealt with improvements in the ease of
development (EoD) category. The new EoD features were all about syntax shortcuts that greatly
reduce the amount of code that must be entered, making coding faster and error-free. Some
features enable improved compile-time type checking, thus producing fewer runtime errors.
Apart from EoD category, new multithreading and concurrency features were added that provide
capabilities previously unavailable. The designers of J2SE considered quality, stability, and
compatibility to be the most important aspect of the new release. A lot of efforts were made
to ensure compatibility with previous versions of Java. Faster JVM startup time and smaller
memory footprint were important goals. These have been achieved through careful tuning of
the software and the use of class data sharing. It is much easier to watch memory usage, detect
and respond to a low-memory condition in Java 5.
2.8.2 Java 6 Features
Some of the major enhancements to Java 6 are given below.
Collections API
The motive was to provide bidirectional collection access. New interfaces have been added like
Deque, BlockingDeque, etc. and existing classes like Linked List, TreeSet, and TreeMap have
been modified to implement these new interfaces. A bunch of new classes have been added like
ArrayDeque, ConcurrentSkipListSet, etc.

Input/Output
A new class named Console has been added to the java.io package. It contains methods to
access character-based console. New methods have been added to File class.
26 Programming in Java

Jar and Zip Enhancements


Two new compressed streams have been added.
  java.util.zip.DeflaterInputStream:for compressing data
  java.util.zip.InflaterOutputStream:fordecompressing data
These classes are useful for transmitting compressed data over a network.
Enhancements Common to Java Web Start and Java Plug-in
All dialogs have been redesigned to be more user-friendly. Caching can be disabled via the Java
control panel. A new support for SSL/TSL is added.
Enhanced Network Interface
It provides a number of new methods for accessing state and configuration information relating
to a system’s network adapters. This includes information such as MAC addresses and MTU
size (discussed in Chapter 11).
Splash Screen
Applications can display the splash screen even before the virtual machine starts.
Java 6 also enhanced the monitoring and mangement API and made significant changes to
JConsole.

2.8.3 Java 7 Features


A number of features have been added in Java 7 such as revised switch…case to accept strings,
multi-catch statements in exception handling,try-with-resource statements, the new file input
output API, the fork and join framework and a few others.
String in switch…case Statement
Java 7 added strings to be used in switch…case statements apart from primitives (short, byte,
int, char), enumerated type and few wrapper classes (discussed in Chapter 3).
Unicode 6.0.0 Support
Java 7 supports Unicode 6.0.0. A new string representation is used to express unicode characters
(discussed in Chapter 6).
Binary Literals and Numeric Literals (with Underscores)
Java 7 added binary literals and underscores to be used with numeric literals. This feature is
particularly useful in increasing the readability of larger literals with a long sequence of numbers
(discussed in Chapter 3).
Automatic Resource Management
A new try with resources statement is introduced so that resources specified with try are released/
nullified when try block exits. There is no need to manually free up the resources using finally
block as was the case with earlier versions of Java (discussed in Chapter 7).
Improved Exception Handling
Java 7 introduced a multi-catch block where multiple exceptions can be caught using a single
catch block (discussed in Chapter 7).
Getting Started with Java 27

nio 2.0 (Non-blocking I/O)—New File System API


java.nio.file package was created in Java 7 to include classes and interfaces like Path,Paths,
File System, File Systems and others. Simplified methods to efficiently copy, move, create
links and receive file/directory change notifications were also incorporated (Chapter 9).
Fork and Join Fork and Join Framework is incorporated in Java 7 to have a more efficient
kind of parallel processing. The task is divided (forked) into smaller task such that no thread is
idle and whose results are combined (joined) to achieve the desired outputs. The classes for the
Fork-Join mechanism are ForkJoinPool and ForkJoinTask.
Supporting Dynamism Java compiler performs the type checking of variables, methods,
arguments etc. Java 7 incorporates a new feature invokedynamic to let JVM resolve type
information at runtime like few other dynamic languages and incorporate non-java language
requirements.
Diamond Operator The Generics declaration, prior to Java 7, required the types to be declared
on both the sides of the declaration. Java 7 onwards the compiler can deduce the type on the right
side, using the diamond operator (< >), by looking at the left-hand-side declaration.
Swing Enhancements Swings added a host of features like AWT and Swing components can
be used together without any problems,JLayer class, Nimbus look and feel, HSV color selection
tab in the JColorChooser class and more (see Chapter 15 for details).
Java FX 2.2.3 Java FX provides the new GUI toolkit for creating rich cross-platform user
interfaces across different types of devices like TV, mobile, desktop etc. Java FX is bundled
with JDK 7.
2.8.4 Brief Comparison of Different Releases
Table 2.1 presents a brief comparison of different releases of Java.
Table 2.1 Java JDK Major Releases and their Differences

Version Name New Features Introduced


1.0 Oak Java released to public.
1.1 Sparkler Added a totally new event model, using Listeners, anonymous classes, and inner classes.
1.2 Playground Added Array List and other Collections, added swing. Added DSA code signing.
Added buffered image.
1.3 Kestrel java.util.Timer,java.lang.StrictMath,java.awt.print.Page Attributes, java.
media.sound (MIDI) Hotspot introduced. RMI can now also use CORBA’s IIOP protocol.
Added RSA code signing.
1.4 Merlin Added regexes, assertions, and nio.
1.5 Tiger Added StringBuilder, java.util.concurrent, generics, enumerations and, annotations.
1.6 Mustang Applet splash screens, table sorting, true double buffering, digitally signed XML files,
JavaCompilerTool, JDBC 4.0, smart card API, Console.readPassword, improved drag
and drop.
1.7 Dolphin Automatic resource management, String in switch…case, Fork and join framework,
dynamism support, Unicode 6 supported, Java Fx 2.2.3.
1.8 Not yet There is still on-going discussion on what should be included.
released
28 Programming in Java

2.9 DIFFERENCES BETWEEN JAVA AND C++


Here is a technical overview of the differences between Java and C++. The following points list
out the aspects that are present in Java and absent in C++.
Multiple Inheritance Not Allowed Multilevel inheritance is enforced, which makes the design
clearer. Multiple inheritance among classes is not supported in Java. Interfaces are used for
supporting multiple inheritance.
Common Parent All classes are single-rooted. The class Object is the parent of all the classes
in Java.
Packages The concept of packages is used, i.e., a large, hierarchical namespace is provided.
This prevents naming ambiguities in libraries.
In-source Documentation In-source code documentation comments are provided. Documenta-
tion keywords are provided, e.g. @author, @version, etc.
All Codes Inside Class Unlike C++, all parts of a Java program reside inside the class. Global
data declaration outside the class is not allowed. However, static data within classes is supported.
Operator Overloading Operator overloading is not supported in Java but a few operators are
already overloaded by Java, e.g. ‘+’. Programmers do not have the option of overloading operators.
Explicit boolean Type boolean is an explicit type, different from int. Only two boolean literals
are provided, i.e. true and false. These cannot be compared with integers 0 and 1 as used in
some other languages.
Array Length Accessible All array objects in Java have a length variable associated with them
to determine the length of the array.
go to Instead of goto, break and continue are supported.
Pointers There are no pointers in Java.
Null Pointers Reasonably Caught Null pointers are caught by a NullPointerException.
Memory Management The use of garbage collection prevents memory leaks and referencing
freed memory.
Automatic Variable Initialization All variables are automatically initialized, except local
variables.
Runtime Checking of Container Bounds The bounds of containers (arrays, strings, etc.) are
checked at runtime and an IndexOutOfBoundsException is thrown if necessary.
Platform Independence C++ is not a platform-independent language whereas Java is.
Sizes of the Integer Types Defined The sizes of the integer types byte, short, int, and long
are defined to be 1, 2, 4, and 8 bytes.
Unicode Provided Unicode represents the characters in most of the languages, e.g. Japanese,
Latin, etc.
String Class An explicit predefined String class is provided along with StringBuffer and
new StringBuilder class.
Getting Started with Java 29

Extended Utility Class Libraries: Package java.util Supported among others, Enumeration
(an Iterator interface), Hashtable, Vector.
Default Access Specifier Added By default, all the variables, methods, and classes in Java
have default privileges that are different from private access specifier. Private is the default
access specifier in C++.

2.10 INSTALLATION OF JDK 1.7


Before writing a single line of code, the software application developer must first make sure
that the best tool for the job are at his or her disposal. Java was designed to be a cross-platform,
object-oriented programming language. Because of the huge amount of interest generated by
the introduction of Java, new tools are being introduced every now and then that provide the
developer with greater flexibility and ease of use.
2.10.1 Getting Started with the JDK
Sun (and now continued by Oracle) decided to give away a Java Developer’s Kit (JDK) that
would provide the basic tools needed for Java programming. The JDK provides the beginners
with all the tools needed to write powerful Java applications or applets. It contains a compiler,
an interpreter, a debugger, sample applications, applet viewer, and some other tools that you
can use to test your code.
A quick visit to Oracle Java website will allow you to download the JDK to your local machine.
Check for the latest version of JDK and download that from this site. The following operating
systems are supported for JDK:
(a) Oracle Solaris (b) Windows (c) Linux (d) Mac
Remember that the availability of JDK for these platforms simply means that Oracle has
implemented the JVM and development tools for these platforms.
2.10.2 JDK Installation Notes
When the Java SE Development Kit is installed, the Java SE Runtime Environment is installed
as well.

Note For the installation of JDK 1.7 on Solaris platform (both 32-bit and 64-bit), you can refer to the
installation documentation on Oracle official site:
http://docs.oracle.com/javase/7/docs/webnotes/install/solaris/solaris-jdk.html
Similarly, for installation of JDK 1.7 on Linux operating system (both 32 bit and 64 bit), visit:
http://docs.oracle.com/javase/7/docs/webnotes/install/linux/linux-jdk.html
For JDK installation on MAC OS visit:
http://docs.oracle.com/javase/7/docs/webnotes/install/mac/mac-jdk.html
The JDK for any OS can be downloaded from:
www.oracle.com/technetwork/java/javase/downloads/jdk7u9-downloads-1859576.html.
Refer to www.oracle.com/technetwork/java/javase/downloads/index.html for latest Java SE
releases.
30 Programming in Java

In this book, we intend to provide the details of installation of JDK 1.7 on Windows operating
system only.
JDK has two versions numbers—an external version number 7 and an internal version
number1.7.0_09, i.e., version 7 update 9.
The installation and configuration process can be broken down into the following steps:
1. Run the JDK installer.
2. Update the Path and Classpath variables.
3. Test the installation.
Step 1: Run the JDK Installer
If you have downloaded the JDK software file (JDK installer) instead of running the installer
from the Java website, you should check to see that the complete file is downloaded:
jdk-7u9-windows-i586.exe

Note The JDK documentation can be downloaded from the following URL: www.oracle.com/
technetwork/java/javase/documentation/java-se-7-doc-download-435117.html.

Double-click on the icon of the JDK Installer.exe to run the installer and then follow the
instructions. Figures 2.8(a)–(h) show some of the snapshots of the installation process. The first
Welcome screen is displayed as soon as you double click on the installer.

Fig. 2.8(a)
The welcome screen also tells you that Java FX SDK is now a part of Java 7. Click on Next>,
the installer prompts you to select what all you want to install and where to install them in your
system.
Getting Started with Java 31

Fig. 2.8(b)

By default, the JDK will be installed at the path mentioned in Install to. You can change
the default path by clicking the Change… button. As soon as you click on the Next> button, the
installation starts.

Fig. 2.8(c)
32 Programming in Java

Figure 2.8(d) snapshot shows that JRE will be installed.

Fig. 2.8(d)

Figure 2.8(e) prompts you to make a selection for installing JRE. As soon as you click on Next>,
the installation of JRE starts.

Fig. 2.8(e)
Getting Started with Java 33

The following snapshot shows you that the JRE is getting registered.

Fig. 2.8(f)
Finally, Java is installed successfully as shown in the snapshot below.

Fig. 2.8(g)
Once you are finished with installation of Java, you get a ‘Thank You’ message (Fig. 2.8(h))
from Oracle Corporation and asking you to register so that you can get alerts, notifications,
special offers, and access to future releases and documentation.
Another random document with
no related content on Scribd:
Sheep,” which were found to be so, and therefore the Devil must
needs have done it. But in this he neither nameth the place, time, nor
Author to avouch it, and therefore all reasonable Men may judge how
palpable a falsity it is, for then if true it would follow that none could
be safe, and that the Devil might kill immediately with swords or
knives, which he cannot do.
2. Whereas he De Lithias. c. 8. p. Observ. 2.
holdeth that the 75.
Devil doth bring or convey the things to be Hist.
injected near unto the place, and that he
offereth filth and poysons to his clients, that thereby he may
fermentally conjoin the Ideas of these formed in the imaginative
faculty with these. If the Devil be taken to be meerly and simply
incorporeal, then he cannot remove matter (as we have before
proved) and so cannot convey the things near to the object; and if he
be taken to be corporeal (as we have asserted) his help is needless,
because the Witches may do it themselves, as we find sufficient
stories of their hideing of strange and poysonous things under the
thresholds of houses and Churches; and to this purpose this same
Author telleth us this story: “A certain person (he saith) did by
custome use to make water in a corner of the Court, whereupon he
was afflicted with a bloody and cruel Strangury. And all the remedy
of the Physicians proved in vain, except that as often as he did drink
of Birch-Ale he did find a signal ease: But as oft as he rose and
walked, and made water in the same place, so often his pains did
return. At the last a pin of old black Oak-wood is espied to be fixed in
the place where he used to make water. Which being pulled forth and
burned he remained free from the bloody Strangury, by drinking Ale
of Birchen-twiggs. Also (he saith) that he remembred, that
Karichterus had written that he had loosed such kind of
inchantments by only pissing through Beesomes of Birch.” Now from
hence it is plain that this making water constantly upon this pin of
old black Oak-wood did cause his bloody Strangury, and that the
pulling of it up and burning of it, was with the help of the Birchen Ale
the cure; but it can no wayes be judged necessary that the Devil
should fix the Oak pin there, but that the Witch might do it himself.
Neither can it be thought to be any power given by the Devil to the
Oaken pin, that it had not by nature, for in probability it will
constantly by a natural power produce the same effect; only thus far
the Devil had a hand in the action, to draw some wicked person to fix
the pin there where the Man was accustomed to make water, thereby
to hurt and torture him, and so was only evil in respect of the end.
3. We observe and affirm that whatsoever Observ. 3.
effects are brought to pass by that which is
commonly called and accounted Witchcraft, if they be not brought to
pass by jugling, confederacy, delusion and imposture (as the most of
them are, if not all) then they are performed either by meer natural
causes, or the strength of the Witches fancy, and most vehement
desire of doing of mischief to those she hateth, or by both joined
together, and that Satan is no further an author or actor, but as he
leadeth and draweth the minds of the Witches to do such
mischievous actions, and pusheth on to seek about to learn of others
such secret poysons, charms, images and other hidden things, that
being used so or so, may produce such destructive ends as their
wicked and diabolical purposes are led to, and in this sense they are
his clients, and bounden vassals, and not otherwise.
4. The stories that he relateth are either Observ. 4.
all to be taken to be true, or none of them;
and if they be all alike equally to be credited, then it will undeniably
follow, that they were all alike produced by natural causes, and so no
need at all of the Devils assistance in performing of them, no more
than by working upon the minds of such as used those natural means
to a wicked and mischievous end. For first he giveth these instances
of things that were very strange that were voided either by vomit or
stool, by the ordinary power of nature, without suspicion of
diabolical cooperation, as the voiding of the piece of the brass
Cannon with its letters, with the Eele wrapped in its secundines: The
Dragon that the Oxe voided by taking three herbs, with a tail like an
Eele, a body like or of leather, with a Serpentine head, and not less
than a Partridge: The knife that the Thieves forced a man to swallow,
which he voided by an Apostume in the side, and was after sound:
also the arrow head of three fingers broad strucken into the back,
and after voided by stool, with diverse such which we recited before.
And that these being solid bodies should have penetrated and passed
through parts that are impatient of wounds, and in which a wound is
mortal, must of necessity be very wonderful, and might as soon and
upon as rational grounds be taken to be diabolical, as those that he
enumerateth to be so: For from these it is manifest that either nature
put to her last pinch doth make penetration of dimensions, or else so
inlarge the pores, that those solid bodies may pass without wound,
which (if seriously considered) is a stupendious operation and effect.
And as there needeth no cooperation of a diabolical power, for the
performing of these, no more needeth there any concurrence of
Devils to the others, that to that purpose he relateth. Only here is all
the difference: these are wrought by the ultimate endeavour of the
Archæus to save life; without the concurrence of external causes; the
others (that are therefore called diabolical) are commonly wrought
for a bad end, namely to hurt or to take away life, and have an
external cause, to wit, the force of the Witches imagination and
strong desire of doing of mischief, which is stirred up to that end by
Satan, and therefore in regard of the end are devilish, though they be
both wrought by the agency of nature, the one in the body of the
imaginant, the other in the body that the Witch intendeth to hurt by
the force of her imagination and vehement desire, whereby a seminal
Idea is created or formed, which is sufficiently operative to
accomplish the end intended.
5. The Syl. Syl. Cent. 10. p. Observ. 5.
arguments that he 556.
bringeth to prove penetration of dimensions to be in nature, or
something equivalent thereunto, seem to be strong and convincing.
For in the generation of things, whosoever shall seriously and strictly
mark, shall find (as he alledgeth) that the spirit of the Archeus
(though not altogether incorporeal) doth in the seeds of things
penetrate it self, and their parts one another, which he further
maketh good by the instance of Gold generated of water; for it must
of necessity be, that more than fifteen parts of water must fall in or
penetrate one another, that from thence one part of Gold may be
made, for weight is not of nothing, but argueth the matter ponderous
in the Ballance. Therefore naturally the water must so oft penetrate
its body as the Gold doth preponderate the water. And though it be
granted that the water hath pores, yet notwithstanding it cannot
contain so much as fourteen times, it whole. And therefore he
irrefragably concludeth: Est ergo ordinarium in natura, quod
aliquæ partes aquæ se penetrent in unicum locum. And this he
backs with an unanswerable story of a Woman that longing for
Muscles, did in greediness eat some of them with the shells twice or
thrice broken with her teeth, and that she brought forth a child with
the same half eaten shells, and a wound in the belly; therefore those
shells had penetrated the stomach, womb and secundines, or
otherwise the force of the Archeus had opened the pores and letten
them pass in an unconceiveable manner. So that if these things be
granted to be true (and we confess we know not how they can be
answered) then there need no diabolical power be brought to solve
the injecting of strange things into mens bodies, seeing nature is
sufficient of it self, and therefore we can allow no power at all unto
Devils in effecting these things (if they be truly done, and be not
delusions) but only in drawing the minds of the Witches to these
wicked and mischievous courses; and therefore the Lord Bacon said
profoundly and wisely these words: Ut in operationibus illis earumq;
causis error cavendus est, ita quoq; danda vel imprimis opera est,
ne effecta nobis imponant, temere judicantibus talia esse, quæ
eousq; nondum processerunt. Sic prudentes judices, præscripta
velut norma, fidem haberi temere nolunt confessionibus sagarum,
nec etiam factorum contra illas probationi. Sagas enim turbat
imaginationis vertigo, ut putent se illud facere, quod non faciunt,
populumq; hîc ludit credulitas, ut naturæ opera imputent fascino.
6. And to confirm this point he addeth far Observ. 6.
more stupendious matters of fact than the
former, of things that were within, being taken to without or invisibly
conveyed away, as the woman at Mechlin that saw the Souldier in a
conflict lose his hand, and forthwith brought forth a Daughter
wanting an hand, which was never found, and the wench died of the
Hæmorrhage. Another at Antwerpe seeing a Souldier begging with
his right arm shot off and bloody, forthwith brought forth a Daughter
wanting the right arm whose bloody shoulder the Chirurgeon cured,
and she was married after; and that the arm was never found, neither
did there appear any bones or putrefied matter into which the arm
might waste. Also another Woman going to see the Decollation of
thirteen men; did soon after bring forth a mature Child with a bloody
neck, the head no where appearing. I confess it would rack the
judgment even of the most credulous to the highest pitch to believe
these unparallel’d Stories; but the Author relating them as of his own
knowledge, and being a person of unquestionable veracity, I cannot
conceive how they can rationally be denied, especially finding Mr
Boyle to affirm, that in those experiments (much more relations of
matters of fact) that Helmont avouched upon his own knowledge, he
durst be his Compurgator. Who would not believe but that these
things could never have been done, but by a supernatural and
Diabolical power, but that this Author (to which all judicious persons
in reason may adhere) doth utterly deny, that the arm was either
pull’d away or conveyed none can tell whither, by Satan, and
therefore that in such a strange Paradox, trivial reasons are not to be
allowed; and it were too much sloathfulness to ascribe all effects unto
Satan, of which we are ignorant. And therefore if an hand, an arm,
nay an whole head, could be separated from the rest of the body, and
conveyed forth of the Womb by the Archeus or natural spirit,
thereunto excited by the impression of horror and terror in the
Women: In like manner by the same power of the natural spirit of
man or woman, excited by a vehement and fierce imagination to
revenge and to do mischief, may strange things be injected (if there
can be any sound proof of such a matter of fact) into the bodies of
such men or women as the Witches intend to do hurt unto, and yet
Satan hath no more hand in it, but only as a spiritual agent to move
the wills of those wicked and malicious people to do mischief unto
those that they hate, though without cause. And the great secret of
that which may be called Witching, is the learning of others, who
likewise have had it by tradition, the great force of imagination, and
the natural spirit with the ways and means how to excite it and exalt
it; herein stands the mystery of all Magick, and it becomes only evil
in the use and application, and they are to be condemned that use it
to such devillish ends, even as those that use those good Creatures
that nature doth produce to poysonous, wicked, and destructive
purposes. And lastly, here we may note, that if things or bodies that
are without may be injected into the bodies of others, by the force of
exalted, imagination and a vehement desire, then the same power
that doth inject them through skin, flesh and bones, must also be
able to bring them near to the place, and need not at all the
assistance of Satan, because it is far easier to carry them near the
place, than to thrust them into the body; and so this Author hath
here introduced the Devils aid to bring them to the place to no
purpose, and never yet proved either by reason or matter of fact, that
ever Satan did any such thing, and so is a meer supposition without
proof.
7. The other De occult. nat. Observ. 7.
matters of fact that mirac. l. 2. c. 40. p.
he relateth are 325.
prodigious, and Hist. De Tumor. l. 6. c.
are brought to prove that Satan is an actor 19. p. 158.
to convey these strange things into the bodies of men, and are these.
A piece of an Oxe Hide taken forth of a mans Arm, so also that
Equuleum, a Wood-Horse, or a four-footed board with a wheel and
ropes twice as broad as the gullet. Another that vomited up perhaps
two thousand pins conglomerated together, with filth and hairs;
another that vomited up, he being present, wooden Chips that had
been cut off with the Hatchet in smoothing of wood, with much slime
to the bigness of two fists, of which we shall note these Conclusions.
1. It doth no way appear (if these things be granted to be true, both
for matter and manner) neither doth he offer to prove it, that these
are any more than the former Diabolical, but only in the end, because
they are for the hurt and destruction of mankind and not otherwise;
and there being no proof of the Devils Cooperation any further but in
working upon the minds of those that are agents and instruments to
bring these things to pass, we may very well reject those things that
are supposed, but not proved. 2. The ejecting or voiding of such
strange things as here he hath related, doth not necessarily suppose
their injection or thrusting in, because they may be bred there by
natural Causes, so Worms of many sorts and strange Figures, also
Frogs, Dracunculos and Askers have been voided, and doubtlesly
bred there by natural causes, and were not injected or thrust in, and
for proof of this I refer the Reader to the relations of learned
Schenchius lib. 3. p. 363. of those strange sorts of Worms and other
Creatures that he from divers Authors sheweth have been vomited
up, which without all scruple, were not injected, but bred there. To
confirm this and to prove what strange things are sometimes bred in
Apostumes and Tumors, we shall translate a passage or two, and first
take this from Levinus Lemnius that learned and famous Physician
of Zeland, who writeth thus: “Also forth of sordid Ulcers and
Impostures (he saith) we have known that the fragments of nails,
hairs, shells, little bones and stones have been taken forth; which
were concreted and grown together forth of putrid humours: As also
little creatures, worms with tails, and little beasts of an
unaccustomed form, cast up by vomiting, especially in those who
were oppressed with contagious diseases, in whose urines I have
often discerned to swim little Animalcles like to Pismires, or to those
creatures we observe in the estival months to move in the celestial
dew here in England we call it Woodsoar, or Cuckow-spittle.” Take
another from that learned and expert Chirurgeon Ambrosius Paræus
where he is speaking of strange tumors, in these words: “Also in
these tumors being opened thou maist see bodies of all kinds, and far
differing from the common matter of Tumors, as stones, chalk, sand,
coals, cockles, ears of corn, hay, horn, hairs, flesh as well hard as
spongious, grisles, bones and whole Animalcles, as well living as
dead. The generation of which things (by the corruption and
alteration of the humors) will not much astonish us, if we consider,
that even as nature hath framed Man as a Microcosm forth of all the
seeds and elements of the whole great world, that he might be as it
were the lively image of that great world: So in that Microcosm,
nature hath willed, that all the species of all motions and actions
might be manifest, nature being never idle in us, as long as matter is
not a wanting to work upon.” So that it is most plain that these
strange things may be bred within, and so the opinion of injecting
them, is but a meer figment. 3. Neither can the vomiting up of such
strange things as he relateth, conclude necessarily that they were
injected either by the power of Satan or the Witch, because they may
be performed by jugling, sleight of hand, confederacy and the like, as
was manifest in the Boy of Bilson, and diverse that we have known,
that had made some numbers of others to believe that they had
voided strange things, as pins, needles, crooked-knitting-pricks,
moss, nails, and the like; but upon a strickt search, have but proved
delusions and sleight, such as our common Hocus Pocus Men use,
when they make the people believe they swallow a long pudding of
white tinn, and again pull it forth of their mouths, or in pulling
ribbins, or laces of diverse colours forth of their throats. 4. And again
the most of these relations are but commonly taken upon trust from
the affirmations of the by-standers who might be confederate parties,
or ignorant persons, and so easily deceived; and it appeareth not that
Helmont was by at the very instant when the children vomited up the
wooden horse, or four-footed board, but that it was the by-standers
that drew it forth, who might be parties to the cheat, or be
themselves deluded, and so aver it pertinaciously to others. For I
have in my practice known a young Wench about 9 or 10 years old,
who that she might be pittied and have an idle life, had made her
Father and Mother believe that quick worms came forth at her ear,
and also I taking her into mine own house she had perswaded all the
family that it was true, and did often open her head-cloaths, and
holding down her ear a quick worm would drop forth of the hair, who
notwithstanding by diligent watching, was found out to get them
privately from under stones or wood, and so did cunningly convey
them into her hair, but being discovered, was by due correction
reclaimed, and so the wonder ceased. And it is as common to mistake
things, either by absolute judging them to be such a thing indeed,
when it hath but some slender resemblance of it, or by judging a
thing to be really so, because of such a name but metaphorically
given unto it; so it is usual to call a Carcinoma in the highest degree
Lupus or a Wolf, because as a Wolf is a most voracious creature, so
this ulcer is the most devouring of all others; and therefore have we
known after that such have been by incision eradicated by our selves
and others, and exposed to the view of the vulgar people, they would
presently most earnestly affirm to others that they had seen it, and
that it was a living creature, and had mouth, eyes and ears; so far will
ignorant mistake induce credulity.
8. That the force Syl. Syl. Cent. 10. p. Observ. 8.
of imagination 583.
accompanied with the passions of horror, fear, envy, malice, earnest,
desire of revenge, and the like, is great upon the body imaginant, as
also upon the fœtus in the womb, is acknowledged by all. But that it
can at distance work upon another body, though denied by Fienus
and the whole rabble of the Schoolmen, yet is strongly proved by this
learned Author, and allowed of by all others that truly understood
the operations of nature, which we also take to be a certain truth, and
do assert that if those people that are esteemed Witches, do really
and truly (of which we utterly doubt) inject any of these strange
things into the bodies of men, that they are brought to pass meerly
by the imagination of the Witch, and the Devil acteth nothing in it at
all, but the setting of his will upon that mischief. As for the handling
the dispute concerning the manner of the injecting of these strange
things, so strongly pursued by this Author, Sennertus and others, we
shall totally supersede and suspend our judgment, until the ὅτι be
sufficiently proved (which yet lies under water, and unseen) and then
it will be time enough to dispute the manner, when the matter is
certainly made evident. Therefore we will shut up this with that
modest and grave advice of the Lord Bacon in these words: Ideo
cogemur in hac inquisitione ad nova experimenta confugere; ubi
directiones tantùm eorum præscribi possunt, non ulla positiva in
medium adferri. Si quis putet subsistendum nobis fuisse, donec
tentamentis res penitus innotuisset, (ut fecisse nos ubiq; probant
alii tituli) sciat dubia nos fide amplecti quæcunq; imaginationis
effecta circumferuntur, animum tamen esse illa per otium exigere
ad Lydium veritatis lapidem, id est, experimentorum lucem.
CHAP. XIII.

That the ignorance of the power of Art and Nature and such like
things, hath much advanced these foolish and impious opinions.

The opinions that we reject as foolish and impious are those we have
often named before, to wit, that those that are vulgarly accounted
Witches, make a visible and corporeal contract with the Devil, that he
sucks upon their bodies, that he hath carnal copulation with them,
that they are transubstantiated into Cats, Dogs, Squirrels, and the
like, or that they raise tempests, and fly in the air. Other powers we
grant unto them, to operate and effect whatsoever the force of
natural imagination joyned with envy, malice and vehement desire of
revenge, can perform or perpetrate, or whatsoever hurt may be done
by secret poysons and such like wayes that work by meer natural
means.
And here we are to shew the chief causes that do and have
advanced these opinions, and this principally we ascribe to mens
ignorance of the power of Nature and Art, as we shall manifest in
these following particulars.
1. There is nothing more certain than, that how great soever the
knowledge of Men be taken to be, yet the ultimate Sphere of natures
activity or ability is not perfectly known, which is made most
manifest in this, that every day there are made new discoveries of her
secrets, which prove plainly that her store is not yet totally
exhausted, nor her utmost efficiency known. And therefore those
Men must needs be precipicious, and build upon a sandy foundation,
that will ascribe corporeal effects unto Devils, and yet know not the
extent of nature, for no Man can rationally assign a beginning for
supernatural agents and actions, that does not certainly know where
the power and operation of nature ends.
2. And as it is thus in general, so in many particulars, as especially
in being ignorant of many natural agents that do work at a great
distance, and very occultly, both to help, and to hurt, as in the
weapon salve, the Sympathetick powder, the curing of diseases by
mumial applications, by Amulets, Appensions and Transplantions,
which all have been, and commonly are ascribed unto Satan, when
they are truly wrought by natural operations. And so (as we have
sufficiently manifested before) by many strange, and secret poysons
both natural and artificial, that have no bewitching power in them at
all, but work naturally, and only may be hurtful in their use through
the devilishness of some persons that use them to diverse evil ends.
3. There is nothing that doth more clearly manifest our scanted
knowledge in the secret operations of nature, and the effects that she
produceth, than the late discoveries of the workings of nature, both
in the vegetable, animal and mineral Kingdoms, brought dayly to
light by the pains and labours of industrious persons: As is most
evident in those many elucubrations, and continued discoveries of
those learned and indefatigable persons that are of the Royal Society,
which do plainly evince that hitherto we have been ignorant of
almost all the true causes of things, and therefore through blindness
have usually attributed those things to the operation of Cacodemons
that were truely wrought by nature, and thereby not smally
augmented and advanced this gross and absurd opinion of the power
of Witches.
4. Another great means in advancing De occult. Philos. l.
these Tenents hath been Mens supine 1. c. 2.
negligence in not searching into and experimenting the power of
natural agents, but resting satisfied in the sleepy notions of general
rules, and speculative Philosophy. By which means a prejudice hath
been raised against the most occult operations of nature, and natural
magick (which is (as Agrippa truly said) “The comprizer of great
power, full of most high mysteries, and containeth the most
profound contemplation, nature, power, quality, substance and
virtue of most secret things, and the knowledge of all nature) to be
condemned, as the work of the Devil and hellish fiends, which is the
handmaid and instrument of the Almighty.” And from this diabolical
pit of the ignorance of the power of nature (especially when assisted
by art) have sprung up those black and horrid lies in the mouths of
Erastus, Conringius and above all of Kircherus, denying the
possibility of the transmutation of metals, by the power of Art and
Nature, and ascribing the performance thereof by Paracelsus,
Lullius, Sendinogius and others to the Devil; so malevolent do men
grow when they are led by nescience and ignorance.
5. The ignorance of the strange and Vid. Theatr. Chym.
wonderful things that Art can bring to pass Vol. 5. p. 943.
hath been no less a cause, why the most admirable things that Art
bringeth to pass by it are through blind ignorance ascribed unto
Devils, for so have many brave learned Artists, and Mechanicians
been accused for Conjurers, as happened to Roger Bacon, Dr. Dee,
Trithemius, Cornelius Agrippa, and many others, when what they
performed was by lawful and laudable art. The strange things that
the Mathematicks and Mechanicks can perform are hardly to be
enumerated, of which were those most wonderful catoptrical glasses
mentioned by Nicero, Aquilonius, Baptista Porta and many others,
those wonderful engines in the shape of Birds, Men, Beasts, and
Fishes that do move, sing, hiss and many such like things mentioned
by Heron of Alexandria, and our Countryman Dr. Fludd; and those
that would have more ample satisfaction concerning the stupendious
things that are produced by art, may receive most large satisfaction
in reading that most learned and elaborate Epistle written as a
preface before the Book of Johannes Ernestus Burgravius called
Biolychnium vel de lampade vitæ et mortis, by Marcellus
Vranckheim Doctor of both laws, as also in reading that profound
and mysterious piece written by Roger Bacon, de admirabili
potestate artis et naturæ, et de nullitate magiæ, with the learned
notes of Dr. Dee upon it, of which he saith this: Ut videatur quod
omnis potestas magica sit inferior his operibus et indigna. And
therefore there can be nothing more unworthy, than for any man,
that pretendeth to any portion of reason, so far to dote, or suffer
himself to be led with ignorance and rashness, as to ascribe those
strange things that Nature and Art, or both joined together do
produce, unto Devils: And yet there is nothing that is more common
not only by the blind vulgar, but even by those that otherwise would
be accounted learned, and wise enough; pride and folly attendeth the
most of the Sons of Men.
6. Another gross mistake there is, in Hist.
supposing those strange things that are
performed by vaulters, tumblers, dancers upon ropes, and such like,
not possible to be done but by the assistance of the Devil, when they
are altogether brought to pass and effected by use, custome, exercise,
nimbleness and agility of body. And yet we have known some not
only of the popular rank, but many that thought themselves both
wise, learned and religious that have been so blind as to father these
things upon Devils and seriously to seem to believe, that the actors of
these things had made a league and compact with the Devil, by
whose help they performed them. And I do remember that a pretty
active young man, within these few years went about in this North
Countrey with a neat Bay Mare for money to shew tricks, which were
very odd and strange, for if she had been blindfolded, and several
pieces of money taken from several persons, and wrapped in a
cloath, the Mare would have given every one their own piece of
money; and this and many other feats she plaid, were not only by the
common people, but by others that should have been more wise,
judged to be performed by no other means but by the Devil, and
some were so stark mad as to believe and affirm that the Mare was
not a natural one, but that it was the Devil that plaid those strange
tricks in the shape of a Mare: when more sober judgments knew that
they were performed by the masters eye, and rod directing the Mare.
Error & credulitas multum in hominibus possunt.
7. In like manner are often both those that are learned, as well as
the vulgar most wofully imposed upon by the odd and strange feats
performed by Legierdemain, sleight of hand, and by wonderful
things brought to pass by subtile and cunning Impostors that act by
confederacy, and the like, of which we have given some instances
before in this treatise. And it was no evil piece of service, that Master
Scot did in his book of the discovery of Witchcraft, when he laid open
all the several tricks of Legierdemain and sleight of hand, thereby to
undeceive the ignorant multitude; and that is no less praise-worthy
that is performed by the Author of that little treatise called Hocus
Pocus junior, where all the feats are set forth in their proper colours,
so that the most ignorant may see how they are done, and that they
are miracles unknown, and but bables being discovered, which
treatise I could commend to be read of all Witchmongers and vain
credulous persons, that thereby their ignorance may be laid open,
and they convinced of their errors.
8. The ignorance or mistaking of these things, joyned with the
notions Men have imbibed from their infancy, together with
irreligious education, are the true and proper causes, that make so
many ascribe that power to Devils and Witches, that they neither
have, or ever had, or can ever bring into act. And therefore it
behoveth all that would judge aright of these abstruse matters, to
labour to understand the secret operations of nature, and the strange
works of art, to divest themselves of their false imbibed notions, and
truely and rightly to understand the Articles of the Christian Faith, to
be daily conversant in reading the Scriptures, they will then be more
fit to judge of these things, and not to call light darkness, nor
darkness light.
CHAP. XIV.

Of diverse Impostures framed and invented to prove false and


lying miracles by, and to accuse persons of Witchcraft, from
late and undeniable authorities.

In the treatise preceeding we have often made mention of delusions


and Impostures, which we shall largely handle in this place: and
though Mr. Glanvil, and others do object, that though many
pretended possessions or Witchcrafts have been proved to be meer
couzenings and impostures, yet therefore it will not follow that all are
so. To which we shall render these answers.
1. If it do not necessarily conclude, that they are all impostures, yet
it gives a most shrewd cause of dubitation that they may be so. And
the objection depends not upon a necessary connexion betwixt the
subject and predicate, for some being direct and palpable
Impostures, it is not of necessity, but by contingency or accident that
the others are not so, and ought first to have been proved, which
never yet was performed.
2. But we affirm that a general conclusion drawn from an inductive
argument is good and sound, where no instance can be clearly made
out to the contrary. But as yet no true instance, really and faithfully
attested, hath ever been brought to prove that any of these things
that we deny, were ever effected by diabolical power. For who were
ever by and present, that were persons of sincerity and sound
judgment, that could truly testifie and averr that the Devil in a visible
and corporeal shape made a contract with the Witch, or that he suckt
upon his, or her body, or that he had carnal copulation with them, or
that saw when the Witch was really changed into a Dog or a Cat, or
that they flew or were carried in the air? Seeing no instance can be
given to prove any of these to be undoubted truths, it must needs
follow that they are meer figments, or at the best all but absolute
Impostures. And again it is but precarious, and petitio principii, to
imagine that any persons have vomited up or voided strange things
that saw or knew that they were injected by Devils, for they were
either naturally bred there, or else were meer Impostures and
delusive Juglings.
And therefore we shall propose some Histories of strange and
prodigious cheats and Impostures from late and unquestionable
authorities, whereby all the rest may be judged and discerned; of
which take this for one.
“1. Elizabeth Vid. Stat. Pulton, Hist. 1.
Barton of Kent (by 25. year Henr. 8. c.
those that 12.
laboured to cry up The Pope. Vid Chron.
her horrible cheats for miracles, otherwise Hollingshead. Stow
An. Hen. 8. 25. p.
called the holy Maid of Kent) and others 1013.
were in the twenty fifth year of King Henry
the Eighth attainted of High Treason, for that under colour of
hypocrisie, Revelations and false Miracles practised by the said
Elizabeth, they conspired to impugne and slander the divorce
between the King and Queen Katherine his first Wife, and the last
Marriage between him and Queen Anne his second Wife, to destroy
the King, and to deprive him of his Crown.” Her false and feigned
miracles, and the subtile and cunning contrivances that were brought
to pass by the help of her confederate accomplices, and her and the
others open confession of them may be found at large in
Hollingshead, Stow, and the writings of Mr. Lambert, whither for
brevities sake I remit my reader, and shall only give it here in the
words of Speed, which are these: “The Romanists (he saith) much
fearing that Babel would down, if Queen Anne might be heard
against wicked Haman, sought to underprop the foundations thereof
with certain devices of their own: and that the same might pass
without note of suspicion, they laid their forgery even upon Heaven it
self; whose pretended oracle Elizabeth Barton (commonly called the
holy Maid of Kent) was made to be; and the pillars of this godless
Fabrick were Edward Bocking a Monk by profession, and Doctor of
Divinity, Richard Masters Parson of Aldington, the Town wherein
she dwelt; Richard Deering a Monk, Hugh Rich a Friar, John
Adestone and Thomas Abell Priests, put to their helping hands; and
Henry Gould Batchelor of Divinity, with John Fisher the reverend
Father of Rochester imployed their pains to dawb these downfalling
walls with their untempered morter. The Scribes that set their pens
for her miracles, were Edward Thwaites Gentleman, and Thomas
Lawrence Register, besides Haukherst a Monk, who writ a letter that
was forged to be sent her from Heaven; And Richard Risby and
Thomas Gould were the men that dispersed her miracles abroad to
the world. This holy Maid Elizabeth made a Votaress in Canterbury,
was taught by Bocking her Ghostly Father, and suspected Paramour,
to counterfeit many feigned trances, and in the same to utter many
virtuous words for the rebuke of sin, under which more freely she
was heard against Luthers doctrine, and the Scriptures translation,
then desired of many: neither so only, but that she gave forth from
God and his Saints by sundry suggestive Revelations, that if the King
proceeded in his Divorce, and second Marriage, he should not raign
in his Realm one month after, nor rest in Gods favour the space of an
hour. But the truth discovered by Gods true Ministers, this oracle
gave place as all other such did, when Christ by his death stopped
their lying mouths: For her self and seven of her disciples were
executed for Treason at Tiburn, and the other six put to their fines
and imprisonment.” To which he subjoineth this story of the like
nature. “With the like counterfeit Revelations and feigned
predictions this generation of hypocrites had brought Edward Lord
Stafford Duke of Buckingham, unto his unhappy end, by the working
of John de la Court his own Confessor, together with Nicholas
Hopkins a Monk of the Carthusian Order in the Priory of Henton in
Somersetshire, who by his visions from Heaven forsooth, heartned
him for the Crown; But before his own Coronet could aspire to that
top, he worthily lost both head and all upon Tower-hill for his
Treason, Anno Domini 1521. Unto such sins the world was then
subject, and into such conceits their reputed holiness had brought
them, not only among the simple and unlettered, but even with them
that seemed to be learned indeed: For by certain predictions
foreshewing a great deluge, Prior Bolton of S. Bartholomews in
London, was so fearful that he built himself a house upon the height
of Harrowhill, storing it with provisions necessary to keep himself
from drowning in Anno Dom. 1524.
2. And that we Stow’s Chron. p. Hist. 2.
may be certified 678.
how frequent and common these counterfeited Impostures have
been, and yet are practised, take this other from undoubted
authority. “The 15 of August being Sunday in the 16 of the raign of
Queen Elizabeth, Agnes Bridges a Maid about the age of 20 years,
and Rachel Pinder a Wench about the age of 11 or 12 years, who both
of them had counterfeited to be possessed by the Devil (whereby they
had not only marvellously deluded many people both Men and
Women, but also diverse such persons, as otherwise seemed of good
wit and understanding) stood before the Preacher at Pauls-cross;
where they acknowledged their hypocritical counterfeiting with
penitent behaviours, requiring forgiveness of God and the world, and
the people to pray for them. Also their several examinations and
Confessions were there openly read by the Preacher, and afterwards
published in print, for posterity hereafter to beware of the like
deceivers.” From whence we may take these two Observations.
1. We may from hence note, how subject Observ. 1.
the nature of man is both to deceive and to
be deceived, and that not only the common people, but also the wiser
and more learned heads may most easily be imposed upon. And, that
therefore in things of this nature, and the like, we cannot use too
much circumspection, nor use too much diligence to discover them.
2. We may note, that when such strange Observ. 2.
Impostures or false Miracles are pretended,
there is commonly some sinister and corrupt end aimed at, under the
colour of Religion, and that those that are most ready to publish such
things as true Miracles and Divine Revelations, are generally those
that did complot and devise them. And therefore the greater number
they be that cry them up, and the more esteem the persons are of
that blow abroad such things, the greater suspicion we ought to have
of the falsity and forgery of them. Always remembring that the
greater the fame and number of the persons are that conspire and
confederate together, the greater things they may bring to pass, and
be more able to deceive, as was manifest by the Priests attending the
Oracles; who, though they laboured to father their predictions upon
some Deity, yet it was manifest that it was nothing else, but their
own Confederacy, Impostures and Juglings.
3. But these Vid. A Book called, Hist. 3.
Diabolical A discovery of
Counterfeitings of fraudulent
practices
possessions, and concerning
the maintaining of pretended
the power of possessions.
dispossession and Vid. ibid. Dialog. 11.
casting forth of Devils, was not only upheld p. 352.
and maintained by the Papists to advance
their superstitious courses; but also in the said time of Queen
Elizabeth, there were divers Non-Conformists, to gain credit and
repute to their way, that did by publick writing labour to prove the
continuation of real possessions by Devils, and that they had power
by fasting and Prayer to cast them out. Of which number were one
Mr Darrell and his Accomplices, who not only writ divers Pamphlets
in the positive defence of that opinion, but also published certain
Narrations of several persons, that they pretended were really
possessed with Devils, which were cast forth by their means in using
Fasting and Prayer. Which writings were answered by Mr Harsnet
and others, and their Theory not only overthrown, but their practice
discovered to be counterfeiting and Imposture. Whereupon there
were divers persons suborned to feign and counterfeit possessions,
as William Sommers of Nottingham, who by the Exorcists was
reported to have strange fits, passions and actions; which are at large
described and set forth in that learned Treatise, Dialogical
Discourses of Spirits and Devils, written about the same time by
John Deacon and John Waller, Ministers, and of divers other
persons who likewise pretended the same counterfeit possessions.
And though the said forged and feigned possessions were strongly
maintained by their Abettors, and the matters of fact audaciously
asserted to be true; yet after the said Darrell and his Accomplices
were examined by the Queens Commissioners, all was made
apparent to be notorious counterfeiting, cheating and imposture,
both by the confession of Sommers himself, and by the Oaths of
several Deponents. Neither was that discourse containing the certain
possession of seven persons in one Family in Lancashire, at
Cheworth in the Parish of Leigh, in the Year 1594. (though believed
by many for a truth, because of the streight tale told by the said
Darrell in that Narrative) of any better grain, but full of untruths,
impossibilities, absurdities and contradictions.
4. Our next Vid. The cunning of Hist. 4.
instance shall be a the Boy of Bilson, p.
most strange 55.
imposture acted in the time of King James, and in a manner known
unto the whole Nation; that is of the Boy of Bilson in Staffordshire,
in the year 1620. by name William Perry, whose condition as he had
been taught, and so left by the Popish Priests, take as followeth. “This
Boy being about thirteen years old (but for wit and subtilty far
exceeding his age) was thought by divers to be possessed of the Devil,
and bewitched, by reason of many strange fits and much distemper,
wherewith he seemed to have been extreamly affected. In those fits
he appeared both deaf and blind, writhing his mouth aside,
continually groaning and panting, and (although often pinched with
mens fingers, pricked with Needles, tickled on his sides, and once
whipped with a Rod, besides other the like extremities) yet could he
not be discerned by either shrieking or shrinking to bewray the least
passion or feeling. Out of his fits he took (as might be thought) no
sustenance which he could digest, but together with it, did void and
cast out of his mouth, rags, thred, straw, crooked pins, &c. Both in
and out of his fits his belly (by wilful and continual abstinence
defrauding his own Guts) was almost as flat as his back, besides, his
throat was swoln and hard, his tongue stiff and rolled up towards the
roof of his mouth, insomuch that he seemed always dumb, save that
he would speak once in a Fortnight or three Weeks, and that but in
very few words.
“Two things there were which gave most just cause of presumption
that he was possessed and bewitched; one was that he could still
discern when that Woman (which was supposed to have bewitched
him) to wit Jone Cocke was brought in to any room where he was,
although she were secretly conveyed thither, as was one time tryed
before the Grand Jury at Stafford: The second, that though he would
abide other passages of Scripture, yet he could not indure the
repeating of that Text, viz. In the beginning was the word, &c. Jo. 1.
ver. 1. but instantly rolling his eyes and shaking his head, as one
distracted, he would fall into his usual fits of groaning, panting,
distraction, &c. In which plight he continued many months, to the
great wonder and astonishment of thousands, who from divers parts
came to see him.” Thus much of his cunning.
Yet notwithstanding, this most devillish and cunningly contrived
counterfeiting and dissimulation was discovered and fully detected
by the sagacity of that pious and learned person, Dr Thomas Morton
then Bishop of Coventry and Lichfield: To whose memory I cannot
but owe and make manifest all due respect, because he was well
known unto me, and by the imposition of whose hands I was
ordained Presbyter when he was Bishop of Durham, and also knew
his then Secretary, Mr Richard Baddeley, who was the Notary, and
writ the examination of this crafty Boy. The manner how such a
doubtful and intricate piece of Imposture was found out and
discovered, you may read at large in the Treatise called a Discourse
concerning Popish Exorcising. And his publick Confession we shall
give in the Authors own words: “He was finally brought again to the
Summer Assizes held at Stafford, the 26. of July, Anno 1621. where
before Sir Peter Warburton and Sir Humfrey Winch Knights, his
Majesties Justices of Assize, and the face of the County and Country
there assembled, the Boy craved pardon first of Almighty God, then
desired the Woman there also present to forgive him; and lastly,
requested the whole Country whom he had so notoriously and
wickedly scandalized, to admit of that his so hearty Confession for
their satisfaction.
“And thus it pleased God (he saith) to open the eyes of this Boy
(that I may so say) luto with the Clay of the Romish Priests lewd
Impostures, and sputo with the spittle of his own infamy, to see his
errors and to glorifie the God of truth. And though many such
Impostures as this have in several ages been hudled up in darkness
and recorded for true stories, by those that were Partisans to them
and Confederates with them, yet doubtless were but of the same
stamp with this, and might all as well have been discovered, if the
like care, skill and industry had been used.
5. No less Vid. The Hist. 5.
villanous, bloody arraignment and
and Diabolical, tryal of Witches at
Lancaster, 1612.
was the design of
Thompson alias Southworth, Priest or Jesuit, against Jennet Bierley,
Jane Southworth, and Ellen Bierly of Samesbury in the County of
Lancaster, in the year 1612. the sum of which is this. “The said
Jennet Bierley, Ellen Bierley, and Jane Southworth, were Indicted at
the Assizes holden at Lancaster upon Wednesday the nineteenth of
August, in the year abovesaid, for that they and every of them had
practised, exercised, and used divers devillish and wicked Arts, called
Witchcrafts, Inchantments, Charms and Sorceries, in and upon one
Grace Sowerbutts. And the chief witness to prove this was Grace
Sowerbutts her self, who said that they did draw her by the hair of
the head, and take her sense and memory from her, did throw her
upon the Hen-roost and Hay-mow; did appear to her sometimes in
their own likeness, sometimes like a black Dog with two feet, that
they carried her where they met black things like men that danced
with them, and did abuse their bodies; and that they brought her to
one Thomas Walsham’s House in the night, and there they killed his
Child by putting a nail into the Navil, and after took it forth of the
Grave, and did boil it, and eat some of it, and made Oyl of the bones,
and such like horrid lies.” But there appearing sufficient grounds of
suspicion that it was practised knavery, the said Grace Sowerbutts
was by the wisdom, and care of Sir Edward Bromley Knight, one of
his Majesties Justices of Assize at Lancaster, appointed to be
examined by William Leigh and Edward Chisnal Esquires, two of his
Majesties Justices of peace in the same County, and so thereupon
made this free confession. Being demanded “whether the accusation
she laid upon her Grandmother, Jennet Bierley, Ellen Bierley and
Jane Southworth, of Witchcraft, viz. of the killing of the child of
Thomas Walshman, with a nail in the Navil, the boyling, eating and
oyling, thereby to transform themselves into divers shapes, was true?
She doth utterly deny the same, or that ever she saw any such
practises done by them. She further saith, that one Mr. Thompson,
which she taketh to be Mr. Christopher Southworth, to whom she
was sent to say her prayers, did perswade, counsel and advise her, to
deal as formerly hath been said against her said Grandmother, Aunt
and Southworths Wife.
“And further she confesseth, and saith, that she never did know, or
saw any Devils, nor any other visions, as formerly hath been alledged
and informed.
“Also she confesseth, and saith, that she was not thrown, or cast
upon the Hen-roust, and Hay-mow in the Barn, but that she went up
upon the Mow by the wall side. Being further demanded whether she
ever was at the Church, she saith, she was not, but promised
hereafter to go to Church, and that very willingly; of which the
author of the relation gives this judgment.
“How well (he saith) this project, to take away the lives of three
innocent poor creatures by practice and villany, to induce a young
Scholar to commit perjury, to accuse her own Grandmother, Aunt,
&c. agrees either with the title of a Jesuit, or the duty of a religious
Priest who should rather profess sincerity and innocency, than
practise treachery! But this was lawful, for they are Hereticks
accursed, to leave the company of Priests, to frequent Churches, hear
the word of God preached, and profess religion sincerely.”
6. But we shall shut up the relating of Hist. 6.
these prodigious and hellish stories, of these
kind of couzening and cheating delusions and impostures, with one
instance more that is no less notorious than these that we have
rehearsed. About the year 1634 (for having lost our notes of the
same, we cannot be so exact as we should) there was a great
pretended meeting of many supposed Witches at a new house or
barn, in Pendle Forest in Lancashire, then not inhabited, where (as
the accusation pretended) some of them by pulling by a rope of Straw
or Hay, did bring Milk, Butter, Cheese, and the like, and were carried
away upon Dogs, Cats or Squirrels. The informer was one Edmund
Robinson (yet living at the writing hereof, and commonly known by
the name of Ned of Roughs) whose Father was by trade a Waller, and
but a poor Man, and they finding that they were believed and had
incouragement by the adjoyning Magistrates, and the persons being
committed to prison or bound over to the next Assizes, the boy, his
Father and some others besides did make a practice to go from
Church to Church that the Boy might reveal and discover Witches,
pretending that there was a great number at the pretended meeting,
whose faces he could know; and by that means they got a good living,
that in a short space the Father bought a Cow or two, when he had
none before. And it came to pass that this said Boy was brought into
the Church of Kildwick a large parish Church, where I (being then
Curate there) was preaching in the afternoon, and was set upon a
stall (he being but about ten or eleven years old) to look about him,
which moved some little disturbance in the Congregation for a while.
And after prayers I inquiring what the matter was, the people told
me that it was the Boy that discovered Witches, upon which I went to
the house where he was to stay all night, where I found him, and two
very unlikely persons that did conduct him, and manage the
business; I desired to have some discourse with the Boy in private,
but that they utterly refused; then in the presence of a great many
people, I took the Boy near me, and said: Good Boy tell me truly, and
in earnest, did thou see and hear such strange things of the meeting
of Witches; as is reported by many that thou dost relate, or did not
some person teach thee to say such things of thy self? But the two
men not giving the Boy leave to answer, did pluck him from me, and
said he had been examined by two able Justices of the Peace, and
they did never ask him such a question, to whom I replied, the
persons accused had therefore the more wrong. But the Assizes
following at Lancaster there were seventeen found guilty by the Jury,
yet by the prudent discretion of the Judge, who was not satisfied with
the evidence, they were reprieved, and his Majesty and his Council
being informed by the Judge of the matter, the Bishop of Chester was
appointed to examine them, and to certifie what he thought of them,
which he did; and thereupon four of them; to wit Margaret Johnson,
Francis Dicconson, Mary Spenser, and Hargrieves Wife, were sent
for up to London, and were viewed and examined by his Majesties
Physicians and Chirurgeons, and after by his Majesty and the
Council, and no cause of guilt appearing but great presumptions of
the boys being suborned to accuse them falsely. Therefore it was
resolved to separate the Boy from his Father, they having both
followed the women up to London, they were both taken and put into
several prisons asunder. Whereupon shortly after the Boy confessed
that he was taught and suborned to devise, and feign those things
against them, and had persevered in that wickedness by the counsel
of his Father, and some others, whom envy, revenge and hope of gain
had prompted on to that devillish design and villany; and he also
confessed, that upon that day when he said that they met at the
aforesaid house or barn, he was that very day a mile off, getting
Plums in his Neighbours Orchard. And that this is a most certain
truth, there are many persons yet living, of sufficient reputation and
integrity, that can avouch and testifie the same; and besides, what I
write is the most of it true, upon my own knowledge, and the whole I
have had from his own mouth more than once.
Thus having brought these unquestionable Histories to manifest
the horrid cheats and impostures that are practised for base, wicked
and devillish ends, we must conclude in opposing that objection
proposed in the beginning of this Chapter, which is this: That though
some be discovered to be counterfeitings and impostures, yet all are
not so, to which we further answer.
1. That all those things that are now Reas. 1.
adayes supposed to be done by Demoniacks
or those that pretend possessions, as also all those strange feats
pretended to be brought to pass by Witches or Witchcraft, are all
either performed by meer natural causes (for it is granted upon all
sides that Devils in corporeal matter can perform nothing but by
applying fit actives to agreeable passives.) And miracles being long
since ceased, it must needs follow, that Devils do nothing but only
draw the minds of Men and Women unto sin and wickedness, and
thereby they become deceivers, cheats and notorious impostours: so
that we may rationally conclude that all other strange feats and
delusions, must of necessity be no better, or of any other kind, than
these we have recited, except they can shew that they are brought to
pass by natural means. Must not all persons that are of sound
understanding judge and believe that all those strange tricks related
by Mr. Glanvil of his Drummer at Mr. Mompessons house, whom he
calls the Demon of Tedworth, were abominable cheats and
impostures (as I am informed from persons of good quality they were
discovered to be) for I am sure Mr. Glanvil can shew no agents in
nature, that the Demon applying them to fit patients, could produce
any such effects by, and therefore we must conclude all such to be
impostures.
2. It is no sound way of reasoning, from Reas. 2.
the principles of knowing, either thereby to
prove the existence of things, or the modes of such existence, because
the principle of being is the cause of the principle of knowing, and
not on the contrary, and therefore our not discovering of all
Impostures that are or have been acted, doth not at all conclude the
rest that pass undiscovered, are diabolical or wrought by a
supernatural power; for it ought first to be demonstrated that there
are now in these days some things wrought by the power of Devils,
that are supernatural, in elementary and corporeal matter, which
never was nor can be, as from the testimonies of all the learned we
have shewed before. And therefore a man might as well argue that
there are no more thieves in a Nation, but those that are known, and
brought to condign punishment, when there may be, and doubtless
are many more; so likewise there are many hundreds of impostures,
that pass and are never discovered, but that will not at all rationally
conclude that those must be diabolical that are not made known.
CHAP. XV.

Of divers Creatures that have a real existence in Nature, and yet


by reason of their wonderous properties, or seldom being seen,
have been taken for Spirits, and Devils.

Before we come to speak of Apparitions in Hist. 1.


general, we shall premise some few things
by way of caution, because there is not one subject (that we know of)
in the World that is liable to so many mistakes, by reason of the
prepossessed fancies of men, in adhering to those fictions of Spirits,
Fairies, Hobgoblins, and many such like, which are continually
heightned by ignorant education, and vain melancholy fears. We
shall not mention those many apparitions that are frequently
practised by forgery and confederacy, for base ends and interests, as
have been commonly used in the time of Popery, and attempted in
our dayes, though with little success. As also by other persons for
base lucre or worse intents, of which we have known some notorious
ones that have been discovered. Neither shall we speak of those
feigned ones that have been practised to hide thievery and roguery,
as we once knew that certain persons who stole mens sheep in the
night, did carry them away upon a thing made like a Bier covered
with a white sheet, by which means those that saw them took it to be
an apparition, and so durst not come near them, and so the most
part of the people of 3 or 4 Villages were terrified, and the report was
far spred that it was a walking spirit, and yet at last discovered to be
a cunning piece of knavery to hide their theft withal. Neither shall we
say any thing of those ludicrous apparitions that are often practised
to terrifie, abuse, and affright others. But we shall here give the
relation of some strange creatures, that seldom being seen or found,
have induced more ignorant persons to take them for Demons, and
these we shall enumerate in this order.
1. It hath been, Centur. 1. Hist. 9. p. Hist. 2.
and still is a strong 18.
opinion amongst the vulgars and Witchmongers also, that Witches
transforming themselves into diverse shapes, did in the night time
enter into peoples houses, and then and there suck the breasts or
navils of infants in their Beds or Cradles, that thereby they were
weakned or consumed away; which inveterate opinion was the more
firmly believed, because children that at night were very well, in the
morning were found to be very ill, and to have been sucked in the
places aforesaid. To clear which point take this Observation from the
learned pen of Thomas Bartholinus that was Physician to Frederick
King of Denmark, in English thus. “Three infants (he saith) of the
Pastor Fionens at Lyckisholm, which is a noble Mannor belonging to
the very illustrious Lord Christian Thomæus Sehsted, the Kings
Chancellor, Eques Auratus, and a most renowned Senator of
Denmark, my Mecænas, that were sleeping in their accustomed
Chamber, were not long after troubled with an unwonted bewailing
and inquietude, that they felt themselves to be sucked or milked of
something. The nipples of their breasts being diligently handled by
the Parents did confirm the Childrens suspicion, because they did
hang out like a Womans that did give suck. And to prevent this
fascination, the nipples of the breasts were anointed with
preservatives against poyson and other bitter things. Hereupon their
Navils were so worn with vehement suction, that not only they were
prominent or did hang out, but also did as it were shew the greatness
of the mouth that had sucked by the impression remaining. But the
Infants being carried forth of the Chamber, did from thenceforth rest
free from any suction, especially being carried in peoples arms. And
this Caprimulgus or Goat-milker, is by Bellonius said to be in Crete
of the bigness of a Cuckow, being very hurtful to the Goats, insomuch
that it sucketh milk from their dugs on the nights.” By which we may
plainly understand, how Creatures that are but seldom seen, or
whose properties are unknown, may easily effect those things that
ignorant heads may impute unto Witchcraft.
2. It is no less Isai. 34. 14. De quadr. l. 1. p.
believed by many, Isai. 13. 21. 862.
that those kind of Deut. 32. 17. Levit. 17. 7.
Creatures which 2 Chron. 11. 15. Psal. 106. 37.
are called Satyres
are but a kind of Demons; for learned Gesner reckoning them to be a
kind of Apes, doth tell us this: “Even as (he saith) the Apes
Cynocephali, or with Dogs-heads, have given the occasion of the
Fable, that some have thought such to be men: So Satyrs being also a
rare kind of Apes, and of greater admiration, some have believed
them to be Devils: also of some men deluded by the Poets and
Painters, as also Statuaries, who have feigned that they had Goats
feet and horns, the more to augment the admiration and
superstition, they have been thought Devils: when in Ape-Satyres
there is no such thing to be seen.” And this opinion hath been the
more strengthened because the most of the Translators have in the
Old Testament rendered the word ‫( ָׂשִעיר‬which properly signifieth an
happy man or beast) a Goat, a Satyre, (as Gen. 27. ver. 11. Esau my
Brother is a hairy man; where the very same word is used) Demon,
or Devil. But it is plain that it did and doth signifie no more but only
Satyrs, as will appear by these reasons. 1. First, as our English
Translators have truly rendred it in that of Isaiah, And the Satyre
shall cry unto his fellow: for it is certainly related, both by ancient
and modern Navigators, that in those desolate Islands where there
are store of them, they will upon the nights make great shouting and
crying, and calling one unto another. And in another place of the
same Prophet it is said by the same Translators, and Satyres shall
dance there; dancing being one of the properties of that hairy
Creature, as a thing it is much delighted with, and so are but Satyres
that are natural Creatures and not Devils. 2. And though the same
Translators have rendred the plural of the same word, by the name
Devils, yet it there properly signifieth also Satyres; for though in
another place it be said; they sacrificed to devils, not to God, and so
again by the Psalmist, for they sacrificed their sons and daughters
unto devils; where in both places the word is ‫ ֵשִד ים‬vastatoribus, to
the destroyers or to Devils; because in those Idols the Devils were
worshipped, and thereby destroyed the souls of men: 3. Yet it is
manifest that their Idols were formed in the shape of Satyres, in a
most terrible manner; for the late and most credible travellers that
have been in those parts of Asia, where those Idolatries are still
upholden, do unanimously relate that they make their Images or
Idols that they worship, as terrible and frightful as they can devise, as
may be seen in the relations of the Travels of Vincent le Blanc,
Mandelslo, and Ferdinand Mendez Pinto, and Mr Herbert our
Countryman gives us the Idol of the Bannyans in the ugly shape of a
monstrous Satyre. 4. So that though this worshipping and sacrificing,
in respect of its abominableness, filthiness and Idolatrousness, was
yielded to Devils, which spiritually and invisibly ruled in these
Children of disobedience, and was the Author of all those delusions
and impostures; yet it doth no where appear, that it was Demons in
the corporeal shape of Satyres (as many have erroneously supposed)
no more than the golden Calves that Jeroboam made, were real
Devils: but these Idols were made in the figure or shape of Satyrs or
hairy Creatures, as saith the Text: And he ordained him Priests for
the high places, and for the hairy Idols or Satyres, and for the Calves
that he had made. It is the same Hebrew word here that our English
Translators render Devils, that in the two former places of Isaiah
they translate Satyres; and as the Calves are not rendred Devils, why
should the Images that were like Satyres be translated so? Surely the
Devil was as much in the Calves, and as much worshipped in those
dumb Idols as he was in the dumb and dead Idols or Images of the
Satyres, and so no more reason to call the one Devils than the other.
But that which totally overthrows the conceit that they should be real
Devils in corporeal shapes and figures, is this, that both the Calves
and the Images of these Satyres were made by Jeroboam: now it is
manifest that he could not make a real Devil, but only Images of
Calves and Satyres, wherein and whereby the Devils might be
worshipped in those Idolatrous ways.
So that it is most Observ. Medic. lib. Hist. 3.
apparent, that 3. c. 56. p. 283.
these Satyres being seldom seen and of strange qualities, have made
many to believe that they were Demons; nay it seems their Images
and Pictures have been taken for Devils, and yet are but meer natural
Creatures, and by learned men accounted a kind of Apes, which we
shall now prove by an undeniable instance or two; and first this from
the pen of that learned Physician Nicholaus Tulpius, who saith thus:
“In our remembrance (he saith) there was an Indian Satyre brought
from Angola; and presented as a gift to Frederick Henry Prince of
Aurange. This Satyre was four-footed and from the humane shape

You might also like