Programming in Java 2nd edition Edition Choudhary - Download the ebook and start exploring right away
Programming in Java 2nd edition Edition Choudhary - Download the ebook and start exploring right away
com
https://ebookgate.com/product/programming-in-java-2nd-
edition-edition-choudhary/
OR CLICK BUTTON
DOWLOAD EBOOK
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
A NYAKTÖRŐ VERSENYFUTTATÁS.
Egy pillanatra elzsibbasztá a rémület Julianna minden idegeit.
A halál jelent meg előtte.
Az az oroszlánfejű angyal, a kinek az arczát nem látta ember,
mégis tudja róla, hogy ez az oroszlán, az állatok királya, az embert is
odaértve az állatok közé.
Ha egy gyermeket ragad is el magával, akkor is borzalom az ő
láthatatlan arczába tekinteni, a nem hallott lépteit neszelni, hát még
mikor egy királyért jön el, hogy elvigye innen!
Egy lehellete elég, hogy a kit a holt király mellett talál, azt is
magával ragadja.
De csak egy pillanatig tartott az asszonynál ez a lélekzsibbasztó
dermenet, a másik pillanatban már megint úr volt a lomha idegek
fölött a megfékezhetetlen csodalény, a lélek, ez az örök ellenfele
annak az öldöklő nemtőnek. Csak a sártömeg reszket előtte, ez az
aristokrata izomhalmaz, a mi fél visszaváltozni azzá, a mi volt,
paraszt porrá. A lélek tusára kel vele! A királyi dæmonnal a demagog
lélek!
«Juhoz, kormos!»
A másik pillanatban már megszületett az agyában valami uj terv;
talán elébb is gondolkozott már rajta, a hosszu rémséges
éjszakákon, a míg a haldokló király deliriumának hangjai tarták
ébren az éjt.
Ha egy csata elveszett, készülni kell a másikhoz.
Betakarta a halott arczát a kámforos borékkal, s kiment a
mellékszobában alvó apáczához, a kinek fel kelle őt váltani. Azt
felkölté s ezt sugta a fülébe:
– A király elaludt, csendesen szunnyad. Ne engedj, testvér, senkit
hozzája bemenni, a míg nem hallod a neszt, hogy fölébredt. Az
orvosok ha jönnek, mondd nekik, hogy a király csendesen alszik,
magához tért; inni kért, imádkozott, úgy aludt el.
Ezzel a kegyes hazugsággal nyerni remélt hat órai időt.
Lesietett a svájczi lépcsőn keresztül a vár udvarra, s onnan ki az
utczára.
Vehette észre, hogy az utczán járó közönség hogy oldalog el
mellőle, s igyekszik át a tulsó gyalogjáróra, a mint a parabolánák
köntösét meglátja rajta. Minden ember tudja, hogy ezek ápolják a
himlőbetegeket. Mikor hazaért a vendéglőbe a «veres háztetőhöz»,
be sem eresztették, hanem a mint megmondta, hogy ő ideszállt
vendég: egyenesen a fürdőszobába vitték, ott le kellett vetnie az
öltönyeit, magának egy kámforos eczettel telitett fürdőbe beleülni,
úgy hozatták le a szállásán hagyott ruháit, hogy oda felmehessen. S
ez nagyon helyesen történt így, mert a rettegett apáczaköntösben
máshová sem nyerhetett volna bebocsáttatást.
– Készülj rögtön az utra, mondá Krisztinának; fogass be, s hajts a
kocsival a karinthi kapu elé; ott várj reám, míg megérkezem.
Csomagolj össze sok ennivalót az utra; mert hosszu utunk lesz, s a
körmünk közül kell élnünk. Egyebet most ne kérdj.
Azzal sietett Wratislawhoz.
A kanczellártól kapott passe partout mellett rögtön bebocsátották
az államférfihoz, ki az ő jövetelére kituszkolt az ajtón egy pár
excellencziást és Durchlauchtot, a kik nála voltak; olyan nevezetes
személy volt előtte ez az asszony.
– Nos, ifjasszony! Mi hir a császárról? kérdé tőle, midőn egyedül
maradtak.
– Meghalt.
A kanczelláron észrevehető volt az összerezzenés.
– Tudja már valaki?
– Rajtam kívül még senki sem. A virrasztó apáczának azt
mondtam, hogy a király alszik, ne hagyjon hozzá senkit bemenni,
még az orvosokat sem. Ezzel öt-hat órai időt remélek nyerni.
– S mit nyer az ifjasszony ezzel az időhaladékkal?
– Megelőzhetem a futárt, a kit a király halálhirével Szathmárra
fognak küldeni.
– Ah! – Az államférfi érzeni kezdé azt a meleget, a mi ennek az
asszonynak a szemeiből kisugárzik.
– Ön Szathmárra akar innen futni! Gyorsabban, mint maga a
staféta?
– Kegyelmességed érteni fogja, hogy miért. A király halva van: ő
nem szentesíthet többé semmit, sem azokat a nagy országos
szerződéseket, sem az apró emberek kegyleveleit, a mik tőle várták
valósulásukat. De van még egy ember, a ki a király személyét
képviseli: Pálffy nádor, a király teljhatalmazottja. A mit ő szentesít,
mielőtt a király halálhirével együtt a teljhatalmat megszüntető
parancsot megkapja, az szent marad. Kegyelmeteknek még öt-hat
órájuk van, hogy két ország béke és háború kérdését befejezzék.
Bizza rám: én odasietek vele s megelőzöm az ellenfelei küldönczét.
– Egy asszony akar versenyezni egy férfival?
– Ah mit! Ha férfi is az, csak ember!
(Nem egészítette ki a mondást: «én nem asszony vagyok, hanem
dæmon.»)
A helyett természetes magyarázatul tevé hozzá:
– A futárt csak a kötelessége fogja siettetni, de engemet a
kétségbeesés, a fiam boldogsága, az anyaszeretet lángdühe
korbácsol a futásban.
Wratislaw rábólintott a fejével.
– Hát az ifjasszony sietni fog Pálffyhoz, hogy a királyi kegylevelet
ő vele irassa alá.
– A hogy a többi magyar urakét is, a kurucz fővezérekét. Mind,
mind ő nála vannak. Csak egy intő szóra van szükség
kegyelmességedtől és minden tökéletessé válik.
A kanczellár kezdte hinni, hogy az asszonyi akarat az első
nagyhatalom a földön.
– Hát lássuk, hogy kezd az ifjasszony hozzá?
– Legelőször is azonnal útra indulok, a hintóm már itt áll a
karinthi kapu előtt; az első állomáson hat lovat fogatok eléje, s a
gänserndorfi postának valamennyi lovát felfogadom a szomszéd
helységekbe küldve. Onnan túl azután vágtatva sietek, éjjelt
nappallá téve, keresztül a Szepességen, s minden postaállomásnál
magammal viszek minden rendelkezés alatt levő fogatot.
– Ez az ifjasszonynak sok pénzébe fog kerülni. Engedje meg,
hogy én is járulhassak hozzá.
Azzal a kanczellár a szekrényéből kivett öt darab tekercset. Ezer
arany volt azokban.
– Ezzel segíthet magán az út közben. Tehát csak tegyen úgy, a
hogy mondta. Foglaljon le minden lovat az állomásokon: ne
engedjen magának pihenést. Ha szerencsésen megérkezik
Szathmárra Pálffyhoz, mutassa meg neki a tőlem kapott passe
partout, s azután mondja el neki élőszóval, a mit megtudott és azt is,
hogy egy másik futár jön a nyomában a visszahívó rendelettel. De
hátha az a futár utól találja az ifjasszonyt érni valahol az ecsedi láp
feneketlen utain?
– Az annak lesz baj, nem nekem!
Ehhez a mondáshoz olyan ördöngős fenyegető arczot tudott
mutatni az asszony, hogy a kanczellár hinni kezdett abban a
fogadásában: «én még a kettészakadt villámsugárt is csomóra
fogom kötni!»
A villámsugár pedig ugyan ketté volt szakadva!
– Nincs veszteni való pillanat: én bucsuzom kegyelmességedtől a
viszontlátásig.
– Ne siessen még, ifjasszony. Egy kérdés még függőben van.
Hátha Illésházyék a hirmondójukat nem azon az útvonalon futtatják
végig, a melyen kegyelmed elindul?
– Adná a magasságos ég, hogy azt tennék. Vajha a bölcs
tanácsuraknak az az áldott spuriusuk jönne, hogy a mappát vegyék a
kezükbe s czirkalommal mérjék ki, melyik a rövidebb útvonal s azon
eresztenék el a stafétájukat. Mert azt mondja a magyar példabeszéd,
hogy «arra közelebb; erre hamarább». A hosszabb út a Vág
mellékén vezet végig, Liptón, Szepesen át Lőcséig, onnan le Kassára.
Tokajnál átvisz a Tiszán; onnan a Nyirségnek, Nyiregyházának,
Nagy-Károlyig. Az egész Felső Magyarországon mindenütt csinált
kőutak vannak, a Nyirben tavaszszal még barátságos a homok, csak
a Szamos közelében, az ecsedi lápon keresztül lesz keserves az
utazás. Aztán ezek itt mind meghódolt vidékek, vendégszerető
nemesi házakkal. De a rövidebb út, Pesten, Szolnokon át egész
Debreczenig, a Hajduságon keresztül, az most csak annak való, akit
halálért küldenek. Ha ott nem vész a sárban, bizonyosan agyonverik
a hajdúk. A Tiszán túl nagyobb bátorságot ád az asszonyköntös,
mint a császári uniformis. Engem nem bántanak se a hajdúk, se a
betyárok, ha közéjük tévedek, eléneklem a nótájukat, iszom a
kulacsukból, s még ők fognak a pusztákon, nádasokon keresztül
elvezetni.
– No hát, Isten segítse az ifjasszonyt.
ebookgate.com