Programming in Java 2nd edition Edition Choudhary download
Programming in Java 2nd edition Edition Choudhary download
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/
ebookgate.com
https://ebookgate.com/product/java-programming-8th-edition-joyce-
farrell/
ebookgate.com
https://ebookgate.com/product/java-programming-6th-edition-joyce-
farrell/
ebookgate.com
https://ebookgate.com/product/functional-programming-in-java-
harnessing-the-power-of-java-8-lambda-expressions-1st-edition-venkat-
subramaniam/
ebookgate.com
JXTA Java P2P Programming 1st Edition Daniel Brookshier
https://ebookgate.com/product/jxta-java-p2p-programming-1st-edition-
daniel-brookshier/
ebookgate.com
https://ebookgate.com/product/java-network-programming-third-edition-
elliotte-rusty-harold/
ebookgate.com
https://ebookgate.com/product/beginning-programming-with-java-for-
dummies-3rd-edition-barry-burd/
ebookgate.com
https://ebookgate.com/product/programming-in-c-2nd-edition-safari/
ebookgate.com
https://ebookgate.com/product/programming-in-scala-2nd-2nd-edition-
martin-odersky/
ebookgate.com
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
Language: English
TO
E. A. N.
AND
G. M. L.
IRELAND IN TRAVAIL
BY JOICE M. NANKIVELL
AUTHOR OF “THE SOLITARY PEDESTRIAN”
LONDON
JOHN MURRAY, ALBEMARLE STREET, W.
1922
All rights reserved
CONTENTS
CHAPTER PAGE
I. 47—Agent (S. L.) 1
Called up—Another acquaintance—Below the
surface—Through a window.
II. We Cross to Dublin (J. M. N.) 10
On board—After curfew—We arrive.
III. I come across 47 (S. L.) 17
Stephen’s Green—On the stroke—Cumann na
mBan—Good advice.
IV. Finding a Roof (J. M. N.) 27
Mrs. Slaney—We take a flat—Au revoir.
V. We settle in (J. M. N.) 34
Mrs. Slaney indignant—We dine.
VI. We make Acquaintances (J. M. N., S. L.) 38
A Beau Brummell—Signs of the times—An
introduction—Money for nothing—A tram ride.
VII. The Birth of Sinn Fein (S. L.) 48
The beginning—The Celtic revival—The Phœnix—
Capital versus Labour—Murder gang—Bad to
worse—Black-and-Tans—Disturbed areas—
Reprisal.
VIII. Autumn wears out (S. L.) 66
The game of bluff—Passers-by—Wanted men—
Templemore—Our mutual friend—Hard at work
—A lonely life.
IX. The Hunger Strike (S. L.) 81
The great fast—A Dublin funeral—The night watch
—A mysterious visitor—Kevin Barry—November
ends.
X. Bloody Sunday (J. M. N.) 94
Terrible news—A Sunday evening—Unhonoured
and unsung.
XI. Aftermath (S. L.) 101
In full cry—In the crowd—A chance meeting.
XII. Visit to a Top Story (J. M. N.) 109
Watching and waiting—Money for nothing—Au
revoir.
XIII. From the Housetop (S. L., J. M. N.) 116
The Central Hotel—A brief haven—A top story—
Down below—Lies, all lies!—Loyalist and
Republican—The first raid—England’s market
garden.
XIV. An At Home (J. M. N.) 133
A Christmas box—Old Meg—Curlewed—A
Unionist.
XV. Height of the Terror (S. L.) 142
Day by day—Building a Republic—President De
Valera—The pendulum—Irish Bulletin—
Reprisals—The gods must laugh.
XVI. The Minister of Propaganda (J. M. N.) 156
A piece of news—An innocent man—Real dotes.
XVII. Capture of a Cabinet Minister (J. M. N.) 162
Mrs. Slaney is uneasy—Open, the military!—
Harbouring rebels—His tea.
XVIII. Winter wears out (S. L.) 170
Spreading the news—A Republican—Propaganda
—Waste! Waste!—Day and night—The City
ambushes.
XIX. Mrs. O’Grady’s Forebodings (J. M. N.) 183
Mrs. O’Grady is prudent—Enter Mrs. Slaney.
XX. To Dublin Castle (S. L.) 189
Raided again—A new acquaintance—A find—A
late call—The journey done.
XXI. Inside the Castle (S. L.) 200
To bed—The Auxiliary at home—Into the fire—
Thirteen at table—An outing.
XXII. Lost: A Husband (J. M. N.) 211
A strained situation—Gelignite!—Next morning—
Dublin Castle—In the maze—Room 13—F
Company—Found.
XXIII. Last Weeks of War (S. L.) 229
Spring and peace—The Customs House—The
Auxiliary Cadets—A brisk affair—Ballykinler—
Under the whip—Mrs. Slaney indignant.
XXIV. The Coming of Summer (S. L.) 244
Corner-boys—Hands up—Erskine Childers—The
phantom army—In Phœnix Park—The old order
changeth.
XXV. The Eve of Peace (J. M. N.) 257
Ambushed—Only another ambush—Patriots—The
final raid—To rack and ruin.
XXVI. The Twelfth of July (S. L.) 268
North and South—King William—The great day—
The trysting-ground—Patches of splendour.
XXVII. Truce (S. L.) 279
Changed times—The final settlement—The last of
47—Dail Eireann—Leave them there.
XXVIII. Last of Ireland (J. M. N.) 291
An avatar—Good-bye to Ireland.
XXIX. Looking Back (S. L.) 297
Hag-ridden—Two alternatives—The hopeful
present.
IRELAND IN TRAVAIL
CHAPTER I
47—AGENT
In the wonderful August weather of 1920, my wife and I were in our
London flat sighing for cooler places. The season had come to an
end with less than its usual glory, and for days taxis and growlers,
topheavy with luggage, had been carrying fleeing Londoners to
country and to sea. The holidays had begun; but England, still
limping from the late war, had lost the holiday spirit: indeed the
world was restless as if it had come through painful convulsions to
kick spasmodically for a while. We were restless too.
Ireland was one of the world’s sores. It was near at hand. Should we
go and see for ourselves? The middle of August had come, and we
could not make up our minds.
On the hottest of those mornings I wandered into Hyde Park, and
where the riders turn their horses about, on the very last chair of the
row, leaning forward, rubbing his chin on his stick, I came across 47
—Agent of the secret service. He had seen me coming along, and
patted the next seat in invitation as if we had met yesterday.
“I thought you were at the other end of the world.”
He answered, “I’m here.”
How I met 47; how it came about that he revealed his secret to me;
how it was that we became friends, has nothing to do with this
story. Sometimes I saw a lot of him; sometimes he passed out of my
life for a year.
Before I had known 47 six months I had learned this, that a secret
service agent, if he is to be more than a common spy, what the
French term a mouchard, a fellow who gleans his news among
servant girls and the like, must have something of a statesman’s
vision to carry him on his way. He must have that sense of the future
which lifts him beyond the individual and the matter of the moment
to think in nations and down centuries. Thus is lessened the pang he
feels as he bruises the individual, as the vivisectionist tortures the
beast that beasts and men shall be freed of pain.
“Come to dinner to-night,” I said. “We are always talking of you.”
“I’m crossing to Ireland to-night.”
“Ireland? Are you working there?”
He nodded. “I’m going to make a beginning. All the fellows who are
resting have been called up. Things are going from bad to worse.”
“Are they worse than the papers make out?”
“They are bad enough. I’ve not seen for myself yet; but the Irish
Republican Army has grown into a moderately disciplined and fairly
numerous fighting affair, and seems to be getting bolder. Thousands
of the young men belong to it. They don’t wear uniform, and those
who aren’t known to the military and police, and so aren’t on the
run, live as ordinary citizens until they are called on for some stunt.
They’re a secret organisation, and we ought to be the people for
them.”
“Are you glad to be off?” I said.
“Damn glad,” he answered. “I’ll be able to see for myself. One man
tells you the country is in the clutches of a murder gang, and the
next that some nobler spasm convulses it. All the same I hear work
in Ireland is trickier than Continental stunts. On the Continent you
have the majority of the nation indifferent to you, and only the
official part to circumvent; but in Ireland they say half the nation is
waiting to give a man away.”
“Why didn’t you come and say you were off?”
“I got orders this morning.”
“We have been thinking of having a look at Ireland. My wife’s
interested in adoption work, and wants to start it over there. We
can’t make up our minds.”
He looked round. “You?”
“Both of us. D’you think we’d find it worth while?”
“Probably. Why not come over? You’re people with nothing to do.”
“If we do, we’re going to be strictly neutral,” I said. “We want to
meet the other side.”
He nodded. “It’s not always easy. That’s what a good many want to
do. You may do it if you stay neutral.”
“We’re going to do it.”
“Then make up your minds. You’re sure to run across me if you
come to Dublin.” He looked at the watch on his wrist and said, “I
must go.” But he did not get up.
“You’ve got the pip,” I said.
“I’m glad to be on the road,” he answered, rubbing his chin on his
stick again; “but it’s a solemn business.” He became suddenly very
stern. “An agent requires a better courage than a soldier’s. Once he
enters enemy country he does not hear a word in favour of his
cause. The very newspapers he must read denounce the
Government whose servant he is. Day after day he wages his lonely
war.
“The man I meet at the Hibernian Hotel at twelve o’clock to-morrow
is to be my ‘cousin,’ as we call it. It is my privilege to pour into his
ears all my troubles, and he will do his best for me. Once a day,
once or twice a week as may be arranged, he will appear at this
place or that place at such and such an hour to take my information.
This information he will pass on to another man, and this third man
is the link with Dublin Castle.
“My wife and I will have no other loyal acquaintances, no other
person in sympathy with us. While the Irish situation stays as it is
we shall have only each other to lean on. Now and again we may
pass an acquaintance in the street, and we shall go by without a
word, without a nod. How many times must we join in the laugh
against us? How many times must we sneer when we love? How
many times must we applaud when we scorn?”
He looked in front of him and said in a low voice, “Betray once more,
47, that a traitor may be destroyed. Deny once again, 47, that a liar’s
mouth may be stopped. Listen this time, 47, that some one else shall
listen no more. Stifle your humanity. Fight your lonely fight.”
He got up, nodded, and departed.
I returned to lunch and told my wife I had come across 47. She was
thrilled now at the idea of Ireland, and when lunch was over we had
nearly made up our minds. I had to leave her in the evening, it was
the case of a theatre, and as I walked out of that same theatre,
somebody was at my side. He was the only other secret service man
I knew; the introduction had come through 47. Such is life.
He was resplendent. The background of lights and women and
motors purring at the kerb was just what he wanted. We strolled
back together along Piccadilly, and he was in his best vein. He asked
after my wife, and from her he got on to women in general. He
began to philosophise presently and said:
“You can’t beat a really good woman.” Then he shook his head. “But
most women are the devil.”
“Not all.”
“Most.”
He drew up his lip like a dog.
“I remember once in Vienna there was an actress, an agent of the
Austrian Government, who was so dangerous that one after another
of our fellows had to pull out half-way because they were losing
their heads.” He nodded and went on showing his eye-tooth. “But
one day there came along an agent less susceptible than the others
and—he broke her neck.”
“One of her unlucky days?”
“Yes, he broke her neck.”
There was a pause.
“The clock was over there. This agent looked at it, and it had long
gone midnight. She had been home from the theatre some time.
The supper things were on the table: supper was over. She was
standing in the middle of the room, and when she heard him coming
up behind, she leaned back bored for an embrace. She was unused
to a refusal. She had in mind to suck this man dry and afterwards
toss him away like an empty wine bottle. She put her head back,
smiling. He slipped his arm round her neck and—it’s not difficult if
you know the way.”
This man had the most wonderful personality in the world. He grew
more and more splendid all the time.
“He who runs may read. In our service a man receives certain
payments for his harassing life. The agent lives two lives at one and
the same time. He lives the life of the citizen, pays his milk bill,
shops with his women friends, breakfasts, lunches, dines, and all the
time he is living a second life below the surface. He sees the moves
in the war raging about him; he remarks man after man go down.
There is no cry. These are the deaths that never get into the papers.
If recorded at all they are recorded as accidents or found dead. He
sees the messages passed at the street corners, and the friend
strolling at his side sees one man giving another a light. He sees this
wanted man go by, he sees that sign put up, he asks himself why is
this man here, what is that woman doing there? And his friend
recognises only the beggar girl whining on the doorstep, and the
cabman flourishing his whip.”
We were passing under a street lamp. He had become magnificent.
His eyes were shining. He had swollen like a pouter pigeon.
“When the time comes for us to leave the service we cannot. We are
offered rest, we are offered peace; at last has come opportunity for
our stretched nerves to recover. But we must continue to be au
courant with affairs. So nearly every agent dies in harness.
“But, of course, besides receiving payment, an agent pays for this
life. He makes payment in several ways. One way is that he finally
comes to believe nothing, to trust nobody. He weighs up what his
best friend says. And another payment is that the life brings a man
in the end to neutral feelings. He is cold sometimes—yes. Wet—yes.
Tired—yes. Even a little depressed sometimes. But not elated. Never
surprised.
“It’s fifteen years since I was surprised.”
And then at Hyde Park Corner, the place where I had last seen 47,
he was gone, and I was left to stroll home alone.
My wife was still up.
“I’ve just met our other friend,” I said, shutting the door.
“What does he say?”
“He’s going over in a day or two. He was at the top of his form.”
Then I gave out what I had been given, and she listened with her
eyes jumping out of her head. Her mind, and accordingly my mind,
was made up half-way through. At the end she jerked upright in the
armchair and cried—
“But let’s go and see for ourselves, and I’ll try and get my ‘Baby
Exchange’ going. Let’s.”
“By all means.”
This was very late at night or very early in the morning.
Now it is time to ask if the world possesses one true history book.
History can only be approximate, for events are without limit, and
man is limited. Each observer of Irish affairs has been watching
Ireland through the windows of his temperament and his
opportunities, and where a man has seen this thing, his neighbour
has seen another.
Humbly, then, we put down what we have to tell, endeavouring to
fill these pages with the spirit of the times rather than with a tedious
list of events.
CHAPTER II
WE CROSS TO DUBLIN
It was past eleven o’clock when I left my wife and wandered out of
the hotel and across O’Connell Bridge. The tide was high, and
something about the lights that lay upon the Liffey waters, and
something about the numerous bridges spanning the river, brought
me dreams of Venice.
It is said there is truth in first impressions. I had a first impression of
Dublin then. In that shining summer weather the city, which was at
once so pleasantly conceived and so down at heels, impressed me
as some likeable person fallen upon a sick bed.
Was it that I was reading into the face of the city what I expected to
see? I had wondered at the suspicion of the guests in the hotel, who
sat surly and apart. Now against the embankment of the river
shabby men and youths leaned, cooling their heels. They smoked
and spat and contemplated the traffic, which was controlled by
magnificent policemen as tall as trees. There appeared to be a
barbers’ strike in progress, as outside the barber’s shop loitered
sundry young men who would have been the better for a shave.
These people displayed a board with “Strike on Here” printed in big
letters, and whenever some customer, maddened by a two months’
growth of hair, vanished into the shop, they would shout after him in
raucous tones, “Strike on there!”
The crowd looked worried and suspicious of itself, and surely it was
evident to him who had eyes to see that war, none the less real
because waged below the surface, was going on, and nobody knew
who was for this side and who for the other.
Yes, war—rumbling through the streets in the guise of heavy military
waggons, tramping round the corners in parties of tin-hatted
soldiers, flying up and down the quays in lorries choked with dapper-
looking men wearing Balmoral bonnets, rushing up this road and
that in Crossley tenders, filled with less romantic men in black
uniforms and peaked caps.
I passed over O’Connell Bridge, up Westmoreland Street, and out of
it between two grave stone buildings; that across the way an
eloquent curving place, once a parliament, and now suffering from a
changed greatness as the Bank of Ireland; this, to my left, the grave
grey face of Trinity, with its arch like a mouth, through which could
be seen cobbled walks removed from the wear and tear of the rest
of the city.
Then to the left and up Dawson Street, past the Mansion House, an
uninspired building, into one of the noble squares that the city
possesses. The heart of this square was a public garden called
Stephen’s Green. I crossed the road, which was wide and straight,
and entered the park by a little gate in the iron railings.
The sun poured out of the sky, and the place was full of nurses and
babies. Two lakes, divided by a bridge, filled all the centre of the
place, and ducks and seagulls and small children disputed for bits of
bread round the edges. It was the scene one meets in all city parks;
but it was specially charming owing to the sun and the twisting
walks.
I was looking for a chair when I discovered 47 strolling down the
path. He had seen me; he always saw me first. He looked just the
same as when we had said good-bye at Hyde Park Corner.
“So you came over?” he said.
“Yes.”
“You’ll find it worth while.”
The place was the best in the gardens for a talk. Two chairs were
beside us. We sat down with mutual consent.
“I have been over a week,” he said. “I put up at the Gresham. That’s
in Sackville Street. I had to get in touch first thing. I was to meet my
‘cousin’ in the lounge of the Hibernian Hotel, Dawson Street, at a
Welcome to Our Bookstore - The Ultimate Destination for Book Lovers
Are you passionate about books and eager to explore new worlds of
knowledge? At our website, we offer a vast collection of books that
cater to every interest and age group. From classic literature to
specialized publications, self-help books, and children’s stories, we
have it all! Each book is a gateway to new adventures, helping you
expand your knowledge and nourish your soul
Experience Convenient and Enjoyable Book Shopping Our website is more
than just an online bookstore—it’s a bridge connecting readers to the
timeless values of culture and wisdom. With a sleek and user-friendly
interface and a smart search system, you can find your favorite books
quickly and easily. Enjoy special promotions, fast home delivery, and
a seamless shopping experience that saves you time and enhances your
love for reading.
Let us accompany you on the journey of exploring knowledge and
personal growth!
ebookgate.com