Programming in Java 2nd Edition Edition Choudhary Download PDF
Programming in Java 2nd Edition Edition Choudhary Download PDF
com
https://ebookgate.com/product/programming-in-
java-2nd-edition-edition-choudhary/
https://ebookgate.com/product/a-guide-to-programming-in-java-
java-2-platform-standard-edition-5-beth-brown/
https://ebookgate.com/product/java-programming-8th-edition-joyce-
farrell/
https://ebookgate.com/product/java-programming-6th-edition-joyce-
farrell/
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/
https://ebookgate.com/product/java-network-programming-third-
edition-elliotte-rusty-harold/
https://ebookgate.com/product/beginning-programming-with-java-
for-dummies-3rd-edition-barry-burd/
https://ebookgate.com/product/programming-in-c-2nd-edition-
safari/
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
ISBN-13: 978-0-19-809485-2
ISBN-10: 0-19-809485-X
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,
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,
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
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
comprehend the problems in procedural programming and how OOP overcomes them
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
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.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
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.
Employee Class
name
address
designation Attributes
salary
addEmployee
deleteEmployee Behavior
searchEmployee
:Employee Object
name=peter
address=NY
designation=manager Attributes
salary=10000
addEmployee
deleteEmployee
searchEmployee
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.
(a) (b)
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.
(a) (b)
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.
(a) (b)
Shape
Triangle Square
Shape
area( )
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
(a) (b)
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
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
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:
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
Client
Browser Internet
(running Web server
Java applet)
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
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).
Operating Systems
(Window, Unix, etc)
Hardware
(Intel, Motorola, Alpha, etc.)
Compile-Time Runtime
Bytecode
Bytecode
moves through
Java compiler verifier
network or
file system
Machine code
Interpreter
generator
Java
bytecode
Operating system
Hardware
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.
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
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
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
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.
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
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.
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
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++.
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
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.