0% found this document useful (0 votes)
39 views

Java Programming All Units Notes

java programming notes r18 jntuh

Uploaded by

thadakalasruthi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views

Java Programming All Units Notes

java programming notes r18 jntuh

Uploaded by

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

Object - Oriented

Thinking

1
1 Object-Oriented Thinking

When computers were first invented, programming was done manually by toggling in a binary machine
instructions by use of front panel. As programs began to grow, high level languages were introduced
that gives the programmer more tools to handle complexity. The first widespread high level language is
FORTRAN. Which gave birth to structured programming in 1960’s. The Main problem with the high
level language was they have no specific structure and programs becomes larger, the problem of
complexity also increases. So C became the popular structured oriented language to solve all the above
problems.

However in SOP, when project reaches certain size its complexity exceeds. So in 1980’s a new
way of programming was invented and it was Object Oriented Programming. Object Oriented
Programming is a programming methodology that helps to organize complex programs through the use
of inheritance, encapsulation & polymorphism. Object Oriented Programming is a Revolutionary idea
totally unlike anything that has came before in programming Object Oriented Programming is an
evolutionary step following naturally on the heels of earlier programming abstractions.

Item situated writing computer programs is as often as possible alluded to as another


programming worldview. The word worldview initially implied model, or model. For instance, a
worldview sentence would assist you with recalling how to conjugate an action word in an unknown
dialect. All the more for the most part, a model is a model that causes you see how the world functions.
For instance, the Newtonian model of material science discloses why apples tumble to the ground. In
software engineering, a worldview clarifies how the components that go into making a PC program are
sorted out furthermore, how they associate with one another. Hence the first step in getting Java is
valuing the item situated world view.

1.1 A Way of Viewing World


To illustrate the major ideas in object-oriented programming, let us consider how we might go about
handling a real-world situation and then ask how we could make the computer more closely model the
techniques employed. Suppose I wish to send flowers to a friend who lives in a city many miles away.
2
Let me call my friend Sally. So I chooce a agent called Flora to carry flowers to my friend.I tell Flora
the variety and quantity of flowers I wish to send and give Sally's address, and I can be assured the
flowers will be delivered expediently and automatically

Figure 1.1: The community of agents helping me

1.1.1 Agents and Communities

At the risk of belaboring a point, let me emphasize that the mechanism I used to solve my
problem was to find an appropriate agent (namely, Flora) and to pass to her a message containing my
request. It is the responsibility of Flora to satisfy my request. There is some method or some algorithm
or set of operations used by Flora to do this. I do not need to know the particular method that Flora will
use to satisfy my request; indeed, often I do not want to know the details. This information is usually
hidden from my inspection.

If I investigated however, I might discover that Flora delivers a slightly diferent message to another
againt in my friend's city. That agent , in turn, perhaps has a subordinate who makes the flflflowers
arrangement. The agent then passes the flowers , along with yet another message, to a delivery person,
and so on. Earlier, the agent in Sally's city had obtained her flowers from a flower wholesaler who, in
turn, had interactions with the flowers growers, each of whom had to manage a team of gardeners.

So, our first observation of object-oriented problem solving is that the solution to my problem
required the help of many other individuals (Figure 1.1). Without their help, my problem could not be
easily solved. We phrase this in a general fashion as the following:

An object oriented program is structured as a community of interacting agents, called objects. Each
object has a role to play. Each object provides a service, or performs an action, that is used by other
members of the community.
3
1.1.2 Messages and Methods

The chain reaction that ultimately resulted in the solution to my program began with my request to
Flora. This request lead to other requests, which lead to still more requests, until my flowers
ultimately reached my friend. We see, therefore, that members of this community interact with each
other by making requests. So, our next principle of object- oriented problem solving is the vehicle by
which activities are initiated:

Action is initiated in object-oriented programming by the transmission of a message to an agent


(an object) responsible for the action. The message encodes the request for an action and is
accompanied by any additional information (arguments) needed to carry out the request. The receiver
is the object to whom the message is sent. If the receiver accepts the message, it accepts the
responsibility to carry out the indicated action. In response to a message, the receiver will perform
some method to satisfy the request.

We have noted the important principle of information hiding in regard to message passing that
is, the client sending the request need not know the actual means by which the request will be
honored. There is another principle, all too human, that we see is implicit in message passing. If there
is a task to perform, the first thought of the client is to find somebody else he or she can ask to do the
work. This second reaction often becomes thin in many programmers with extensive experience in
conventional techniques. Frequently, a dificult hurdle to overcome is the idea in the programmer's
mind that he or she must write everything and not use the services of others.

An important part of object-oriented programming is the development of reusable components,


and an important first step in the use of reusable components is a willingness to trust software written
by others.

Information hiding is also an important aspect of programming in conventional languages. In


what sense is a message difierent from, say, a procedure call? In both cases, there is a set of well-
defined steps that will be initiated following the request. But, there are two important distinctions. The
first is that in a message there is a designated receiver for that message; the receiver is some object to
which the message is sent. In a procedure call, there is no designated receiver.

4
The second is that the interpretation of the message (that is, the method used to respond to the
message) is dependent on the receiver and can vary with difierent receivers. I can give a message to
my neighbor Elizabeth, for example, and she will understand it and a satisfactory outcome will be
produced (that is, flflowers will be delivered to my friend). However, the method Elizabeth uses to
satisfy the request (in all likelihood, simply passing the request on to Flora) will be different from that
used by Flora in response to the same request. If I ask , someother to send flowers to my friend, he
may not have a method for solving that problem.

Let us move our discussion back to the level of computers and programs. There, the distinction
between message passing and procedure calling is that, in message passing, there is a designated
receiver, and the interpretation may vary with difierent receivers(the selection of a method to execute
in response to the message). Usually, the specific receiver for any given message will not be known
until run time, so the determination of which method to invoke cannot be made until then. Thus, we
say there is late binding between the message (function or procedure name) and the code fragment
(method) used to respond to the message. This situation is in contrast to the very early (compile-time
or link-time) binding of name to code fragment in conventional procedure calls.

1.1.3 Responsibilities

A fundamental concept in object-oriented programming is to describe behavior in terms of


responsibilities. My request for action indicates only the desired outcome (flowers for my friend).
Flora is free to pursue any technique that achieves the desired objective and is not hampered by
interference on my part.

By discussing a problem in terms of responsibilities we increase the level of abstraction. This


permits greater independence between objects, a critical factor in solving complex problems. The
entire collection of responsibilities associated with an object is often described by the term protocol.

A traditional program often operates by acting on data structures, for example changing fields
in an array or record. In contrast, an object oriented program requests data structures (that is, objects)
to perform a service. This difference between viewing software in traditional, structured terms and
viewing it from an object-oriented perspective can be summarized by a twist on a well-known quote:

5
“Ask not what you can do to your data structures, but rather ask what your data structures can do for you”.

1.1.4 Classes and Instances

Although I have only dealt with Flora a few times, I have a rough idea of the behavior I can expect
when I go into her shop and present her with my request. I am able to make certain assumptions
because I have information about forists in general, and I expect that Flora, being an instance of this
category, will fit the general pattern. We can use the term Florist to represent the category (or class) of
all forists. Let us incorporate these notions into our next principle of object-oriented programming:

All objects are instances of a class.The method invoked by an object in response to a message is
determined

by the class of the receiver. All objects of a given class use the same method in response to similar
messages.

Figure 1.2: The category surrounding Flora

6
1.1.5 Class Hierarches - Inheritance

I have more information about Flora not necessarily because she is a florist but because she is a
shopkeeper. I know, for example, that I probably will be asked for money as part of the transaction,
and that in return for payment I will be given a receipt. These actions are true of grocers, stationers,
and other shopkeepers. Since the category Florist is a more specialized form of the category
Shopkeeper, any knowledge I have of Shopkeepers is also true of Florists and hence of Flora.

One way to think about how I have organized my knowledge of Flora is in terms of a hierarchy
of categories (see Figure 1.2). Flora is a Florist, but Florist is a specialized form of Shopkeeper.
Furthermore, a Shopkeeper is also a Human; so I know, for example, that Flora is probably bipedal. A
Human is a Mammal (therefore they nurse their young and have hair), and a Mammal is an Animal
(therefore it breathes oxygen), and an Animal is a Material Object (therefore it has mass and weight).
Thus, quite a lot of knowledge that I have that is applicable to Flora is not directly associated with her,
or even with her category Florist.

Figure 1.3: A class hirearchy for various meteral objects


7
The principle that knowledge of a more general category is also applicable to a more specific
category is called inheritance. We say that the class Florist will inherit attributes of the class (or
category) Shopkeeper.

There is an alternative graphical technique often used to illustrate this relationship, particularly
when there are many individuals.. This technique shows classes listed in a hierarchical tree-like
structure, with more abstract classes (such as Material Object or Animal) listed near the top of the
tree, and more specific classes, and finally individuals, are listed near the bottom. Figure 1.3 shows
this class hierarchy for Flora.

“Classes can be organized into a hierarchical inheritance structure. A child class (or subclass) will inherit
attributes from a parent class higher in the tree. An abstract parent class is a class (such as Mammal) for
which there are no direct instances; it is used only to create subclasses.”

1.1.6 Method Binding, Overriding and Exceptions

I know that mammals give birth to live children, but Phyl is certainly a Mammal, but it lays eggs. To
accommodate this, we need to find a technique to encode exceptions to a general rule.

We do this by declearing that information contained in a subclass can override information


inherited from a parent class. Most often, implementations of this approach takes the form of a method
in a subclass having the same name as a method in the parent class, combined with a rule for how the
search for a method to match a specific message is conducted:

The search for a method to invoke in response to a given message begins with the class of the receiver. If no
appropriate method is found, the search is conducted in the parent class of this class. The search continues up
the parent class chain until either a method is found or the parent class chain is exhausted. In the former case
the method is executed; in the latter case, an error message is issued. If methods with the same name can be
found higher in the class hierarchy, the method executed is said to override the inherited behavior.

8
Even if the compiler cannot determine which method will be invoked at run time, in many
object-oriented languages, such as Java, it can determine whether there will be an appropriate method
and issue an error message as a compile-time error diagnostic rather than as a run-time message.

If Elizabeth and my florist Flora will respond to my message by difierent methods is an


example of one form of polymorphism. We will discuss this important part of object-oriented
programming in Chapter. As explained, that I do not, and need not, know exactly what method Flora
will use to honor my message is an example of information hiding.

1.1.7 Summary of Object - Oriented Concepts

The following are fundamental to OOP :

 Everything is an object.
 An object is a runtime entity in an object oriented programming
 Computation is performed by objects communicating with each other. Objects
communicate by sending and receiving messages. A message is a request for action
bundled with whatever arguments may be necessary to complete the task.
 Each object has its own memory, which consists of other objects.
 Every object is an instance of a class. A class simply represents a grouping of similar
objects, such as integers or lists.
 The class is the repository for behavior associated with an object. That is, all objects that
are instances of the same class can perform the same actions.
 Classes are organized into a singly rooted tree structure, called the inheritance hierarchy.
Memory and behavior associated with instances of a class are automatically available to
any class associated with a descendant in this tree structure.
 Wrapping of data and methods into a single unit (called class)is known as
“encapsulation”
 Encapsulation makes it possible to treat Object as a blackbox each performing a specific
task without any conceren for internal implementation.

9
Figure 1.3:Encapusulation

 Insulation of the data from direct acess by the program is called as “data hiding”.
 Abstraction refers to the act of representing essential features without including
background details or exaplanations
 Inheritance is the process by which objects of one class acquire the properties of objects
of another class.Inheritance supports the concept of hierarchical classification as shown
below.

Figure 1.4:Property inheritance

 Polymorphism means the ability to take more than one form.For example ,an operation
may exhibit different behaviour in different instance.

10
Figure 1.5:Polymorphism

Applications of Object Oriented Programming


Main application areas of OOP are:
User interface design such as windows, menu.
Real Time Systems
Simulation and Modeling
Object oriented databases
AI and Expert System
Neural Networks and parallel programming
Decision support and office automation systems etc.
1. Client-Server Systems
Object-oriented Client-Server Systems provide the IT infrastructure, creating object-oriented Client-Server
Internet (OCSI) applications. Here, infrastructure refers to operating systems, networks, and hardware. OSCI
consist of three major technologies:
 The Client Server
 Object-Oriented Programming
 The Internet
2. Object-Oriented Databases
They are also called Object Database Management Systems (ODBMS). These databases store objects
instead of data, such as real numbers and integers. Objects consist of the following:

Attributes: Attributes are data that defines the traits of an object. This data can be as simple as integers and
real numbers. It can also be a reference to a complex object.

Methods: They define the behavior and are also called functions or procedures.

3. Object Oriented Databases


These databases try to maintain a direct correspondence between the real-world and database objects in
order to let the object retain their identity and integrity. They can then be identified and operated upon.

4. Real-Time System Design


Real time systems inherit complexities that makes difficult to build them. Object-oriented techniques make it
easier to handle those complexities. These techniques present ways of dealing with these complexities by
providing an integrated framework which includes schedulability analysis and behavioral specifications.

5. Simulation And Modelling System


It’s difficult to model complex systems due to the varying specification of variables. These are prevalent in
medicine and in other areas of natural science, such as ecology, zoology, and agronomic systems.
Simulating complex systems requires modelling and understanding interactions explicitly. Object-oriented
Programming provides an alternative approach for simplifying these complex modelling systems.

6. Hypertext And Hypermedia


OOP also helps in laying out a framework for Hypertext. Basically, hypertext is similar to regular text as it
can be stored, searched, and edited easily. The only difference is that hypertext is text with pointers to other
text as well.Hypermedia, on the other hand, is a superset of hypertext. Documents having hypermedia, not
only contain links to other pieces of text and information, but also to numerous other forms of media,
ranging from images to sound.
11
7. Neural Networking And Parallel Programming
It addresses the problem of prediction and approximation of complex time-varying systems. Firstly, the
entire time-varying process is split into several time intervals or slots. Then, neural networks are developed
in a particular time interval to disperse the load of various networks. OOP simplifies the entire process by
simplifying the approximation and prediction ability of networks.

8. Office Automation Systems


These include formal as well as informal electronic systems primarily concerned with information sharing
and communication to and from people inside as well as outside the organization. Some examples are Email,
Word processing, web calendars, Desktop publishing
9. CIM/CAD/CAM Systems
OOP can also be used in manufacturing and design applications as it allows people to reduce the effort
involved. For instance, it can be used while designing blueprints, flowcharts, etc. OOP makes it possible for
the designers and engineers to produce these flowcharts and blueprints accurately.

10. AI Expert Systems


These are computer applications which are developed to solve complex problems pertaining to a specific
domain, which is at a level far beyond the reach of a human brain. It has the following characteristics:
Reliable,Highly responsive,Understandable,High-performance

1.1.8 Java Buzzwords or Features of Java


The primary objective of Java programming language creation was to make it portable, simple
and secure programming language. Apart from this, there are also some excellent features which
play an important role in the popularity of this language. The features of Java are also known as
java buzzwords.
A list of most important features of Java language is given below.

1. Simple
2. Object-Oriented
3. Platform independent
4. Secured
5. Robust
6. Architecture neutral
7. Portable
8. Dynamic
9. Interpreted
10. High Performance
11. Multithreaded
12. Distributed
12
Figure 1.6: Features of Java

Simple:

Java language is simple because:


1) Syntax is based on C++ (so easier for programmers to learn it after C++).
2) Removed many confusing and/or rarely-used features
Ex.; explicit pointers, operator overloading etc.
3) No need to remove unreferenced objects ,to do this Automatic Garbage Collection in java.
Object-oriented :
Object-Oriented means we organize our software as a combination of different types of objects
that incorporates both data and behavior. Object-oriented programming (OOPs) is a
methodology that simplify software development and maintenance by providing some
principles. They are :

13
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation

Platform Independence :
Java provides software-based platform. The Java platform differs from most other platforms in
the sense that it's a software-based platform that runs on top of other hardware-based platforms.
It has two components:
1. Runtime Environment
2. API(Application Programming Interface)
Java code can be run on multiple platforms e.g.Windows,Linux,SunSolaris,Mac/OS etc. Java
code is compiled by the compiler and converted into bytecode.This bytecode is a platform
independent code because it can be run on multiple platforms i.e. Write Once and Run
Anywhere(WORA).

Figure 1.7: platform independency

14
Secured:
Java is secured because

1. There is no explicit pointers.


2. Programs run inside virtual machine sandbox.

Robust :

Robust simply means strong. Java uses strong memory management. There is automatic
garbage collection in java. There is exception handling and type checking mechanism in java.
All these points makes java robust.

Architecture-neutral:

There are no implementation dependent features Ex.;size of primitive types is set

Portable :

We may carry the java bytecode to any platform.

High-performance:

Java is faster than traditional interpretation since byte code is "close" to native code still
somewhat slower than a compiled language (e.g., C++)

Distributed :

We can create distributed applications in java. RMI and EJB are used for creating distributed
applications. We may access files by calling the methods from any machine on the internet.

Multi-threaded:

A thread is like a separate program, executing concurrently. We can write Java programs that
deal with many tasks at once by defining multiple threads. The main advantage of multi-

15
threading is that it shares the same memory. Threads are important for multi-media, Web
applications etc.

1.1.9 An Overview of Java

Java is a Programming Language and a Platform.

Platform : Any hardware or software environment in which a program runs, known as a platform.
Since Java has its own Runtime Environment (JRE) and API, it is called platform.

History of Java

Java team members (also known as Green Team), initiated a revolutionary task to develop a language
for digital devices such as set-top boxes, televisions etc. It was best suited for internet programming.
Later, Java technology as incorporated by Netscape.

Currently, Java is used in internet programming, mobile devices, games, e-business solutions etc. There
are given the major points that describes the history of java.

James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in June
1991. The small team of sun engineers called Green Team.

Firstly, it was called "Greentalk" by James Gosling and file extension as .gt.After that, it was called
Oak and was developed as a part of the Green project.

Oak is a symbol of strength and chosen as a national tree of many countries like U.S.A., France,
Germany, Romania etc. In 1995, Oak was renamed as "Java" because it was already a trademark by
Oak Technologies. Java is an island of Indonesia where first coffee was produced (called java coffee).

Note: Java is just a name not an acronym.

Java Version History

There are many java versions that has been released.

16
1. JDK Alpha and Beta (1995)
2. JDK 1.0 (23rd Jan, 1996)
3. JDK 1.1 (19th Feb, 1997)
4. J2SE 1.2 (8th Dec, 1998)
5. J2SE 1.3 (8th May, 2000)
6. J2SE 1.4 (6th Feb, 2002)
7. J2SE 5.0 (30th Sep, 2004)
8. Java SE 6 (11th Dec, 2006)
9. Java SE 7 (28th July, 2011)
10. Java SE 8 (18th March, 2014)

Applications using Java: There are mainly 4 type of applications that can be created using java

a. Standalone Application:

It is also known as desktop application or window-based application. An application that we


need to install on every machine such as media player, antivirus etc. AWT and Swing are used
in java for creating standalone applications.

b. Web Application:

An application that runs on the server side and creates dynamic page, is called web application.
Currently, Servlet, JSP, struts, JSF etc. technologies are used for creating web applications in
java.

c. Enterprise Application:

An application that is distributed in nature, such as banking applications etc. It has the
advantage of high level security, load balancing and clustering. In java, EJB is used for creating
enterprise applications.

17
d. Mobile Application:

An application that is created for mobile devices. Currently Android and Java ME are used for
creating mobile applications.

JDK, JRE and JVM

Java Development Kit(JDK)

JDK is an acronym for Java Development Kit.It physically exists.It contains JRE +
development tools.

Figure 1.8: Java Development Kit (JDK)

Java Runtime Environment (JRE) :

JRE is an acronym for Java Runtime Environment.It is used to provide runtime environment.It is the
implementation of JVM.It physically exists.It contains set of libraries + other files that JVM uses at
runtime.implementation of JVMs are also actively released by other companies besides Sun Micro
Systems.

18
Figure 1.9: Java Runtime Environment (JRE)

Java Virtual Machine (JVM)

JVM(Java Virtual Machine) acts as a run-time engine to run Java applications. JVM is the one that
actually calls the main method present in a java code. JVM is a part of JRE(Java Runtime
Environment).

Java applications are called WORA (Write Once Run Anywhere). This means a programmer can
develop Java code on one system and can expect it to run on any other Java enabled system without
any adjustment. This is all possible because of JVM.

JVM is an abstract machine. It is a specification that provides runtime environment in which java
bytecode can be executed . JVMs are available for many hardware and software platforms.

JVM is:

1. A specification where working of Java Virtual Machine is specified. But


implementation provider is independent to choose the algorithm. Its implementation
has been provided by Sun and other companies.
2. An implementationIts implementation is known as JRE (Java Runtime
Environment).
3. Runtime Instance Whenever you write java command on the command prompt to
run the java class, and instance of JVM is created.

NOTE:JVM, JRE and JDK are platform dependent because configuration of each OS differs.
But, Java is platform independent

Internal Architecture of JVM

When we compile a .java file, .class files(contains byte-code) with the same class names
present in .java file are generated by the Java compiler. This .class file goes into various
steps when we run it. These steps together describe the whole JVM.
19
Class Loader Subsystem

It is mainly responsible for three activities.

 Loading
 Linking
 Initialization

Loading : The Class loader reads the .class file, generate the corresponding binary data
and save it in method area.

20
Linking : Performs verification, preparation, and (optionally) resolution.

o Verification : It ensures the correctness of .class file i.e. it check whether this file is
properly formatted and generated by valid compiler or not. If verification
fails, we get run-time exception java.lang.VerifyError.
o Preparation : JVM allocates memory for class variables and initializing the memory to
default values.
o Resolution : It is the process of replacing symbolic references from the type with
direct references. It is done by searching into method area to locate the
referenced entity.

Initialization : In this phase, all static variables are assigned with their values defined in the
code and static block(if any). This is executed from top to bottom in a class and from parent to
child in class hierarchy.

Method area /Class area:In method area, all class level information like class name, immediate parent
class name, methods and variables information etc. are stored, including static variables. There is only
one method area per JVM, and it is a shared resource.

Heap area :Information of all objects is stored in heap area. There is also one Heap Area per JVM. It
is also a shared resource.

Stack area :For every thread, JVM create one run-time stack which is stored here. Every block of this
stack is called “activation record/stack frame” which store methods calls. All local variables of that
method are stored in their corresponding frame. After a thread terminate, it’s run-time stack will be
destroyed by JVM. It is not a shared resource.

PC Registers :Store address of current execution instruction of a thread. Obviously each thread has
separate PC Registers.

Native method stacks :For every thread, separate native stack is created. It stores native method
information.

21
Execution Engine

Execution engine execute the .class (bytecode). It reads the byte-code line by line, use data and
information present in various memory area and execute instructions. It can be classified in three parts
:-

Interpreter : It interprets the bytecode line by line and then executes. The disadvantage here is that
when one method is called multiple times, every time interpretation is required.

Just-In-Time Compiler(JIT) : It is used to increase efficiency of interpreter.It compiles the entire


bytecode and changes it to native code so whenever interpreter see repeated method calls,JIT provide
direct native code for that part so re-interpretation is not required,thus efficiency is improved.

Garbage Collector : It destroy un-referenced objects.

22
Java Native Interface (JNI) :

It is an interface which interacts with the Native Method Libraries and provides the native libraries(C,
C++) required for the execution. It enables JVM to call C/C++ libraries and to be called by C/C++
libraries which may be specific to hardware.

Native Method Libraries :

It is a collection of the Native Libraries(C, C++) which are required by the Execution Engine.

Installation of Java
The following steps will demonstrate the installation of Java

1. Type http://java.sun.com link and press enter.

2. Click on “Java SE” on the right (under “Popular Downloads”.)

23
24
3. On the page that loads, scroll down until you see “Java SE Development Kit (JDK).”
Click on the “Download” button to the right.

NOTE: At the time of writing (January 2009) the latest version of the JDK is 6 Update 11.

4. On the page that loads, choose Windows as your platform, set language to Multi-
Language, and select the checkbox. Finally, click the orange “Continue >>” button.

NOTE: If you are confident that you are on a 64-bit Windows installation, you can select
Windows x64 as your platform, but do not need to do so.

25
5. On the next screen that loads click to download the “Java SE Development Kit.”

NOTE: You may be requested to use the Sun Downloader to download Java. I advise just
using the directly linked full download.

6. Chose to save the file.

26
7. loading the file may take a couple of minutes based on your connection speed.

8. Go to where you downloaded the JDK.

27
9. Launch the installer. If User Account Control given a security warning click the “Yes”
button. The installer should begin loading. Please be patient.

10. Eventually you will be presented with an End User License Agreement (EULA). Read
it before clicking the “Accept >” button.

28
11. For this course, a default installation is completely fine, so just click the
“Next >” button.

NOTE: Pay attention to the “Install to:” location, you will need it later.

12. Be patient while Java installs the JDK.

29
13. You will then be asked to install the Java Runtime Engine (JRE.) Click the “Next >”
button.

14. Be patient while Java installs the JRE.

30
15. You are now done installing Java. All that is left is configuration.

Note: You may be asked to reboot your computer at this point. If you are, please do so.

31
Setting of path and class path

1. Now load the System Information Window by right clicking on “Computer” in the start
menu and selecting properties.

Note: This step can be done in other ways too. Such as…

Right clicking on Computer on the desktop and selecting properties.


 Holding the Windows-key () on your keyboard and pressing the “Pause” key.
(This may require holding FN on some laptops.)

32
2. The System Information Window should load.

3. Click on “Advanced system settings” on the left of the window.

33
4. System Properties window should open with the “Advanced” tab already selected.
Click on “Environment Variables” button.

5. The “Environment Variables” dialog should load.

34
6. In the “System variables” region, scroll down until you see the “Path” variable.

7. Click the lower “Edit” button.

35
8. You should now be editing the “Path” variable.

9. Remember the “Install to:” location on Step 12? That is the line you need to add to the
end of the path. Be sure to prefix the location with a ; and post fix it with bin
Therefore you want to add:
;<YOUR_INSTALL_LOCATION>bin
On MY computer, a Windows 7 beta x64 machines where I installed the 32-bit JDK, that
meant:

; C:\Program Files (x86)\Java\jdk1.6.0_11\bin

WARNING: BE VERY CAREFUL NOT TO OVERWRITE ALL THE


EXISTING ENTRIES IN YOUR PATH!

36
10. Click the “OK” button to confirm your change.

11. Click the “OK” button in the Environment Variables dialog.

37
12. Click the “OK” button in the System Properties dialog.

13. Close the System information window by clicking on the x icon on the top right.

38
14. Now to test our changes. Open the “Command Prompt” by going to:

Start  All Programs  Accessories  Command Prompt

Note: This step can be done in other ways too. Such as…

 Opening the Run Dialog and entering the command “cmd” (without the
quotes.)
 Searching for “Command Prompt” in the start menu.

15. The command prompt should load.

39
16. Enter the command “path” (without the quotes) and press enter. You should see the new
path location, which includes your update.

17. Enter the command “java -version” (without the quotes) and press enter. You should
see the JRE version you have installed.

40
18. Enter the command “javac -version” (without the quotes) and press enter. You should
see the JDK version you have installed.

19. Close the command prompt by click on the x on the top right or typing “exit”
(without the quotes) and pressing enter.

At this point, you can delete the JDK installer that you downloaded on step 6.

41
Setting of CLASSPATH in Java

CLASSPATH: CLASSPATH is an environment variable which is used by Application ClassLoader to


locate and load the .class files. The CLASSPATH defines the path, to find third-party and user-defined
classes that are not extensions or part of Java platform. Include all the directories which contain .class files
and JAR files when setting the CLASSPATH.

You need to set the CLASSPATH if:

o You need to load a class that is not present in the current directory or any sub-directories.
o You need to load a class that is not in a location specified by the extensions mechanism.

There are two ways to ways to set CLASSPATH:

1. Using Command Prompt

2. Using Environment Variable.

1.Setting CLASSPATH in Windows Using Command Prompt


Type the following command in your Command Prompt and press enter.

set CLASSPATH=%CLASSPATH%;C:\Program Files\Java\jre1.8\rt.jar;

In the above command, The set is an internal DOS command that allows the user to change the
variable value. CLASSPATH is a variable name. The variable enclosed in percentage sign (%) is an
existing environment variable. The semicolon is a separator, and after the (;) there is the PATH of
rt.jar file.

2.Setting CLASSPATH in Windows Using Environment Variable.

Let's see how to set CLASSPATH of MySQL database:

Step 1: Click on the Windows button and choose Control Panel. Select System.

Step 2: Click on Advanced System Settings.


Java Programming 43

Step 3: A dialog box will open. Click on Environment Variables.

Step 4: If the CLASSPATH already exists in System Variables, click on the Edit button then put a
semicolon (;) at the end. Paste the Path of MySQL-Connector Java.jar file.

If the CLASSPATH doesn't exist in System Variables, then click on the New button and type Variable
name as CLASSPATH and Variable value as C:\Program Files\Java\jre1.8\MySQL-Connector
Java.jar;.;

Remember: Put ;.; at the end of the CLASSPATH.

43
Java Programming 44

Difference between PATH and CLASSPATH

PATH CLASSPATH

PATH is an environment CLASSPATH is also an environment variable.


variable.

It is used by the operating It is used by Application ClassLoader to locate the .class file.
system to find the executable
files (.exe).

You are required to include the You are required to include all the directories which contain
directory which contains .exe .class and JAR files.
files.

PATH environment variable The CLASSPATH environment variable can be overridden by


once set, cannot be overridden. using the command line option -cp or -CLASSPATH to both
javac and java command.

44
Java Programming 45

Writing and Execution of simple Program

1.Open a simple text editor program such as Notepad and type the following content:

public class HelloWorld


{
public static void main(String[] args)
{
System.out.println("Hello world!");
}
}

2.Save the file as HelloWorld.java (note that the extension is .java) under a directory, let’s say, C:\Java

3.Compile your first Java program

Now let’s compile our first program in the HelloWorld.java file using javac tool.
Syntax: javac programname.java
Type the following command to change the current directory to the one where the source file is stored:

4.Run your first Java program

It’s now ready to run our first Java program. To run java program use following Syntax

Syntax: java programname

That invokes the Java Virtual Machine to run the program called HelloWorld (note that there is no .java or
.class extension). You would see the following output:

45
Java Programming 46

Structure of the Java Program

Structure of a java program is the standard format released by Language developer to the Industry
programmer.

Sun Micro System has prescribed the following structure for the java programmers for developing
java application.

Structure of Java Program Example


package detials import java.lang.*;

class Classname class Demo

{ {

Datamembers int x=10;

user defined methods; void display(){

public static void main(string args[]) System.out.println(“java program structure”);

{ }

block of statements; public static void main(string args[])

} {

} Demo obj=new Demo();

System.out.println(“x value is”+obj.x);

Obj.display();

46
Java Programming 47

A package is a collection of classes, interfaces and sub-packages. A sub package contains collection of
classes, interfaces and sub-sub packages etc. java.lang.*; package is imported by default and this package
is known as default package.

Class is keyword used for developing user defined data type and every java program must start with a
concept of class.

"ClassName" represent a java valid variable name treated as a name of the class each and every class
name in java is treated as user-defined data type.

Data member represents either instance or static they will be selected based on the name of the class.

User-defined methods represents either instance or static they are meant for performing the operations
either once or each and every time.

Each and every java program starts execution from the main() method. And hence main() method is
known as program driver.

Since main() method of java is not returning any value and hence its return type must be void.

Since main() method of java executes only once throughout the java program execution and hence its
nature must be static.

Since main() method must be accessed by every java programmer and hence whose access specifier must
be public.

Each and every main() method of java must take array of objects of String.

Block of statements represents set of executable statements which are in term calling user-defined
methods are containing business-logic.

The file naming conversion in the java programming is that which-ever class is containing main()
method, that class name must be given as a file name with an extension .java.

Lexical Issues In Java


A source code of a Java program consists of tokens. Tokens are atomic code elements. Java programs are a
collection of Tokens such as white space identifiers, comments, literals, operators, separators, and keywords.
Whitespace:

Java is a free-form language. This means that you do not need to follow any special indentation rules. For
example, the Example program could have been written all on one line or in any other strange way you felt like
typing it, as long as there was at least one whitespace character between each token that was not already delineated
by an operator or separator. In java, whitespace is a space, tab, or new line.

47
Java Programming 48

Identifiers:

Identifiers are used for class names, method names, and variable names. An identifier may be any
descriptive sequence of uppercase and lowercase letters, numbers or the underscore and dollar sign characters. They
must not begin with a number, lest they be confused with a numeric literal. Again, java is case-sensitive,
so VALUE is a different identifier the Value. Some examples of valid identifiers are:

AvgTemp count a4 $test this_is_ok

Invalid variable names include:

2count high-temp Not/ok

Literals:

Using a literal representation of it creates a constant value in java. For example, here are some literals:

100 98.6 ‘X’ “This is a test”

Left to right, the first literal specifies an integer, the next is a floating-point value, the third is a character
constant, and the last is a string. A literal can be used anywhere a value of its type is allowed.

Comments:

As mentioned, there are three types of comments defined by java. You have already seen two: single-line
and multilane. The third type is called a documentation comment. This type of comment is used to produce an
HTML file that documents your program. The documentation comment begins with a /** and ends with a*/.
Separators

There are few symbols in java that are used as separators.The most commonly used separator in java is the
semicolon ' ; '. some other separators are Parentheses '( )' , Braces ' {} ' , Bracket ' [] ' , Comma ' , ' , Period ' . ' .

Java Keywords

There are 49 reserved keywords currently defined in java. These keywords cannot be used as names for a variable,
class or method.

1.1.10 Data Types

Every variable has a type, every expression has a type and all types are strictly define .Every assignment
should be checked by the compiler by the type compatibility hence java language is considered as
strongly typed language. In java, There are two types of Data Types:

Primitive Data Types

48
Java Programming 49

Non-Primitive Data Types

1. Primitive Data Types

Data Types make a variable to store a single value at a time

The Eight Primitive data types in Java are:


The integer types:

 byte
 short
 int
 long

The floating-point types:

 float
 double

49
Java Programming 50

Values of class type are references. Strings are references to an instance of class String.

Type Size(bytes) Range Default


byte 1 -128 .. 127 0
short 2 -32768 to32767 0
Int 4 -2147483648 to 2147483647 0

-9223372036854775808 to
long 8 0
9223372036854775807

float 4 3.4 e38 to 1.4 e-45 0.0


double 8 1.e-308 to 4.9e-324 0.0
boolean JVM Specific true or false FALSE
char 2 0 ..65535 \u0000

2. Non-Primitive Data Types:Derived data types are those that are made by using any other data type
and can make a variable to store multiple values ,for example, arrays.
3. User Defined Data Types: User defined data types are those that user / programmer himself
defines. For example, classes, interfaces.
Note : int a

Here a is a variable of int data type.

MyClass obj;

Here obj is a variable of data type MyClass and we call them reference variables as they can be used
to store the reference to the object of that class.

In java char uses 2 byte in java because java uses unicode system rather than ASCII code system.
\u0000 is the lowest range of unicode system.

Unicode System

Unicode is a universal international standard character encoding that is capable of representing

50
Java Programming 51

most of the world's written languages.

1.1.11 Variables

Introduction of variables:

Variable is name of reserved area allocated in memory

int data=10; //Here data is variable

A variable has these attributes:

 Name

1. The string of letters in a program used to designate a variable.


2. A name should start with a letter and consist of letters and/or digits.
3. Variables in names are case sensitive (capitalization matters).
4. The naming convention in Java is to start a variable name with a lower case letter.
5. New words within a name with a name start with a capital letter(example:
numberOfCustomers).

 Value
The binary data contained in memory. The value is interpreted according to the variable's
datatype.

 Address
The location in memory where the value is stored.

 Size
The number of bytes that the variable occupies in memory.

51
Java Programming 52

 Datatype
The interpretation of the value.

 Range
The minimum and maximum values of the variable. The range of a variable depends on its size. In
general, the bigger the size in bytes, the bigger the range.

Declaration of variables:

Syntax:

Datatype variable_name;

Example on variable declarations:


int maxAge;
int x, y, selectedIndex;
char a, b;
boolean flag;
double maxVal, massInKilos;

Initialization of Variable:

Two types of initializations:

i.Compile time initialization

ii.Runtime initialization

i)Compile time initialization:

Syntax:

Datatype variable_name=value;

52
Java Programming 53

Example on Variable initialization in declaration:


int timeInSeconds = 245;
char a = 'K', b = '$';
boolean flag = true;
double maxVal = 35.875;

Dynamic initialization of variable:

Datatype variable_name=Expression;

Example on Dynamic initialization

double a =10.0,b=20.0;

double d=Math.squart(49)+a+b;

ii)Runtime Initialization

In Java, there are three different ways for reading input from the user in the command line
environment(console).

1.Using Buffered Reader Class


2.Using Scanner Class
3.Using Console Class

1.Using Buffered Reader Class:

This is the Java classical method to take input, Introduced in JDK1.0. This method is used by wrapping
the System.in (standard input stream) in an InputStreamReader which is wrapped in a BufferedReader, we
can read input from the user in the command line.

Advantages
The input is buffered for efficient reading.
Drawback:
The wrapping code is hard to remember.

Example program on BufferedReader Class;

import java.io.*;
class Readdemo

53
Java Programming 54

{
public static void main(String args[]) throws IOException
{
int x;String str;
System.out.println("enter x value");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
x=Integer.parseInt(br.readLine());
System.out.println("x value is"+x);
System.out.println("enter ur name");
str=br.readLine();
System.out.println(" ur name is"+str);
}
}

Note: To read other types, we use functions like Integer.parseInt(), Double.parseDouble(). To read
multiple values, we use split().

2. Using Scanner Class

This is probably the most preferred method to take input. The main purpose of the Scanner class is to
parse primitive types and strings using regular expressions, however it is also can be used to read input
from the user in the command line.

Advantages:
Convenient methods for parsing primitives (nextInt(), nextFloat(), …) from the tokenized input.
Regular expressions can be used to find tokens.
Drawback:
The reading methods are not synchronized
class GetInputFromUser
{
public static void main(String args[])
{
// Using Scanner for Getting Input from User
Scanner in = new Scanner(System.in);
System.out.println("enter a string”);
String s = in.nextLine();

System.out.println("enter a integer”);
int a = in.nextInt();

System.out.println("enter a float”);
float b = in.nextFloat();
System.out.println("You entered string "+s);
System.out.println("You entered integer "+a);
System.out.println("You entered float "+b);
}

54
Java Programming 55

}
Output:

enter a string
CMREC
enter a integer
12
enter a float
3.4

You entered string CMREC


You entered integer 12
You entered float 3.4

3. Using Console Class

It has been becoming a preferred way for reading user’s input from the command line. In addition, it can
be used for reading password-like input without echoing the characters entered by the user; the format
string syntax can also be used (like System.out.printf()).
Advantages:

Reading password without echoing the entered characters.


Reading methods are synchronized.
Format string syntax can be used.
Drawback:
Does not work in non-interactive environment (such as in an IDE).

// Java Program to demonstrate Console Methods

import java.io.*;
class ConsoleDemo
{
public static void main(String args[])
{
String str;

55
Java Programming 56

//Obtaining a reference to the console.


Console con = System.console();

// Checking If there is no console available, then exit.


if(con == null)
{
System.out.print("No console available");
return;
}
// Using Console to input data from user
System.out.println(“enter name”);
String name =con.readLine();
System.out.println(name);

//to read password and then display it


System.out.println("Enter the password: ");
char[] ch=con.readPassword();

//converting char array into string


String pass = String.valueOf(ch);
System.out.println("Password is: " + pass);
}
}
Output:

Enter your name: abc


Here is your name: abc
Enter the password:
Password is: xzzzz

Note: System.console() returns null in an online IDE


Types of Variable

There are three types of variables in java


 Local Variable
 Instance Variable
 Static Variable

56
Java Programming 57

Local Variable

A variable that is declared inside the method is called Local variable.

Instance Variable

A variable that is declared inside the class but outside the method is called instance variable .

It is not declared as static.


Static variable

A Variable that is declared as static is called static variable. It cannot be local.

Example to understand the types of variables

class A
{
int data=50;//instance variable
static int m=100;//static variable
void method()
{
int n=90; //local variable
}
} //end of class

Scope and life time of a variable

The scope determines what objects are visible to other parts of program and also determine Lifetime of
the those objects.

In java,scope is defined by the class and by the method.The instance variables and static variables are
declared which the class and out of any method ,so this types variables are available through out the class

57
Java Programming 58

The local variables are declared in side the method .so this avariables are available with the block in
which there are declared.

Type conversion and casting

The process of converting one data type to another data type is called as Casting

Types of castings:

There are two type of castings

1. Explicit type conversion (or) Narrowing conversion


2. Implicit type conversion (or ) Widening conversion

1.Casting Incompatible Types or explicit type conversion or narrowing conversion

Casting larger data type into smaller data type may result in a loss of data.

This kind of conversion is sometimes called a narrowing conversion, since you are explicitly making the
value narrower.

To create a conversion between two incompatible types, you must use a cast. A cast is

simply an explicit type conversion.

It has this general form:

type variable1=(target-type) variable2;


Example:

double m=50.00;

int n=(int)m;

58
Java Programming 59

2.Java’s Automatic Conversions or implicit type conversion or widening conversion

When one type of data is assigned to another type of variable, an automatic type conversion

will take place if the following two conditions are met:

a. The two types are compatible.


b. The destination type is larger than the source type.

When these two conditions are met, a widening conversion takes place.

Example:

int i=30;

double x;

x=i;

The double type is always large enough to hold all valid int values, so no explicit cast statement is

required.

class Typecastdemo

public static void main(String args[])

double f=3.141,x;

int i,j=30;

i=(int)f;//explicit conversion

x=j;//implicit conversion

System.out.println("i value is"+i);

System.out.println("x value is"+x);

59
Java Programming 60

Output: i value is 3

x value is 30.00

Type promotion rules

The sequence of promotion rules that are applied while implicit type conversion is as follows: All
byte,short and char are automatically converted to int; then

1. if one of the operands is long, the other will be converted to long and the result will be long

2. else, if one of the operands is float, the other will be converted to float and the result will be float

3. else, if one of the operands is double, the other will be converted to double and the result will be

.The final result of an expression is converted to the type of the variable on the left of the assignment sign
before assigning the value to it. However the following changes are introduced during the final
assignment.

Float to int causes truncation of the fractional part. Double to float causes rounding of digits.

60
Java Programming 61

Long int to int causes dropping of the excess higher order bits.

1.1.12 Arrays

Introduction

Definition of Array

Normally, array is a collection of similar type of elements that have contiguous memory location.

 Java array is an object the contains elements of similar data type.


 It is a data structure where we store similar elements.
 We can store only fixed set of elements in a java array.
 Array in java is index based, first element of the array is stored at 0 index.
 An array is an indexed collection of fixed number of homogeneous data elements.

Types of Array in java

There are two types of array.

1. Single Dimensional Array


2. Multidimensional Array.

Single Dimensional Array:

Single dimensional array declaration:

Sytax:
Datatype arrayname[ ];
Or
Datatype[ ] arrayname;

Example :

int a[ ];

61
Java Programming 62

int[ ] a; //recommended to use because name is clearly separated from the type int
[ ]a;

At the time of declaration we can’t specify the size otherwise we will get compile time error.

Example :

int[ ] a;//valid

int[5] a;//invalid

Creation of Array construction:

Every array in java is an object hence we can create by using new operator.

Syntax for Creating:

arrayname=new datatype[size];

Example :

a= new int[3];

we can also combine declaration and creation into one step

Syntax Datatype[ ] arrayname= new datatype[size];

Example:

int[] a=new int[3];

Diagram:

62
Java Programming 63

For every array type corresponding classes are available but these classes are part of java
language and not available to the programmer level.
Rules for creating an Array
Rule 1 :

 At the time of array creation compulsory we should specify the size otherwise we will get
compile time error.

Example :

int[] a=new int[3];

int[] a=new int[];//C.E:array dimension missing

Rule 2:

 It is legal to have an array with size zero in java.

Example :

int[] a=new int[0];


System.out.println(a.length);//0

Rule 3 :

 If we are taking array size with -ve int value then we will get runtime exception saying
NegativeArraySizeException.

Example :

int[] a=new int[-3];//R.E:NegativeArraySizeException

Rule 4:

 The allowed data types to specify array size are byte, short, char, int. By mistake if we are using
any other type we will get compile time error.
63
Java Programming 64

Example :

int[] a=new int['a'];//(valid)

byte b=10;

int[] a=new int[b];//(valid)


short s=20;

int[] a=new int[s];//(valid)

int[] a=new int[10l];//C.E:possible loss of precision//(invalid)

int[] a=new int[10.5];//C.E:possible loss of precision//(invalid)

Rule 5 :

 The maximum allowed array size in java is maximum value of int size [2147483647].

Example :

int[] a1=new int[2147483647];(valid)

int[] a2=new int[2147483648];//C.E:integer number too large: 2147483648(invalid)

Array initialization:

Syntax for initialization of Single Dimensional Array:

arrayname[subscript]=value;

Example:

int[] a=new int[4];

a[0]=10;

64
Java Programming 65

a[1]=20;

a[2]=30;

a[3]=40;

a[4]=50;//R.E:ArrayIndexOutOfBoundsException: 4

a[-4]=60;//R.E:ArrayIndexOutOfBoundsException: -4

Diagram:

Note:if we are trying to access array element with out of range index we will
get RuntimeException saying ArrayIndexOutOfBoundsException

Declaration construction and initialization of an array in a single line:

 We can perform declaration construction and initialization of an array in a single line.

Example:

int [] a={10,20,30};//valid

String[] s={"abc","def","jog","lmn”};(valid)

65
Java Programming 66

Whenever we are creating an array every element is initialized with defaultvalue automatically.

Example 1:

int[] a=new int[3];


System.out.println(a);//
System.out.println(a[0]);
Diagram :

Array Length:

length Vs length():

length:

 It is the final variable applicable only for arrays.


 It represents the size of the array.

length() method:

 It is a final method applicable for String objects.


 It returns the no of characters present in the String.

Example:

66
Java Programming 67

int[] x=new int[3];

System.out.println(x.length);//3

System.out.println(x.length());//C.E: cannot find symbol

Example:

String s="bhaskar";
System.out.println(s.length);//C.E:cannot find symbol
System.out.println(s.length());//7

Example on Single Dimensional Array :

class Testarray1
{
public static void main(String args[]){
int a[]={33,3,4,5};//declaration, instantiation and initialization
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}
}
Output :
33
3
4
5

67
Java Programming 68

Array and Functions (or)Passing single dimensional array to a function

Passing Array to method in java. We can pass the java array to method so that we can reuse the same
logic on any array.

Let's see the simple example to get minimum number of an array using method.

class Testarray2 {
static void min(int arr[]) {
int min=arr[0];
for(int i=1;i<arr.length;i++)
if(min>arr[i])
min=arr[i];
System.out.println(min);
}
public static void main(String args[])
{
int a[]={33,3,4,5};
min(a); //passing array to method
}
}
Output: 3

2.Multidimensional Array

Two dimensional array

68
Java Programming 69

 In java multidimensional arrays are implemented as array of arrays approach but not matrix
form.
 The main advantage of this approach is to improve memory utilization.

Two dimensional array declaration:

Datatype arrayname[ ][ ];
Or
Datatype[ ][ ] arrayname;

Alternate two dimensional array Declaration Syntax

int [ ][ ]a;

int [ ][ ]a;

int a[ ] [ ]; All are valid statements

int [ ] [ ]a;

int [ ] a[ ];

int [ ]a[ ];

Example :

Creation of Two- Dimensional array:

69
Java Programming 70

syntax:

arrayname=new datatype[size] [size];

Example:

int a[ ] [ ];

a=new int[3][2];

we can also combine declaration and creation into one step

Syntax

Datatype[ ][ ] arrayname= new datatype[size] [size];

Example1:

Variable Size Array:

int[][] a=new int[3][];

70
Java Programming 71

a[0]=new int[2];

a[1]=new int[4];

a[2]=new int[3];

Two- Dimensional array Array initialization :

Syntax for initialization of Two- Dimensional Array:

datatype [subscript][subscript] arrayname ={list of value};

Example:

int[][] a={{10,20,30},{40,50}};`

Diagram:

If we want to use this short cut compulsory we should perform declaration, construction and
initialization in a single line. If we are trying to divide into multiple lines then we will get compile
time error.

Two Dimensional array length

Length variable applicable only for arrays where as length()method is applicable for String objects.

Example :

int[][] a=new int[6][3];


System.out.println(a.length);//6
System.out.println(a[0].length);//3

71
Java Programming 72

Diagram:

Examples on Two Dimensional array


Example 1: program to declare,create,initialize and access the elements of 2-D array
class array2d

public static void main(String args[]) {

//declaring and initializing 2D array

int arr[][]={{1,2,3},{2,4,5},{4,4,5}};

//printing 2D array

for(int i=0;i<3;i++) {

for(int j=0;j<3;j++) {

System.out.print(arr[i][j]+" ");

System.out.println();

}
}
}
Output:1 2 3
245
445

72
Java Programming 73

Example 2 : program for Addition of two matrix

class twodarrayaddition
{
public static void main(String args[]) {
//creating two matrices
int a[][]={{1,3,4},{3,4,5}};
int b[][]={{1,3,4},{3,4,5}};
//creating another matrix to store the sum of two matrices
int c[][]=new int[2][3];
//adding and printing addition of 2 matrices
for(int i=0;i<2;i++){
for(int j=0;j<3;j++){
c[i][j]=a[i][j]+b[i][j];
System.out.print(c[i][j]+" ");
}
System.out.println();//new line
}
}
}
Output : 2 6 8
6 8 10

73
Java Programming 74

Alternate Three dimensional array declaration Syntax:

int[ ][ ][ ] a;

int [ ][ ][ ]a;

int a[ ][ ][ ]; All are valid statements

int [ ] a[ ][ ];

int [ ][ ]a[ ];

Anonymous Arrays:

Sometimes we can create an array without name such type of nameless arrays are called
anonymous arrays.
The main objective of anonymous arrays is “just for instant use”.
We can create anonymous array as follows.

new int[]{10,20,30,40}; (valid)


new int[][]{{10,20},{30,40}}; (valid)

At the time of anonymous array creation we can’t specify the size otherwise we will get compile time
error.

Example :

new int[3]{10,20,30,40};//C.E:';' expected(invalid)

74
Java Programming 75

Advantage of Java Array

o Code Optimization : It makes the code optimized, we can retrieve or sort the data easily.
o Random access : We can get any data located at any index position.
o Readability : we can represent multiple values with the same name so that readability of the
code will be improved

Disadvantage of Java Array

o Fixed in size that is once we created an array there is no chance of increasing or decreasing
the size based on our requirement that is to use arrays concept compulsory we should know
the size in advance which may not possible always.
o We can resolve this problem by using collections.

1.1.13 Operators

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the
following groups −

 Arithmetic Operators

 Relational Operators

 Bitwise Operators

 Logical Operators

 Assignment Operators

 Misc Operators

The Arithmetic Operators

Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra.
The following table lists the arithmetic operators −

75
Java Programming 76

Assume integer variable A holds 10 and variable B holds 20, then −

Show Examples

Operator Description Example

+ (Addition) Adds values on either side of the operator. A + B will give 30

- (Subtraction) Subtracts right-hand operand from left-hand operand. A - B will give -10

* (Multiplication) Multiplies values on either side of the operator. A * B will give 200

/ (Division) Divides left-hand operand by right-hand operand. B / A will give 2

Divides left-hand operand by right-hand operand and


% (Modulus) B % A will give 0
returns remainder.

++ (Increment) Increases the value of operand by 1. B++ gives 21

-- (Decrement) Decreases the value of operand by 1. B-- gives 19

The Relational Operators

There are following relational operators supported by Java language.

Assume variable A holds 10 and variable B holds 20, then −Show Examples

Operator Description Example

Checks if the values of two operands are equal or not, if yes


== (equal to) (A == B) is not true.
then condition becomes true.

76
Java Programming 77

Checks if the values of two operands are equal or not, if


!= (not equal to) (A != B) is true.
values are not equal then condition becomes true.

Checks if the value of left operand is greater than the value of


> (greater than) (A > B) is not true.
right operand, if yes then condition becomes true.

Checks if the value of left operand is less than the value of


< (less than) (A < B) is true.
right operand, if yes then condition becomes true.

>= (greater than Checks if the value of left operand is greater than or equal to
(A >= B) is not true.
or equal to) the value of right operand, if yes then condition becomes true.

<= (less than or Checks if the value of left operand is less than or equal to the
(A <= B) is true.
equal to) value of right operand, if yes then condition becomes true.

The Bitwise Operators

Java defines several bitwise operators, which can be applied to the integer types, long, int, short, char,
and byte.

Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60 and b = 13; now in
binary format they will be as follows −

a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011

The following table lists the bitwise operators −

Assume integer variable A holds 60 and variable B holds 13 then −

Show Examples

77
Java Programming 78

Operator Description Example

Binary AND Operator copies a bit to


& (bitwise
the result if it exists in both (A & B) will give 12 which is 0000 1100
and)
operands.

Binary OR Operator copies a bit if it


| (bitwise or) (A | B) will give 61 which is 0011 1101
exists in either operand.

Binary XOR Operator copies the bit


^ (bitwise
if it is set in one operand but not (A ^ B) will give 49 which is 0011 0001
XOR)
both.

Binary Ones Complement Operator (~A ) will give -61 which is 1100 0011 in 2's
~ (bitwise
is unary and has the effect of complement form due to a signed binary
compliment)
'flipping' bits. number.

Binary Left Shift Operator. The left


<< (left operands value is moved left by the
A << 2 will give 240 which is 1111 0000
shift) number of bits specified by the right
operand.

Binary Right Shift Operator. The left


>> (right operands value is moved right by the
A >> 2 will give 15 which is 1111
shift) number of bits specified by the right
operand.

Shift right zero fill operator. The left


>>> (zero operands value is moved right by the
fill right number of bits specified by the right A >>>2 will give 15 which is 0000 1111
shift) operand and shifted values are filled
up with zeros.

78
Java Programming 79

The Logical Operators


The following table lists the logical operators −
Assume Boolean variables A holds true and variable B holds false, then −

Show Examples

Operator Description Example

Called Logical AND operator. If both the


&& (logical
operands are non-zero, then the condition (A && B) is false
and)
becomes true.

Called Logical OR Operator. If any of the two


|| (logical or) operands are non-zero, then the condition (A || B) is true
becomes true.

Called Logical NOT Operator. Use to reverses


the logical state of its operand. If a condition is
! (logical not) !(A && B) is true
true then Logical NOT operator will make
false.

The Assignment Operators

Following are the assignment operators supported by Java language −

Show Examples

Operator Description Example

Simple assignment operator. Assigns values from C = A + B will assign value of


=
right side operands to left side operand. A + B into C

Add AND assignment operator. It adds right


C += A is equivalent to C = C
+= operand to the left operand and assign the result
+A
to left operand.

79
Java Programming 80

Subtract AND assignment operator. It subtracts


C -= A is equivalent to C
-= right operand from the left operand and assign the
=C–A
result to left operand.

Multiply AND assignment operator. It multiplies


C *= A is equivalent to C = C
*= right operand with the left operand and assign the
*A
result to left operand.

Divide AND assignment operator. It divides left


C /= A is equivalent to C = C /
/= operand with the right operand and assign the
A
result to left operand.

Modulus AND assignment operator. It takes


C %= A is equivalent to C = C
%= modulus using two operands and assign the result
%A
to left operand.

<<= Left shift AND assignment operator. C <<= 2 is same as C = C << 2

>>= Right shift AND assignment operator. C >>= 2 is same as C = C >> 2

&= Bitwise AND assignment operator. C &= 2 is same as C = C & 2

^= bitwise exclusive OR and assignment operator. C ^= 2 is same as C = C ^ 2

|= bitwise inclusive OR and assignment operator. C |= 2 is same as C = C | 2

Miscellaneous Operators

Miscellaneous operators includes

80
Java Programming 81

 Conditional Operator ( ? : )
 instanceof Operator

There are few other operators supported by Java Language.

Conditional Operator ( ? : )
Conditional operator is also known as the ternary operator. This operator consists of three operands and
is used to evaluate Boolean expressions. The goal of the operator is to decide, which value should be
assigned to the variable. The operator is written as −

variable x = (expression) ? value if true : value if false


Following is an example −

Example

publicclassTest {
publicstaticvoid main(String args[]){
int a, b;
a =10;
b =(a ==1)?20:30;
System.out.println("Value of b is : "+ b );
b =(a ==10)?20:30;
System.out.println("Value of b is : "+ b );
}
}

This will produce the following result −

Output

Value of b is : 30
Value of b is : 20

81
Java Programming 82

instanceof Operator

This operator is used only for object reference variables. The operator checks whether the object is of a
particular type (class type or interface type). instanceof operator is written as −

( Object reference variable ) instanceof (class/interface type)

If the object referred by the variable on the left side of the operator passes the IS-A check for the
class/interface type on the right side, then the result will be true. Following is an example −

Example

publicclassTest{
publicstaticvoid main(String args[]) {
String name ="James";
// following will return true since name is type of String
boolean result = name instanceofString;
System.out.println( result );
}
}

This will produce the following result −

Output

true
This operator will still return true, if the object being compared is the assignment compatible with the
type on the right. Following is one more example −

Example

classVehicle{}
publicclassCarextendsVehicle{
publicstaticvoid main(String args[]){
Vehicle a =newCar();

82
Java Programming 83

boolean result = a instanceofCar;


System.out.println( result );
}
}

This will produce the following result −

Output

true

Precedence of Java Operators

Operator precedence determines the grouping of terms in an expression. This affects how an expression is
evaluated. Certain operators have higher precedence than others; for example, the multiplication operator
has higher precedence than the addition operator −

For example, x = 7 + 3 * 2; here x is assigned 13, not 20 because operator * has higher precedence than +,
so it first gets multiplied with 3 * 2 and then adds into 7.

Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at
the bottom. Within an expression, higher precedence operators will be evaluated first.

Category Operator Associativity

Postfix () Left toright


[]
. (dot operator)
Unary ++ Right to left
--
!
~

83
Java Programming 84

Multiplicative * Left to right


/
%

Additive + Left to right


-

Shift >> Left to right


>>>
<<

Relational > Left to right


>=
<
<=

Equality == Left to right


!=

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = Right to left


+=
-=
*=
/=
%=
>>=
<<=
&=
^=
|=

84
Java Programming 85

ssignment, Arithmetic, and Unary Operators

The Simple Assignment Operator

One of the most common operators that you'll encounter is the simple assignment operator " =".

int cadence = 0;

int speed = 0;

int gear = 1;

The Arithmetic Operators

classArithmeticDemo {

public static void main (String[] args) {

int result = 1 + 2;

// result is now 3

System.out.println("1 + 2 = " + result);

intoriginal_result = result;

result = result - 1;

// result is now 2

System.out.println(original_result + " - 1 = " + result);

original_result = result;

result = result * 2;

// result is now 4

System.out.println(original_result + " * 2 = " + result);

85
Java Programming 86

original_result = result;

result = result / 2;

// result is now 2

System.out.println(original_result + " / 2 = " + result);

original_result = result;

result = result + 8;

// result is now 10

System.out.println(original_result + " + 8 = " + result);

original_result = result;

result = result % 7;

// result is now 3

System.out.println(original_result + " % 7 = " + result);

This program prints the following:

1+2=3

3-1=2

2*2=4

4/2=2

2 + 8 = 10

10 % 7 = 3

86
Java Programming 87

You can also combine the arithmetic operators with the simple assignment operator to create
compound assignments. For example, x+=1; and x=x+1; both increment the value of x by 1.

The + operator can also be used for concatenating (joining) two strings together, as shown in the
following ConcatDemo program:

classConcatDemo

public static void main(String[] args)

String firstString = "This is";

String secondString = " a concatenated string.";

String thirdString = firstString+secondString;

System.out.println(thirdString);

The Unary Operators

The unary operators require only one operand; they perform various operations such as incrementing /
decrementing a value by one, negating an expression, or inverting the value of a boolean.

Operator Description

+ Unary plus operator; indicates positive value (numbers are positive without this, however)

- Unary minus operator; negates an expression

++ Increment operator; increments a value by 1

-- Decrement operator; decrements a value by 1

! Logical complement operator; inverts the value of a boolean

87
Java Programming 88

The following program, UnaryDemo, tests the unary operators:

ClassUnaryDemo {

public static void main(String[] args) {

int result = +1;

// result is now 1

System.out.println(result);

result--;

// result is now 0

System.out.println(result);

result++;

// result is now 1

System.out.println(result);

result = -result;

// result is now -1

System.out.println(result);

boolean success = false;

// false

System.out.println(success);

// true

System.out.println(!success);

88
Java Programming 89

The increment/decrement operators can be applied before (prefix) or after (postfix) the operand. The
code result++; and ++result; will both end in result being incremented by one. The only difference is that
the prefix version (++result) evaluates to the incremented value, whereas the postfix version ( result++)
evaluates to the original value. If you are just performing a simple increment/decrement, it doesn't
really matter which version you choose. But if you use this operator in part of a larger expression, the
one that you choose may make a significant difference.

The following program, PrePostDemo, illustrates the prefix/postfix unary increment operator:

classPrePostDemo {

public static void main(String[] args) {

int i = 3;

i++;

// prints 4

System.out.println(i);

++i;

// prints 5

System.out.println(i);

// prints 6

System.out.println(++i);

// prints 6

System.out.println(i++);

// prints 7

System.out.println(i);

89
Java Programming 90

Equality, Relational, and Conditional Operators


The Equality and Relational Operators
The equality and relational operators determine if one operand is greater than, less than, equal to, or
not equal to another operand. The majority of these operators will probably look familiar to you as
well. Keep in mind that you must use "==", not "=", when testing if two primitive values are equal.
Operator Description
== equal to
!= not equal to
> greater than
>= greater than or equal to
< less than
<= less than or equal to
classComparisonDemo {
public static void main(String[] args) {
int value1 = 1;
int value2 = 2;
if(value1 == value2)
System.out.println("value1 == value2");
if(value1 != value2)
System.out.println("value1 != value2");
if(value1 > value2)
System.out.println("value1 > value2");
if(value1 < value2)
System.out.println("value1 < value2");
if(value1 <= value2)
System.out.println("value1 <= value2");
}
}

90
Java Programming 91

The Conditional Operators

The && and || operators perform Conditional-AND and Conditional-OR operations on two boolean
expressions. These operators exhibit "short-circuiting" behavior, which means that the second operand
is evaluated only if needed.

Operator Description
&& Conditional-AND
|| Conditional-OR

class ConditionalDemo1 {

public static void main(String[] args){

int value1 = 1;

int value2 = 2;

if((value1 == 1) && (value2 == 2))

System.out.println("value1 is 1 AND value2 is 2");

if((value1 == 1) || (value2 == 1))

System.out.println("value1 is 1 OR value2 is 1");

91
Java Programming 92

The following program, ConditionalDemo2, tests the ?: operator:

class ConditionalDemo2 {

public static void main(String[] args){

int value1 = 1;

int value2 = 2;

int result;

booleansomeCondition = true;

result = someCondition ? value1 : value2;

System.out.println(result);

Because someCondition is true, this program prints "1" to the screen. Use the ?: operator instead of
an if-then-else statement if it makes your code more readable; for example, when the expressions
are compact and without side-effects (such as assignments).

Bitwise and Bit Shift Operators

The Java programming language also provides operators that perform bitwise and bit shift operations
on integral types. The operators discussed in this section are less commonly used. Therefore, their
coverage is brief; the intent is to simply make you aware that these operators exist.

The unary bitwise complement operator "~" inverts a bit pattern; it can be applied to any of the integral
types, making every "0" a "1" and every "1" a "0". For example, a byte contains 8 bits; applying this
operator to a value whose bit pattern is "00000000" would change its pattern to "11111111".

The signed left shift operator "<<" shifts a bit pattern to the left, and the signed right shift operator
">>" shifts a bit pattern to the right. The bit pattern is given by the left-hand operand, and the number

92
Java Programming 93

of positions to shift by the right-hand operand. The unsigned right shift operator ">>>" shifts a zero
into the leftmost position, while the leftmost position after ">>" depends on sign extension.

The bitwise & operator performs a bitwise AND operation.

The bitwise ^ operator performs a bitwise exclusive OR operation.

The bitwise | operator performs a bitwise inclusive OR operation.

The following program, BitDemo, uses the bitwise AND operator to print the number "2" to standard
output.

classBitDemo {

public static void main(String[] args) {

int bitmask = 0x000F;

intval = 0x2222;

// prints "2"

System.out.println(val& bitmask);

93
Java Programming 94

1.1.14 Expressions

Expressions, Statements, and Blocks

Definition: An expression is a series of variables, operators, and method calls (constructed according to
the syntax of the language) that evaluates to a single value. As discussed in the previous section, operators
return a value, so the use of an operator is an expression. This partial listing of
the MaxVariablesDemo program shows some of the program's expressions in boldface:

...

// other primitive types

char aChar = 'S';

boolean aBoolean = true;

// display them all

System.out.println("The largest byte value is " + largestByte);

...

if (Character.isUpperCase(aChar)) {

... }

Each expression performs an operation and returns a value, as shown in the following table.

Expression Action Value Returned


Assign the character 'S' to the character The value of aChar after
a Char = 'S'
variable aChar the assignment ('S')
Concatenate the string "The largest byte
"The largest byte value The resulting string: The
value is " and the value
is " + largestByte largest byte value is 127
of largestByte converted to a string
Character.isUpperCase( The return value of the
Call the method isUpperCase
aChar) method: true

94
Java Programming 95

The data type of the value returned by an expression depends on the elements used in the expression. The
expression aChar = 'S' returns a character because the assignment operator returns a value of the same data
type as its operands and aChar and 'S' are characters. As you see from the other expressions, an expression
can return a boolean value, a string, and so on.

The Java programming language allows you to construct compound expressions and statements from
various smaller expressions as long as the data type required by one part of the expression matches the
data type of the other. Here's an example of a compound expression:

x*y*z

. For example, the following expression gives different results, depending on whether you perform the
addition or the division operation first:

x + y / 100 //ambiguous

You can specify exactly how you want an expression to be evaluated, using balanced parentheses—
( and ). For example, to make the previous expression unambiguous, you could write:

(x + y)/ 100 //unambiguous, recommended

If you don't explicitly indicate the order in which you want the operations in a compound expression to be
performed, the order is determined by the precedence assigned to the operators in use within the
expression. Operators with a higher precedence get evaluated first. For example, the division operator has
a higher precedence than does the addition operator. Thus, the two following statements are equivalent:

x + y / 100

x + (y / 100) //unambiguous, recommended

When writing compound expressions, you should be explicit and indicate with parentheses which
operators should be evaluated first. This pratice will make your code easier to read and to maintain.

95
Java Programming 96

1.1.15. Control Statements

A control statement works as a determiner for deciding the next task of the other statements whether to
execute or not. An ‘If’ statement decides whether to execute a statement or which statement has to execute
first between the two. In Java, the control statements are divided into three categories which are selection
statements, iteration statements, and jump statements. A program can execute from top to bottom but if
we use a control statement. We can set order for executing a program based on values and logic, see below
table .

» Decision Making in Java

 Simple if Statement
 if…else Statement
 Nested if statement
 if...else if…else statement
 Switch statement

» Looping Statements in Java

 While
 Do…while
 For
 For-Each Loop

» Branching Statements in Java

 Break
 Continue
 Return

Decision Making in Java

96
Java Programming 97

Decision making statements are statements which decides what to execute and when. They are similar to
decision making in real time. Control flow statements control the flow of a program’s execution. Here
flow of execution will be based on state of a program. We have 4 decision making statements available in
Java.

Simple if Statement :

Simple if statement is the basic of decision-making statements in Java. It decides if certain amount of code
should be executed based on the condition.

Syntax:
if (condition)
{
Statemen 1; //if condition becomes true then this will be executed
}

Statement 2; //this will be executed irrespective of condition becomes true or false

Example:

class ifTest {

public static void main(String args[]) {

int x = 5;

if (x > 10)

System.out.println("Inside If");

System.out.println("After if statement");

Output:

After if statement
97
Java Programming 98

if…else Statement :

In if…else statement, if condition is true then statements in if block will be executed but if it comes out as
false then else block will be executed.

Syntax: if (condition) {

Statemen 1; //if condition becomes true then this will be executed

Example:

class ifelseTest {

public static void main(String args[]) {

int x = 9;

if (x > 10)

System.out.println("i is greater than 10");

else

System.out.println("i is less than 10");

System.out.println("After if else statement");

Output:

98
Java Programming 99

i is less than 10

After if else statement

Nested if statement :

Nested if statement is if inside an if block. It is same as normal if…else statement but they are written
inside another if…else statement.

Syntax: if (condition1)
{
Statemen 1; //executed when condition1 is true
if (condition2)
{
Statement 2; //executed when condition2 is true
}
else
{
Statement 3; //executed when condition2 is false
}
}

Example:

class nestedifTest {

public static void main(String args[]) {

int x = 25;

if (x > 10) {

if (x%2==0)

99
Java Programming 100

System.out.println("i is greater than 10 and even number");

else

System.out.println("i is greater than 10 and odd number");

else {

System.out.println("i is less than 10");

System.out.println("After nested if statement");

Output:

i is greater than 10 and odd number


After nested if statement

if…else statement :

if…else if statements will be used when we need to compare the value with more than 2 conditions. They
are executed from top to bottom approach. As soon as the code finds the matching condition, that block
will be executed. But if no condition is matching then the last else statement will be executed.

Syntax:
if (condition1) {
Statemen 1; //if condition1 becomes true then this will be executed
}
else if (condition2) {
Statement 2; // if condition2 becomes true then this will be executed
}
....
....
else {
Statement 3; //executed when no matching condition found
100
}
Java Programming 101

Example:

class ifelseifTest {

public static void main(String args[]) {

int x = 2;

if (x > 10) {

System.out.println("i is greater than 10");

else if (x <10)

System.out.println("i is less than 10");

else {

System.out.println("i is 10");

System.out.println("After if else if ladder statement");

Output:

i is less than 10

101
Java Programming 102

After if else if ladder statement

Switch statement :

Java switch statement compares the value and executes one of the case blocks based on the condition. It is
same as if…else if ladder. Below are some points to consider while working with switch statements:

» case value must be of the same type as expression used in switch statement
» case value must be a constant or literal. It doesn’t allow variables
» case values should be unique. If it is duplicate, then program will give compile time error

Let us understand it through one example.

class switchDemo{

public static void main(String args[]) {

int i=2;

switch(i){

case 0:

System.out.println("i is 0");

break;

case 1:

System.out.println("i is 1");

break;

case 2:

System.out.println("i is 2");

break;

case 3:

102
Java Programming 103

System.out.println("i is 3");

break;

case 4:

System.out.println("i is 4");

break;

default:

System.out.println("i is not in the list");

break;

Looping Statements in Java :

Looping statements are the statements which executes a block of code repeatedly until some condition
meet to the criteria. Loops can be considered as repeating if statements. There are 3 types of loops
available in Java.

While :

While loops are simplest kind of loop. It checks and evaluates the condition and if it is true then executes
the body of loop. This is repeated until the condition becomes false. Condition in while loop must be
given as a Boolean expression. If int or string is used instead, compile will give the error.

Syntax:
Initialization;
while (condition)
{
statement1;
increment/decrement;
}
103
Java Programming 104

Example:

class whileLoopTest {

public static void main(String args[]) {

int j = 1;

while (j <= 10) {

System.out.println(j);

j = j+2;

Output:

1 3 5 7 9

Do…while :

Do…while works same as while loop. It has only one difference that in do…while, condition is checked
after the execution of the loop body. That is why this loop is considered as exit control loop. In do…while
loop, body of loop will be executed at least once before checking the condition

Syntax: do
{
statement1;
}while(condition);

104
Java Programming 105

Example:

class dowhileLoopTest {

public static void main(String args[]) {

int j = 10;

do {

System.out.println(j);

j = j+1;

} while (j <= 10)

Output: 10

For Statement :

It is the most common and widely used loop in Java. It is the easiest way to construct a loop structure in
code as initialization of a variable, a condition and increment/decrement are declared only in a single line
of code. It is easy to debug structure in Java.

Syntax:
for (initialization; condition; increment/decrement)

statement;

105
Java Programming 106

Example:

class forLoopTest
{
public static void main(String args[])
{
for (int j = 1; j <= 5; j++)
System.out.println(j);
}
}
Output:

For-Each Loop :

For-Each loop is used to traverse through elements in an array. It is easier to use because we don’t have to
increment the value. It returns the elements from the array or collection one by one.

Example:

class foreachDemo {

public static void main(String args[]) {

int a[] = {10,15,20,25,30};

for (int i : a) {

106
Java Programming 107

System.out.println(i);

Output:

10

15

20

25

30

Branching Statements in Java :

Branching statements jump from one statement to another and transfer the execution flow. There are 3
branching statements in Java.

Break :

Break statement is used to terminate the execution and bypass the remaining code in loop. It is mostly
used in loop to stop the execution and comes out of loop. When there are nested loops then break will
terminate the innermost loop.

Example:

class breakTest {

public static void main(String args[]) {

for (int j = 0; j < 5; j++) {

// come out of loop when i is 4.

107
Java Programming 108

if (j == 4)

break;

System.out.println(j);

System.out.println("After loop");

Output:

After loop

Continue :

Continue statement works same as break but the difference is it only comes out of loop for that iteration
and continue to execute the code for next iterations. So it only bypasses the current iteration.

Example:

class continueTest {

public static void main(String args[]) {

108
Java Programming 109

for (int j = 0; j < 10; j++) {

// If the number is odd then bypass and continue with next value

if (j%2 != 0)

continue;

// only even numbers will be printed

System.out.print(j + " ");

Output:

02468

ASIS FOR
BREAK CONTINUE
COMPARISON

Task It terminates the execution of It terminates only the current

remaining iteration of the loop. iteration of the loop.

Control after 'break' resumes the control of the 'continue' resumes the control

break/continue program to the end of loop enclosing of the program to the next

that 'break'. iteration of that loop

enclosing 'continue'.

109
Java Programming 110

Causes It causes early termination of loop. It causes early execution of

the next iteration.

Continuation 'break' stops the continuation of loop. 'continue' do not stops the

continuation of loop, it only

stops the current iteration.

Other uses 'break' can be used with 'switch', 'continue' can not be

'label'. executed with 'switch' and

'labels'.

Return :

Return statement is used to transfer the control back to calling method. Compiler will always bypass any
sentences after return statement. So, it must be at the end of any method. They can also return a value to
the calling method.

1.1.16 Introducing Classes

Class fundamentals

How to create classes by using the following basics:

» The parts of a class definition

» Declaring and using instance variables

» Defining and using methods

» Creating Java applications, including the main() method and how to pass arguments to a
Java program from a command line

110
Java Programming 111

Definition :

A class is a sort of template which has attributes and methods. An object is an instance of a class,
e.g. Ram is an object of type Person.

A class is defined as follows:

class classname {

// declare instance variables

type var1;

type var2;

// ... type varN;

// declare methods

type method1(parameters) {

// body of method

type method2(parameters) {

// body of method

// ...

type methodN(parameters) {

// body of method

The classes we have used so far had only one method, main(), however not all classes specify a
main method. The main method is found in the main class of a program (starting point of
program).

111
Java Programming 112

A Simple Class

Let’s begin our study of the class with a simple example. Here is a class called Box that defines three
instance variables: width, height, and depth. Currently, Box does not contain any methods (but some will
be added soon).

class Box {

double width;

double height;

double depth;

As stated, a class defines a new type of data. In this case, the new data type is called Box. You will use
this name to declare objects of type Box. It is important to remember that a class declaration only creates a
template; it does not create an actual object. Thus, the preceding code does not cause any objects of type
Box to come into existence.

Declaration of Object and its initialization

To create an object of the class we use new keyword as shown below syntaxt

classname objectname=new classname( );


To actually create a Box object, you will use a statement like the following:

Box mybox = new Box(); // create a Box object called mybox

After this statement executes, mybox will be an instance of Box. Thus, it will have “physical” reality.
For the moment, don’t worry about the details of this statement.

As mentioned earlier, each time you create an instance of a class, you are creating an object that
contains its own copy of each instance variable defined by the class. Thus, every Box object will contain
its own copies of the instance variables width, height, and depth. To access these variables, you will use
the dot (.) operator. The dot operator links the name of the object with the name of an instance variable.

112
Java Programming 113

To set the values of the parameters we use the following syntax:

object.member=value;

For example, to assign the width variable of mybox the value 100, you would use the following statement:

mybox.width = 100;

This statement tells the compiler to assign the copy of width that is contained within the mybox object
the value of 100. In general, you use the dot operator to access both the instance variables and the methods
within an object.

Here is a complete program that uses the Box class:

/* A program that uses the Box class. Call this file BoxDemo.java */

class Box {

double width;

double height;

double depth;

// This class declares an object of type Box.

class BoxDemo {

public static void main(String args[]) {

Box mybox = new Box();

double vol;

// assign values to mybox's instance variables

mybox.width = 10;

mybox.height = 20;

mybox.depth = 15;

113
Java Programming 114

// compute volume of box

vol = mybox.width * mybox.height * mybox.depth;

System.out.println("Volume is " + vol);

You should call the file that contains this program BoxDemo.java, because the main( ) method is in the
class called BoxDemo, not the class called Box. When you compile this program, you will find that two
.class files have been created, one for Box and one for BoxDemo. The Java compiler automatically puts
each class into its own .class file. It is not necessary for both the Box and the BoxDemo class to actually
be in the same source file. You could put each class in its own file, called Box.java and BoxDemo.java,
respectively.

To run this program, you must execute BoxDemo.class. When you do, you will see the following output:

Volume is 3000.0

As stated earlier, each object has its own copies of the instance variables. This means that if you have
two Box objects, each has its own copy of depth, width, and height. It is important to understand that
changes to the instance variables of one object have no effect on the instance variables of another.

Constructors
 Constructor is a special type of method that is used to initialize the object.
 Constructor is invoked at the time of object creation. It constructs the values i.e. provides data
for the object that is why it is known as constructor.
Rules for creating Constructor
There are basically two rules defined for the constructor.

1. Constructor name must be same as its class name


2. Constructor must have no explicit return type
Types of Constructors
There are two types of constructors:

1. default constructor (no-arg constructor)


114
Java Programming 115

2. parameterized constructor

1) Default Constructor

A constructor that have no parameter is known as default constructor.

Syntax of Default Constructor:

class_name( )

Statements;

Example of Default Constructor

In this example, we are creating the no-arg constructor in the DefaultConstructor class. It will be invoked
at the time of object creation.

class DefaultConstructor
{
DefaultConstructor()
{
System.out.println("hai");
}
public static void main(String args[])
{
DefaultConstructor obj=new DefaultConstructor();
}
}

115
Java Programming 116

Output: hai

Rule: If there is no constructor in a class, compiler automatically creates a default constructor.

Purpose of Default Constructor

Default constructor provides the default values to the object like 0, null etc. depending on the
typeExample of default constructor that displays the default values

class DefaultC
{
int stdid;
String name;
static void dispaly()
{
System.out.println("stdid"+"");
System.out.println("name"+"");
}
public static void main(String args[])
{
Output: dc=new DefaultC();
DefaultC
dc.display();
}0 null
}
Explanation : In the above class,you are not creating any constructor so compiler provides you a default
constructor. Here 0 and null values are provided by default constructor.
2. Parameterized constructor
A constructor that have parameters is known as parameterized constructor.

116
Java Programming 117

Usage of Parameterized Constructor

Parameterized constructor is used to provide different values to the distinct objects.

Example on Parameterized constructor :.

class Paraconstructor
{
int stdid;
String name;
Paraconstructor(int x,String n)
{
stdid=x;
name=n;
}
void display()
{
System.out.println("stdid is"+""+stdid);
System.out.println("name is"+""+name);
}
public static void main(String args[])
{
Paraconstructor obj1=new Paraconstructor(5,"abc");
obj1.display();
Paraconstructor obj2=new Paraconstructor(7,"def");
obj2.display();
}
}

Output:

stdid is 5

name is abc

stdid is 7

name is def

117
Java Programming 118

Difference between constructor and method

Constructor Method

Constructor is used to initialize the state of an


Method is used to expose behaviour of an object.
object.

Constructor must not have return type. Method must have return type.

Constructor is invoked implicitly. Method is invoked explicitly.

The java compiler provides a default constructor


Method is not provided by compiler in any case.
if you don't have any constructor.

Constructor name must be same as the class Method name may or may not be same as class
name. name.

Understanding of This Keyword


Sometimes a method will need to refer to the object that invoked it. To allow this, Java defines
the ‘this’ keyword. this can be used inside any method to refer to the current object. That is,
this is always a reference to the object on which the method was invoked. You can use this
anywhere a reference to an object of the current class’ type is permitted.
To better understand what this refers to, consider the following version of Box( ):
/* Here, Box uses a parameterized constructor to initialize the dimensions of a box.*/
class Box {
double width;
double height;
double depth;
// This is the constructor for Box.
Box(double w, double h, double d) {
this.width = w;
this.height = h;
this.depth = d;
}
// compute and return volume
double volume() {

118
Java Programming 119

return width * height * depth;


}
}
class BoxDemo {
public static void main(String args[]) {
// declare, allocate, and initialize Box objects
Box mybox1= new Box(10, 20, 15);
Box mybox2 = new Box(3, 6, 9);

double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
The use of this is redundant, but perfectly correct. Inside Box( ), this will always refer to the invoking
object.

Instance Variable Hiding


Because this lets you refer directly to the object, you can use it to resolve any name space collisions
thatmight occur between instance variables and local variables. For example, here is another version of
Box( ), which uses width, height, and depth for parameter names and then uses this to access the instance
variables by the same name:
// Use this to resolve name-space collisions.
Box(double width, double height, double depth) {
this.width = width;
this.height = height;
this.depth = depth;
}
Aword of caution: The use of this in such a context can sometimes be confusing, and
some programmers are careful not to use local variables and formal parameter names that
hide instance variables. Of course, other programmers believe the contrary—that it is a good
convention to use the same names for clarity, and use this to overcome the instance variable
hiding. It is a matter of taste which approach you adopt.

119
Java Programming 120

1.1.17 Methods and Classes

Class Methods in Java

A method is a collection of statements that are grouped together to perform an operation.

Methods describe behavior of an object.

For example, if we have a class Human, then this class should have methods like eating(), walking(),
talking(), etc, which in a way describes the behaviour which the object of this class will have.

Syntax: return-type methodName(parameter-list)

//body of method

Example of a Method:

public String getName(String st) {

String name="StudyTonight";

name=name+st;

return name;

120
Java Programming 121

Modifier : Modifier are access type of method. We will discuss it in detail later.

Return Type : A method may return value. Data type of value return by a method is declare in method
heading.

Method name : Actual name of the method.

Parameter : Value passed to a method.

Method body : collection of statement that defines what method does.

Parameter Vs. Argument in a Method :

While talking about method, it is important to know the difference between two
terms parameter and argument.

Parameter is variable defined by a method that receives value when the method is called. Parameter are
always local to the method they dont have scope outside the method. While argument is a value that is
passed to a method when it is called.

Overloading:

Overloading:

Overloading is a machanisum by which Java supports polymorphism.

In Java we have 2 types of Overloading namely

121
Java Programming 122

i)Method Overloading

ii)Constructor Overloading

i)Method overloading:

In Java it is possible to define two or more methods within the same class that share the
same name, as long as their parameter declarations are different. When this is the case, the methods are
said to be overloaded, and the process is referred to as method overloading. Method overloading is one of
the ways that Java supports polymorphism.

When an overloaded method is invoked, Java uses the type and/or number of arguments as its
guide to determine which version of the overloaded method to actually call.

Example on Method Overloading

class Methodoverload
{
void display()
{
System.out.println("display method without arguements");
}
void display(int a)
{
System.out.println("display method with integer"+""+a);
}
void display(int a,double b)
{
System.out.println("display method with integer"+a+"and double"+b);
}
public static void main(String args[])
{
Methodoverload obj=new Methodoverload();
obj.display();
obj.display(10);
obj.display(20,65.99);
}
}

Output:

display method without arguments

122
Java Programming 123

display method with integer 10

display method with integer 20 and double 65.99

Constructor Overloading:

In addition to overloading normal methods, you can also overload constructor methods

class Coverload
{

int a;double b;
Coverload()
{
System.out.println("constructor without parameters");
}
Coverload(int i)
{
a=i;
System.out.println("constructor with one parameter");
System.out.println("a value is"+a);
}
Coverload(int i,double d)
{
a=i;
b=d;

System.out.println("constructor with two parameter");


System.out.println("a value is"+a);
System.out.println("b value is"+b);
}
public static void main(String args[])
{
Coverload obj1=new Coverload();
Coverload obj2=new Coverload(10);
Coverload obj3=new Coverload(40,29.99);
}
}

Output:

constructor without parameters

123
Java Programming 124

constructor with one parameter


a value is 10
constructor with two parameter
a value is 40
b value is29.99

Recursion:

Recursion:

Java supports recursion. Recursion is the process of defining something in terms of itself. As it relates to
Java programming, recursion is the attribute that allows a method to call itself. Amethod that calls itself
is said to be recursive.

Example on Recursion:

class Recursion
{
int fact(int n)
{
int result;
if(n==0||n==1)
return 1;
else
result=n*fact(n-1);
return result;
}
public static void main(String args[])
{
int ans;
Recursion obj=new Recursion();
ans=obj.fact(5);
System.out.println("factorial of 5 is"+ans);
}
}

Output:factorial of 5 is 120.

124
Java Programming 125

Parameter passing Techniques (or) call-by-value and call-by-reference

call-by-value and call-by-reference :

There are two ways to pass an argument to a method

1. call-by-value : In this approach copy of an argument value is pass to a method. Changes made to
the argument value inside the method will have no effect on the arguments.
2. call-by-reference : In this reference of an argument is pass to a method. Any changes made inside
the method will affect the agrument value.

Example of call-by-value:

public class Test {


public void callByValue(int x) {
x=100;
}
public static void main(String[] args) {
int x=50;
Test t = new Test();
t.callByValue(x); //function call
System.out.println(x);
}
}
Output: 50

125
Java Programming 126

Example of call-by-Reference:
public class CBRTest {
int a;
CBRTest(int i)
{
a=i;
}
public void callByReference(CBRTest obj)
{
obj.a=obj.a+10;
}
public static void main(String[] args)
{
CBRTest obj = new CBRTest(10);
System.out.println("before calling a value is"+obj.a);
obj.callByReference(obj)//function call by passing object
System.out.println("after calling a value is"+obj.a);
}
}

Output:

before calling a value is 10

after calling a value is 20

NOTE: When a primitive type is passed to a method, it is done by use of call-by-value. Objects are
implicitly passed by use of call-by-reference.

126
Java Programming 127

Understanding of Static and Final Keyword

Static Keyword:
The static keyword in Java is used for memory management mainly. We can apply java static keyword
with variables, methods, blocks and nested class. The static keyword belongs to the class than an instance
of the class.

The static can be:

i. Variable (also known as a class variable)


ii. Method (also known as a class method)
iii. Block

i)Java static variable

If you declare any variable as static, it is known as a static variable.

The static variable can be used to refer to the common property of all objects (which is not unique for each
object), for example, the company name of employees, college name of students, etc.

The static variable gets memory only once in the class area at the time of class loading.

Advantages of static variable

It makes your program memory efficient (i.e., it saves memory).

Understanding the problem without static variable

class Student{

int rollno;

String name;

String college="CMREC";

Suppose there are 500 students in my college, now all instance data members will get memory each time
when the object is created. All students have its unique rollno and name, so instance data member is good
in such case. Here, "college" refers to the common property of all objects. If we make it static, this field
will get the memory only once.

127
Java Programming 128

Note:Java static property is shared to all objects

//Java Program to demonstrate the use of static variable

class Student{

int rollno;//instance variable

String name;

static String college ="CMREC";//static variable

Note:As we have mentioned above, static variable will get the memory only once, if any object changes
the value of the static variable, it will retain its value

class Counter{

static int count=0;//will get memory only once and retain its value

Counter(){

count++;//incrementing the value of static variable

System.out.println(count);

public static void main(String args[]){

//creating objects

Counter c1=new Counter();

Counter c2=new Counter();

Counter c3=new Counter();

Output:

128
Java Programming 129

ii) Java static method

If you apply static keyword with any method, it is known as static method.

o A static method belongs to the class rather than the object of a class.
o A static method can be invoked without the need for creating an instance of a class.
o A static method can access static data member and can change the value of it.

class Calculate{
static int cube(int x){
return x*x*x;
}
public static void main(String args[]){
int result=Calculate.cube(5);
System.out.println(result);
}
}

Restrictions for the static method

There are two main restrictions for the static method. They are:

 The static method can not use non static data member or call non-static method directly.
 this and super cannot be used in static context.

iii) Java static block

Is used to initialize the static data member.

It is executed before the main method at the time of classloading.

Example:

class Demo{

static{System.out.println("static block is invoked");}

public static void main(String args[]){

System.out.println("Hello main");

129
Java Programming 130

Output:

static block is invoked

Hello main

Final Keyword In Java:


The final keyword in java is used to restrict the user. The java final keyword can be used in many context.
Final can be:
 variable
 method
 class
 if a variable is made as final it cannot change its value
Example:
class Demo
{

int a=10;

final int b=20;

public static void main(String arg[])

a=a+10;

System.out.println(a);

b=b+20;//error because variable ‘b’ is final

System.out.println(b);

130
Java Programming 131

 if a method is made as final it cannot override it.

Class Demo

Final void display( )

System.out.println(“hello”);

Class FinalDemo extends Demo

void display( ) //overriding is not premitted

System.out.println(“hello”);

public static void main(String arg[])

FinalDemo fd=new FinalDemo();

fd. display( );

If a class is made as final it cannot be extended by another class

131
Java Programming 132

Program to demonstrate using final with inheritance

final class A
{

Class B extends A //error since A is final we can’t inherit it properties


{
void display()
{
System.out.println("demo on final");
}

public static void main(String args[]){


B obj=new B();
Obj.display();
}
}

symbolic constants
Symbolic constants in Java are named constants. Constants may appear repeatedly in number of
places in the program. Constant values are assigned to some names at the beginning of the
program, then the subsequent use of these names in the program has the effect of caving their
defined values to be automatically substituted in appropriate points. The constant is declared as
follows:

Syntax : final datatype symbolicname= value;

Eg: final float PI =3.14159;


final int STRENTH =100;

Rules :-

1. Symbolic names take the some form as variable names. But they one written in capitals to
distance from variable names. This is only convention not a rule.

2.After declaration of symbolic constants they shouldn’t be assigned any other value within the
program by using an assignment statement.

132
Java Programming 133

For eg:- STRENTH = 200 is illegal

3. They can’t be declared inside a method. They should be used only as class data members in the
beginning of the class.

class SymbolicDemo

static final int A=10;

static final double PI=3.141;

public static void main(String args[])

//final int A=10;

//final double PI=3.141;

int a=20,sum;

double r=30.49;

sum=A+a;

System.out.println("sum is "+sum);

double area=PI*r*r;

System.out.println("area is "+area);

//A=A+1;//ERROR CANNOT ASSIGN A VALUE FOR FINAL VARIABLE

133
Java Programming 134

Introduction of Nested and Inner classes


Nested classes in Java

A class declared inside a class is known as nested class.

We use nested classes to logically group classes and interfaces in one place so that it can be more
readable and maintainable code.

Additionally, nested class can access all the members of outer class including private data members
and methods but viceverse is not possible

Syntax of Nested class

class Outer_class_Name

...

class Nested_class_Name

...

...

Advantage of nested classes

There are basically three advantages of nested classes. They are

• Nested classes represent a special type of relationship that is it can access all the members
(data members and methods) of outer class including private.

• Nested classes are used to develop more readable and maintainable code because it logically
group classes and interfaces in one place only.

134
Java Programming 135

• Code Optimization: It requires less code to write.

Types of Nested class:

There are two types of nested classes non-static and static nested classes.

The Non-static nested classes are also known as Inner classes.

1. Non-static nested class(inner class)

a)Member inner class

b) Local inner class

c) Annomynous inner class

2. Static nested class

135
Java Programming 136

1.Member inner class

A class that is declared inside a class but outside a method is known as member inner
class.

Invocation of Member Inner class

 From within the class


 From outside the class

Example of member inner class :

In this example, we are invoking the method of member inner class from the display method of Outer
class.

class Outer
{
private int data=20;
class MemberInner
{
void message()
{
System.out.println("private data of outerclass is"+data);
}
}
void display()
{
MemberInner in=new MemberInner();
in.message();
}
public static void main(String args[])
{
Outer out=new Outer();
out.display();
}
}
Output:
private data of outerclass is 20

136
Java Programming 137

2) Local inner class

A class that is created inside a method is known as local inner class. If you want to invoke the
methods of local inner class, you must instantiate this class inside the method.

Program of local inner class


class Outer{
private int data=30;//instance variable
void display()
{
class LocalInner
{
void massage()
{
System.out.println("private data of outer class"+data);
}
}
LocalInner in=new LocalInner();
in.massage();
}
public static void main(String args[]){
Outer obj=new Outer();
obj.display();
}
}
Output:

private data of outer class 30

Rules for Local Inner class

1) Local inner class cannot be invoked from outside the method.

2) Local inner class cannot access non-final local variable.

3)Annonymous inner class

A class that have no name is known as annomymous inner class.

Example:

Program of annonymous inner class by abstract class

abstract class Demo

137
Java Programming 138

{
abstract void display();
}
class Annomynous
{
public static void main(String args[])
{

Demo obj=new Demo()


{
void display()
{
System.out.println("Demo on annomynous inner class");
}
};
obj.display();
}
}
Output: Demo on annomynous inner class

4)static nested class

A static class that is created inside a class is known as static nested class. It cannot access the non-static
members outer class.

 It can access static data members of outer class including private.


 static nested class cannot access non-static (instance) data member or method.

Program of static nested class that have instance method


class Outer{
static int data=30;

static class Inner


{
void msg(){System.out.println("data is "+data);}
}

public static void main(String args[]){


Outer.Inner obj=new Outer.Inner();
obj.msg();
}
}

Output:data is 30

138
Java Programming 139

In this example, you need to create the instance of static nested class because it has
instance method msg(). But you don't need to create the object of Outer class because nested class is
static and static properties, methods or classes can be accessed without object.

1.1.18 Java String

Introduction to Java string class and String object

 String is a sequence of characters. But in java, string is an object that represents a sequence of
characters. The java.lang.String class is used to create string object.

For example:

char[] ch={'j','a','v','a'};

String s=new String(ch);

is same as:

String s="java";

 Java String class provides a lot of methods to perform operations on string such as compare(),
concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.

There are two ways to create String object:

i. By String Literal
ii. By new keyword

i) String Literal

Java String literal is created by using double quotes. For Example:

String s="welcome";

Each time you create a string literal, the JVM checks the string constant pool first. If the string already
exists in the pool, a reference to the pooled instance is returned. If string doesn't exist in the pool, a new
string instance is created and placed in the pool. For example:

139
Java Programming 140

String s1="Welcome";
String s2="Welcome";//will not create new instance

ii) By new keyword

String s= new String("Welcome"); //creates two objects and one reference variable

In such case, JVM will create a new string object in normal(non pool) heap memory and the literal
"Welcome" will be placed in the string constant pool. The variable s will refer to the object in heap(non
pool).

Java String Example:

public class StringExample


{
public static void main(String args[])
{
String s1="java";//creating string by java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to string
String s3=new String("example");//creating java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}
}
140
Java Programming 141

String manipulation methods

Java String class method

String objects are immutable, whenever you want to modify a String, you must

either copy it into a StringBuffer or StringBuilder, or use one of the following String methods,

which will construct a new copy of the string with your modifications complete.

The java.lang.String class provides many useful methods to perform operations on sequence of char
values

No. Method Description

1 char charAt(int index) returns char value for the particular index

2 int length() returns string length

3 static String format(String format, returns formatted string


Object... args)

4 String substring(int beginIndex, int returns substring for given begin index and end
endIndex) index

5 boolean contains(CharSequence s) returns true or false after matching the


sequence of char value

6 static String join(CharSequence returns a joined string


delimiter, CharSequence...
elements)

7 boolean equals(Object another) checks the equality of string with object

141
Java Programming 142

8 boolean isEmpty() checks if string is empty

9 String concat(String str) concatinates specified string

10 String replace(char old, char new) replaces all occurrences of specified char value

11 String replace(CharSequence old, replaces all occurrences of specified


CharSequence new) CharSequence

12 static String compares another string. It doesn't check case.


equalsIgnoreCase(String another)

13 String[] split(String regex) returns splitted string matching regex

14 String[] split(String regex, int limit) returns splitted string matching regex and limit

15 int indexOf(int ch) returns specified char value index

16 int indexOf(int ch, int fromIndex) returns specified char value index starting with
given index

17 int indexOf(String substring) returns specified substring index

18 int indexOf(String substring, int returns specified substring index starting with
fromIndex) given index

19 String toLowerCase() returns string in lowercase.

142
Java Programming 143

20 String toUpperCase() returns string in uppercase.

21 String trim() removes beginning and ending spaces of this


string.

22 static String valueOf(int value) converts given type into string. It is


overloaded.

Program on StringHandling :

public class StringhandlingExample

public static void main(String args[])

String name="JAVA PROGRAMMING";

String s1="hello";

String s2="hello";

String joinstring,stringlower,stringupper;

char ch=name.charAt(4);//returns the char value at the 4th index

System.out.println(ch);

System.out.println(s1.compareTo(s2));//0 because both are equal

System.out.println(s1.equals(s2));//true because content and case is same

System.out.println("string length is: "+s1.length());//5 is the length of hello string

joinstring=string.join(“welcome”, “to”, “javaprogramming”);

System.out.println(joinstring); //welcome to javaprogramming

143
Java Programming 144

stringlower=name.toLowerCase( );

System.out.println(stringlower); // javaprogramming

stringupper= s1.toUpperCase();

System.out.println(stringupper); //HELLO

System.out.println(s1.trim()+"javaprogramming");//hellojavaprogramming

//space between s1 contents and javaprogramming is removed

StringBuffer

Java StringBuffer class is used to create mutable (modifiable) string. The StringBuffer
class in java is same as String class except it is mutable i.e. it can be changed.

StringBuffer Constructors

Important Constructors of StringBuffer class

Constructor Description

StringBuffer() creates an empty string buffer with the initial capacity of


16.

StringBuffer(String str) creates a string buffer with the specified string.

StringBuffer(int creates an empty string buffer with the specified capacity


capacity) as length.

144
Java Programming 145

Important methods of StringBuffer class

Modifier Method Description


and Type

public append(String s) is used to append the


synchronized specified string with this
StringBuffer string. The append()
method is overloaded like
append(char),
append(boolean),
append(int),
append(float),
append(double) etc.

public insert(int offset, is used to insert the


synchronized String s) specified string with this
StringBuffer string at the specified
position. The insert()
method is overloaded like
insert(int, char),
insert(int, boolean),
insert(int, int), insert(int,
float), insert(int, double)
etc.

public replace(int is used to replace the


synchronized startIndex, int string from specified
StringBuffer endIndex, String str) startIndex and endIndex.

public delete(int startIndex, is used to delete the string


synchronized int endIndex) from specified startIndex
StringBuffer and endIndex.

public reverse() is used to reverse the


synchronized string.
StringBuffer

public int capacity() is used to return the


current capacity.

public void ensureCapacity(int is used to ensure the


minimumCapacity) capacity at least equal to
the given minimum.

145
Java Programming 146

public char charAt(int index) is used to return the


character at the specified
position.

public int length() is used to return the


length of the string i.e.
total number of
characters.

public String substring(int is used to return the


beginIndex) substring from the
specified beginIndex.

public String substring(int is used to return the


beginIndex, int substring from the
endIndex) specified beginIndex and
endIndex.

Command-Line Arguments

Sometimes you will want to pass information into a program when you run it. This is

accomplished by passing command-line arguments to main( ). A command-line argument is

the information that directly follows the program’s name on the command line when it is

executed.

To access the command-line arguments inside a Java program is quite easy—

they are stored as strings in a String array passed to the args parameter of main( ). The first

command-line argument is stored at args[0], the second at args[1], and so on.

146
Java Programming 147

Example 1:

The following program displays all of the command-line arguments that it is called with:

// Display all command-line arguments.

class CommandLine {
public static void main(String args[]) {
for(int i=0; i<args.length; i++)
System.out.println("args[" + i + "]: " +args[i]);
}
}
Running:
C:>\ java CommandLine have a nice time
output:
args[0]:have
args[1]: a
args[2]:nice
args[3]:time
REMEMBER All command-line arguments are passed as strings.

Example 2:

Program to add to numbers that are passed through command prompt

class CommandLine
{
public static void main(String args[])
{
int a,b,sum;
a=Integer.parseInt(args[0]);
b=Integer.parseInt(args[1]);
sum=a+b;
System.out.println("addition of"+a+"and"+b+"is"+sum);
}
}

147
Java Programming 148

1.
Inherirance Concept

Inheritance is the mechanism of deriving new class from old one, old class is knows as superclass and new
class is known as subclass. The subclass inherits all of its instances variables and methods defined by the
superclass and it also adds its own unique elements. Thus we can say that subclass are specialized version
of superclass.

Benefits of Java’s Inheritance

1. Reusability of code
2. Code Sharing
3. Consistency in using an interface

1. Inherirance Basics

Defination:The process by which one class acquires the properties(data members) and functionalities
(methods) of another class is called inheritance.

(or)

Inheritance is a process of defining a new class based on an existing class by extending its common data
members and methods.

Child Class:

The class that extends the features of another class is known as child class, sub class or derived class.

Parent Class:

The class whose properties and functionalities are used(inherited) by another class is known as parent
class, super class or Base class.

148
Java Programming 149

Inheritance allows us to reuse of code, it improves reusability in your java application.

The biggest advantage of Inheritance is that the code that is already present in base class need not be
rewritten in the child class.This means that the data members(instance variables) and methods of the
parent class can be used in the child class .Child class has to write only the unique features and rest of
the common properties and functionalities can be extended from the another class.

Syntax: Inheritance in Java

To inherit a class we use extends keyword. Here class XYZ is child class and class ABC is parent
class. The class XYZ is inheriting the properties and methods of ABC class.

class XYZ extends ABC

Types of inheritance

1. Single Inheritance
2. Multilevel inheritance
3. Hierarchical inheritance
4. Multiple Inheritance

1.Single Inheritance: refers to a child and parent class relationship where a class extends the another
class.

149
Java Programming 150

Program to demonstrate Single Level Inheritance:


class A
{
int i=10;
void Adisplay()
{
System.out.println("class A display");
}
}
class B extends A
{
int j=20;
void Bdisplay()
{
System.out.println("class B display");
}
public static void main(String args[])
{
B obj=new B();
obj.Adisplay();
obj.Bdisplay();
System.out.println("i value is "+obj.i);
System.out.println("j value is "+obj.j);
}
}

class A display

class B display

i value is 10

j value is 20

2.Multilevel inheritance: refers to a child and parent class relationship where a class extends the child
class. For example class C extends class B and class B extends class A.

150
Java Programming 151

Program to demonstrate Multi Level Inheritance:

class A
{
A()
{
System.out.println("A constructor");
}
void Amethod()
{
System.out.println("method of A");
}
}
class B extends A
{
B()
{
System.out.println("B constructor");
}
void Bmethod()
{
System.out.println("method of B");
}
void welcome()
{
System.out.println("class B-welcome method");
}
}
class C extends B
{
C()
{
System.out.println("C constructor");
}
void welcome()
{
System.out.println("class C- welcome method");

}
public static void main(String args[])
{
C oc=new C();
oc.Amethod();
oc.Bmethod();
oc.welcome();

151
Java Programming 152

}
}

Output:

A constructor

B constructor

C constructor

method of A

method of B

method of A

3.Hierarchical inheritance: refers to a child and parent class relationship where more than one classes
extends the same class. For example, classes B, C & D extends the same class A.

class A
{
A()
{
System.out.println("A constructor");
}
void Amethod()
{
System.out.println("method of A class");
}
}
class B extends A
{

152
Java Programming 153

B()
{
System.out.println("B constructor");
}
void Bmethod()
{
System.out.println("method of B class");
}
}
class D extends A
{
D()
{
System.out.println("D constructor");
}
void Dmethod()
{
System.out.println(" method of D class");
}
public static void main(String args[])
{
D od=new D();
od.Amethod();
od.Dmethod();
B ob=new B();
ob.Amethod();
ob.Bmethod();
}

Output:

A constructor
D constructor
method of A class
method of D class
A constructor
B constructor
method of A class
method of B class

153
Java Programming 154

4.Multiple Inheritance: refers to the concept of one class extending more than one classes, which means
a child class has two parent classes. For example class C extends both classes A and B. Java doesn’t
support multiple inheritances.

5.Hybrid inheritance: Combination of more than one types of inheritance in a single program. For
example class A & B extends class C and another class D extends class A then this is a hybrid inheritance
example because it is a combination of single and hierarchical

154
Java Programming 155

inheritance.

1. Member Access

Member Access and Inheritance

An instance variable of a class will be declared private to prevent its unauthorized use or tampering.
Inheriting a class does not overrule the private access restriction. Thus, even though a subclass includes
all of the members of its superclass, it cannot access those members of the superclass that have been
declared private. For example, if, as shown here, width and height are made private in TwoDShape,
then Triangle will not be able to access them:

//private members are not inherited

//This program does not compile….

Class PrivateAccess

155
Java Programming 156

private int a=10;

private int b=20;

int c;

void display()

c=a+b;

System.out.println(c);

Class Demo extends PrivateAccess

Void sub()

c=a-b;//error private member a and b can’t be inherited.

Java-Superclass Variable Can Reference a Subclass Object


Superclass Variable Can Reference a Subclass Object
A reference variable of a superclass can be assigned a reference to any subclass derived from that
superclass. In the following program, obj is a reference to NewData object, Since NewData is a subclass
of Data, it is permissible to assign obj a reference to the NewData object. When a reference to a subclass
object is assigned to a superclass reference variable, you will have access only to those parts of the object
defined by the superclass. This is way obj can’t access data3 and data4 even it refers to a NewData object.
Program

156
Java Programming 157

157
Java Programming 158

1. Creating Multilevel Hierarchy


Create multilevel hierarchy
It is nothing but the enhancement of the Simple Inheritance. From the type name, it is pretty much clear
that Inheritance is done at ‘n’ number of levels, where n>1.
In simple inheritance, a subclass or derived class derives the properties from its parent class, but in
multilevel inheritance, a subclass is derived from a derived class. One class inherits the only single class.
Therefore, in multilevel inheritance, every time ladder increases by one. The lowermost class will have
the properties of all the superclass.

Program to demonstrate Multi Level Inheritance/hierarchy:

class A
{
A()
{
System.out.println("A constructor");
}
void Amethod()
{
System.out.println("method of A");
}
}
class B extends A
{
B()
{
System.out.println("B constructor");
}
void Bmethod()
{
System.out.println("method of B");
}
void welcome()
{
System.out.println("class B-welcome method");

158
Java Programming 159

}
}
class C extends B
{
C()
{
System.out.println("C constructor");
}
void welcome()
{
System.out.println("class C- welcome method");

}
public static void main(String args[])
{
C oc=new C();
oc.Amethod();
oc.Bmethod();
oc.welcome();

}
}

Output:

A constructor

B constructor

C constructor

method of A

method of B

method of A

159
Java Programming 160

Note: Multilevel inheritance is not multiple inheritances where one class can inherit more than one class
at a time. Java does not support multiple inheritances.

1. Super Uses

super keyword in java

The super keyword in java is a reference variable which is used to refer immediate parent class object.

Whenever you create the instance of subclass, an instance of parent class is created implicitly which is
referred by super reference variable

Usage of java super Keyword

1. super can be used to refer immediate parent class instance variable.


2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor.

The use of super keyword

1) super is used to refer immediate parent class instance variable.

We can use super keyword to access the data member or field of parent class. It is used if parent class and
child class have same fields.

2) super can be used to invoke parent class method

The super keyword can also be used to invoke parent class method. It should be used if subclass contains
the same method as parent class. In other words, it is used if method is overridden.

160
Java Programming 161

Example program to demonstrating invoking of parent class instance variable and parent class method

class A
{
int data=10;
void display()
{
System.out.println(" A class display");
}
}

class B extends A
{
int data=20;

void display()
{
System.out.println(" B class display");
}
void superdisplay()
{
System.out.println("data in A class is"+super.data);
super.display();
}
public static void main(String args[])
{
B obj=new B();
obj.display();
System.out.println(obj.data);
obj.superdisplay();
}
}

Output

B class display
20
data in A class is 10
A class display

161
Java Programming 162

3) super is used to invoke parent class constructor.

The super keyword can also be used to invoke the parent class constructor.

class Parentclass
{
Parentclass()
{
System.out.println("Constructor of parent class");
}
}
class Subclass extends Parentclass
{
Subclass()
{
//Compile implicitly adds super() here as the first statement of this
constructor.
System.out.println("Constructor of child class");
}
Subclass(int num)
{
// Even though it is a parameterized constructor The compiler still adds the super() here
System.out.println("arg constructor of child class");
}
void display()
{
System.out.println("Hello!");
}
public static void main(String args[])
{
Subclass obj= new Subclass();
//Calling sub class method
obj.display();
Subclass obj2= new Subclass(10);
obj2.display();
}
}

Output:
Constructor of parent class

162
Java Programming 163

Constructor of child class


Hello!
Constructor of parent class
arg constructor of child class
Hello!

1. Using Final with Inheritance


.

The final keyword in java is used to restrict the user. The java final keyword can be used in many context.
Final can be:
 variable
 method
 class

if a variable is made as final it cannot change its value

if a method is made as final it cannot override it.

If a class is made as final it cannot be extended by another class

Program to demonstrate using final with inheritance

final class A
{

Class B extends A //error since A is final we can’t inherit it properties


{
void display()
{
System.out.println("demo on final");
}

public static void main(String args[]){


B obj=new B();
Obj.display();
}
}

163
Java Programming 164

1. Polymorphism-ad hoc polymorphism

Polymorphism in Java is a concept by which we can perform a single action in different ways.
Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly" means many and
"morphs" means forms. So polymorphism means many forms.

There are two types of polymorphism in Java:

1. Compile-time polymorphism or Ad hoc polymorphism


2. Runtime polymorphism. Or Pure polymorphism

We can perform polymorphism in java by method overloading and method overriding.

If you overload a static method in Java, it is the example of compile time polyymorphism.

164
Java Programming 165

1. Compile-time polymorphism or Ad hoc polymorphism:

Ad hoc polymorphism is also known as function overloading or operator overloading because a


polymorphic function can represent a number of unique and potentially different implementations
depending on the type of argument it is applied to.

The term ad hoc in this context is not intended to be pejorative; it refers simply to the fact that this type
of polymorphism is not a fundamental feature of the type system.

i)operator overloading:

Java also provide option to overload operators. For example, we can make the operator (‘+’) for string
class to concatenate two strings. We know that this is the addition operator whose task is to add two
operands. So a single operator ‘+’ when placed between integer operands, adds them and when placed
between string operands, concatenates them.

In java, Only “+” operator can be overloaded:

Example on Operator overloading

// Java program for Operator overloading

class Operatoroverloading {

void operator(String str1, String str2)


{
String s = str1 + str2;
System.out.println("Concatinated String - "+ s);
}

void operator(int a, int b)


{
int c = a + b;
System.out.println("Sum = " + c);
}
}

class Main {
public static void main(String[] args)
{
Operatoroverloading obj = new Operatoroverloading ();
obj.operator(2, 3);
obj.operator("CMR", "EC");
}
}
165
Java Programming 166

Output:

Sum = 5

Concatinated String -CMREC

ii)Method Overloading:

When there are multiple functions with same name but different parameters then these functions are said
to be overloaded. Functions can be overloaded by change in number of arguments or/and change in type
of arguments. Overloaded methods are generally used when they conceptually execute the same task but
with a slightly different set of parameters.

Example on method overloading


class MultiplyFun {

// Method with 2 parameter


static int Multiply(int a, int b)
{
return a * b;
}
// Java program for Method overloading
// Method with 3 parameter
static int Multiply(int a, int b,int c)
{
return a * b*c;
}

// Method with the same name but 2 double parameter


static double Multiply(double a, double b)
{
return a * b;
}
}

class Main {
public static void main(String[] args)
{

System.out.println(MultiplyFun.Multiply(2, 4));
System.out.println(MultiplyFun.Multiply(2, 4,2));
System.out.println(MultiplyFun.Multiply(5.5, 6.3));
}
}
166
Java Programming 167

Output:
8
16
34.65

Note:
we overload static methods
we cannot overload methods that differ only by static keyword
we overload main() in Java

2. Runtime polymorphism. Or Pure polymorphism

Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an overridden


method is resolved at runtime rather than compile-time.

In this process, an overridden method is called through the reference variable of a superclass. The
determination of the method to be called is based on the object being referred to by the reference
variable.

Let's first understand the upcasting before Runtime Polymorphism.

Upcasting

If the reference variable of Parent class refers to the object of Child class, it is known as upcasting.

For example:

class A{}

167
Java Programming 168

class B extends A{}

A a=new B();//upcasting .

Example of Java Runtime Polymorphism

In this example, we are creating two classes A and B. B class extends A class and overrides its
display ()method. We are calling the display ()by the reference variable of Parent class. Since it refers to
the subclass object and subclass method overrides the Parent class method, the subclass method is
invoked at runtime.
Since method invocation is determined by the JVM not compiler, it is known as runtime polymorphism.

class A
{
void display ()
{
System.out.println(" A class display ");
}
}
class B extends A
{
void display ()
{
System.out.println(" B class display ");
}
public static void main(String args[])
{
A obj = new B();//upcasting
obj. display ();
}
}

Output:

B class display

Advantages of dynamic binding along with polymorphism with method overriding are.

o Less memory space

168
Java Programming 169

o Less execution time


o More performance

Difference between Static & Dynamic Polymorphism

Static Polymorphism Dynamic Polymorphism

Compile time polymorphism or static


Run time polymorphism or dynamic polymorphism or
1 polymorphism relates to method
dynamic binding relates to method overriding.
overloading.
Difference between Method overloading and Method overriding
Method overloading Method overriding

1 When a class have same method Method overriding - Method of superclass is overridden in
name with different argument, subclass to provide more specific implementation.
than it is called method
overloading.

2 Method overloading is generally Method overriding is always done in subClass in java.


done in same class but can also
be done in SubClass .

3 Both Static and instance method Only instance methods can be overridden in java.
can be overloaded in java.
Static methods can’t be overridden in java.

4 Main method can also be Main method can’t be overridden in java, because main is
overloaded in java static method and static methods can’t be overridden in java (as
mentioned in above point)

5 private methods can be private methods can’t be overridden in java, because private
overloaded in java. methods are not inherited in subClass in java.

6 final methods can be overloaded final methods can’t be overridden in java, because final
in java. methods are not inherited in subClass in java.

7 Call to overloaded method is Call to overridden method is bonded at runtime in java.


bonded at compile time in java.

8 Method overloading concept is Method overriding concept is also known as runtime time
also known as compile time polymorphism or pure polymorphism or Dynamic binding
polymorphism or ad hoc in java.

169
Java Programming 170

polymorphism or static binding


in java.

1. Method Overriding

In this process, an overridden method is called through the reference variable of a superclass. The
determination of the method to be called is based on the object being referred to by the reference
variable.variable of the current object.

Let's first understand the upcasting before Runtime Polymorphism.

Upcasting

If the reference variable of Parent class refers to the object of Child class, it is known as upcasting

class A{}

class B extends A{}

A a=new B();//upcasting

class A
{
void display ()
{
System.out.println(" A class display ");
}
}
class B extends A
{
void display ()
{
System.out.println(" B class display ");
}
public static void main(String args[])
{
A obj = new B();//upcasting
170
obj. display ();
}
}
Java Programming 171

Output:

B class display

1. Abstract Classes

Abstract class in Java

 A class that is declared with abstract keyword, is known as abstract class in java.
 It can have abstract and non-abstract methods (method with body).
 It needs to be extended and its method implemented.
 It cannot be instantiated.

Example abstract class

abstract class A

Abstract method

A method that is declared as abstract and does not have implementation is known as abstract method.

Example abstract method

abstract void printStatus();//no body and abstract

171
Java Programming 172

Example on abstract class and method(or)Example on multilevel inheritance using abstract

abstract class Hello


{
abstract void hai();
}
abstract class Demo extends Hello
{
}
class Welcome extends Demo
{
void hai()
{
System.out.println("hello");
}
}
public class AbstractClass {
public static void main(String args[])
{
//Hello oa=new Hello();//error because for abstract class we can't create object
//Demo ob=new Demo();//error because for abstract class we can't create object
Welcome oh=new Welcome();
oh.hai();
}
}

Output:hello

172
Java Programming 173

Difference Between Abstract and Concrete class

Abstract Class Concrete Class


Abstract class contain abstract method(i.e a Concrete class can’t contain abstract method
method without implementation)along with
concrete methods
For Abstract class object cannot be created For Concrete class object can be created.
Abstract classes need to be extended in order to Concrete class need not be extended because it is a
make it complete class complete class
Abstract methods of abstract class need to be All concrete methods contain implementations.
implemented in subclass/child class
Example: Example:
abstract class demo class demo
{ {
abstract hai(); void welcome()
void welcome() {
{ System.out.println(“welcome”);
System.out.println(“welcome”); }
} }
}

Object Class

There is one special class, Object, defined by Java.

The Object class is the parent class of all the classes in java by default.

Object is a superclass of all other classes. This means that a reference variable of type Object can refer to
an object of any other class.

The parent class reference variable can refer the child class object, know as upcasting.

173
Java Programming 174

Methods of Object class

The Object class provides many methods. They are as follows:

Method Description

public final Class getClass() returns the Class class object of this object. The Class class can
further be used to get the metadata of this class.

public int hashCode() returns the hashcode number for this object.

public boolean equals(Object obj) compares the given object to this object.

protected Object clone() throws creates and returns the exact copy (clone) of this object.
CloneNotSupportedException

public String toString() returns the string representation of this object.

public final void notify() wakes up single thread, waiting on this object's monitor.

public final void notifyAll() wakes up all the threads, waiting on this object's monitor.

public final void wait(long causes the current thread to wait for the specified milliseconds,
timeout)throws until another thread notifies (invokes notify() or notifyAll()
InterruptedException method).

public final void wait(long causes the current thread to wait for the specified milliseconds
timeout,int nanos)throws and nanoseconds, until another thread notifies (invokes notify()
InterruptedException or notifyAll() method).

public final void wait()throws causes the current thread to wait, until another thread notifies
InterruptedException (invokes notify() or notifyAll() method).

protected void finalize()throws is invoked by the garbage collector before object is being
Throwable garbage collected.

174
Java Programming 175

The methods getClass( ), notify( ), notifyAll( ), and wait( ) are declared as final. So we cannot override
this methods and rest of the methods can be overridden.

Forms of Inheritance-Specialization

Forms of Inheritance :

All objects eventually inherit from Object, which provides useful methods such as equals and toString.

In general we want to satisfy substitutability: if B is a subclass of A, anywhere we expect an instance


of A we can use an instance of B.

Inheritance gets used for a number of purposes in typical object-oriented programming:

Specification inheritance:

If the parent class is abstract, we often say that it is providing a specification for the child class,
and therefore it is specification inheritance (a variety of specialization inheritance).

Specialization inheritance:

The superclass just specifies which methods should be available but doesn't give code.

This is supported in java by interfaces and abstract methods

Construction inheritance

The superclass just specifies which methods should be available but doesn't give code.

This is supported in java by interfaces and abstract methods

Extension inheritance

The superclass is just used to provide behavior, but instances of the subclass don't really act like the
superclass. Violates substitutability. Exmample: defining Stack as a subclass of Vector. This is not clean
-- better to define Stack as having a field that holds a vector

If a child class generalizes or extends the parent class by providing more functionality, but does not
override any method, we call it inheritance for generalization.

175
Java Programming 176

The child class doesn't change anything inherited from the parent, it simply adds new features.

An example is Java Properties inheriting form Hashtable. subclass adds new methods, and perhaps
redefines inherited ones as well

Inheritance for Limitation

• If a child class overrides a method inherited from the parent in a way that makes it unusable (for
example, issues an error message), then we call it inheritance for limitation.

• For example, you have an existing List data type that allows items to be inserted at either end, and
you override methods allowing insertion at one end in order to create a Stack.

• Generally not a good idea, since it breaks the idea of substitution. But again, it is sometimes found
in practice. the subclass restricts the inherited behavior. Violates substitutability. Example: defining
Queue as a subclass of Dequeue.

Combination

The child class inherits features from more than one parent class. This is multiple inheritance .

Summary of Forms of Inheritance

Specialization. The child class is a special case of the parent class; in other words, the child class is a
subtype of the parent class.

Specification. The parent class defines behavior that is implemented in the child class but not in the
parent class.

Construction. The child class makes use of the behavior provided by the parent class, but is not a
subtype of the parent class.

Generalization. The child class modifies or overrides some of the methods of the parent class.

Extension. The child class adds new functionality to the parent class, but does not change any inherited
behavior.

Limitation. The child class restricts the use of some of the behavior inherited from the parent class.

Variance. The child class and parent class are variants of each other, and the class-subclass relationship
is arbitrary.

176
Java Programming 177

Combination. The child class inherits features from more than one parent class. This is multiple
inheritance .

Benefits of Inheritance

Benefit of using inheritance:

 A code can be used again and again


 Inheritance in Java enhances the properties of the class, which means that property of the
parent class will automatically be inherited by the base class
 It can define more specialized classes by adding new details.
 In addition we have benefits such as

 Software Reuse
 Code Sharing
 Improved Reliability
 Consistency of Interface
 Rapid Prototyping
 Polymorphism
 Information Hiding

Cost of Inheritance

 Execution speed
 Program size
 Message Passing Overhead
 Program Complexity

This does not mean you should not use inheritance, but rather than you must understand the benefits, and
weigh the benefits against the costs.

177
Java Programming 178

[JNTUH-PREVIOUS QUESTION PAPERS]


UNIT WISE SHORT QUESTION

UNIT-I

1. What is data abstraction? [2M]


2. Explain the feature of Java [2M]
3. Explain the types of operators used in java [3M]
4. What is static inner class [3M]
5. List string manipulation functions of Java String class. [3M]
6. Explain the use of ‘final’ keyword. [3M]
7. Differentiate between class and object. [2M]
8. What is meant by ad-hoc polymorphism? [3M]
9. What is abstract class? Give example. [2M]
10. What is inheritance? Give example. [2M]
11. Define the basic characteristics of object oriented programming. [3M]
12. Explain the use of ‘for’ statement in Java with an example. [3M]
13. What is the significance of Java’s byte code? [2M]
14. List the applications of object oriented programming. [3M]
15. Differentiate between break and continue statement. [2M]
16. What is type casting? Explain with an example. [3M]
17. What is the use of super keyword? [2M]
18. Why is Java known as platform independent? [3M]
19. What is the size of char data type? Why does it differ from C language? [3M]
20. Differentiate between print() and println() methods in Java [2M]
21. What are symbolic constants? Explain with examples. [3M]
22. Program to convert foreign heat to centigrade [3M]
23. Program to find sum of given number [3M]
24. Program to display [3M]
25. What is the purpose of this Keyword [3 M]
26. Explain about enumerated data type . [3 M]
27. What is Anonymous inner class . [3 M]
28. what is the difference between abstract class and concrete class [2 M]
29. What are Lexical issues in java [2M]
30. Write about console. [3 M]

178
Java Programming 179

JNTUH-PREVIOUSLY ASKED _ESSAY_QUESTIONS

1.a)What are the responsibilities of an agent?


b) What is the purpose of constructor in Java programming? [5+5]
2. Define inheritance. What are the benefits of inheritance? What costs are associated with inheritance?
How to prevent a class from inheritance? [10 M]
3. Write a program to demonstrate hierarchical and multiple inheritance using interfaces [10 M]
4. a)Describe the structure of a typical Java program with an example.
b) What are the benefits of inheritance? Explain the various forms of inheritance with suitable code
segments [5+5]
5Write the significance of Java Virtual Machine. [5 M]
6.a) How do we implement polymorphism in JAVA? Explain briefly.
b) What is an array? How do you declare the array in java? Give examples. [5+5]
7.a) What is meant by byte code? Briefly explain how Java is platform independent.
b) Explain the significance of public, protected and private access specifies in Inheritance.
[5+5]
8.a) Explain different parts of a Java program with an appropriate example.
b) How does polymorphism promote extensibility? Explain with example. [5+5]
9. What are the drawbacks of procedural languages? Explain the need of object oriented
programming with suitable program. [10 mark]
10.a) Does Java support multi way selection statement? Justify your answer.
b) Describe type promotion rules of Java. [5+5]
11.a) Explain the basic concepts of object oriented programming.
b) What is the usage of enumerated data type? Give examples. [5+5]
12.a) Discuss Java jump statements.
b) Write about garbage collection in Java.
c) Explain the use of ‘this’ keyword. [3+3+4]

13.a) Explain method overriding with a suitable example program.


b) With suitable program segments describe the usage of ‘super’ keyword. [5+5]
14 What is a nested class? Differentiate between static nested classes and non-static nested classes.
15.a) What is inheritance and how does it help to create new classes quickly.
b) Describe different levels of access protection available in Java. [5+5]
16.a) List the primitive data types available in Java and explain.
b) What is polymorphism? Explain different types of polymorphisms with examples.
[5+5]

179
Java Programming 180

17.a) What are the drawbacks of procedural languages? Explain the need of object oriented
programming with suitable program.
b) Discuss the lexical issues of Java. [5+5]
18.a) What are the primitive data types in Java? Write about type conversions.
b) What is a constructor? What is its requirement in programming? Explain with program.
[5+5]

19.a) With suitable code segments illustrate various uses of ‘final’ keyword.
b) Discuss about anonymous inner classes. [5+5]
20.a) What feature of Java makes it platform independent and portable?
b) Program to find sum of given number

21. Explain about anonymous inner clas


22.a)write a java Program to display
1
12
123
1234
12345
b) Compare and cons tract overloading and overriding with an example [5+5]
23 a).Different data types in java
b.)Program to convert foreign heat to centigrade [5+5]
24 a) Explain multilevel inheritance with the help of abstract class in your programb)
b)Is Java a robust language? Justify your answer. [5+5]
25.a) Differentiate between a class and object.
b) Demonstrate constructor overloading concept. [5+5]
26 a) Write a java program to find the factorial of a given number.
b) Explain the different types of constructors with an example. [5+5]
27 a) Write a program to find the transpose of a given matrix.
b) Explain the scope and life time of the variable. [5+5]
28 a) Explain the different parameter passing mechanisms used in Java with an example.
b) Write a runtime polymorphism program in Java by using interface reference variable.
[5+5]

180
Packages ,Interfaces
And Stream Based
Input /Output
Java Programming 2

2.1 Packages

2.1.1 Introduction to packages

A java package is a group of similar types of classes, interfaces and sub-packages.

Package in java can be categorized in two form,

i) built-in package and


ii) user-defined package.

Built-in package:

Collection of classes & interfaces which are already defined are called as Build-in packages.

There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.

user-defined packages:

The collection of classes and interfaces for which definition is provided by the
developer or programmer are called as user-defined packages.

2
Java Programming 3

2.1.2 Defining a user-defined package

To create a user defined package in java we use a keyword “package”

Syntax:

package packagename[.subpackage1][.subpackage2]…[.subpackageN];

Sample program on userdefined package:

//save as Simple.java

package mypack;

public class Simple

public static void main(String args[])

System.out.println("Welcome to package");

compile java package:

If you are not using any IDE, you need to follow the syntax given below:

Syntax:

3
Java Programming 4

javac -d directory javafilename

For example

1. javac -d . Simple.java

The -d switch specifies the destination where to put the generated class file. You can
use any directory name like /home (in case of Linux), d:/abc (in case of windows) etc.
If you want to keep the package within the same directory, you can use . (dot).

run java package program:

You need to use fully qualified name e.g. mypack.Simple etc to run the class.

To Compile: javac -d . Simple.java

To Run: java mypack.Simple

Output:Welcome to package

The -d is a switch that tells the compiler where to put the class file i.e. it represents
destination. The . represents the current folder.

2.1.3 CLASSPATH Setting

CLASS PATH environment variable setting is used by java run time system to know
where to look for package that is created.

For example, consider the following package specification:

package MyPack

the class path must not include MyPack, itself.

4
Java Programming 5

It must simply specify the path to MyPack. For example, in a Windows environment, if
the path to MyPack is
C:\MyPrograms\Java\MyPack
Then the class path to MyPack is
C:\MyPrograms\Java
Example:
package MyPack;
class Demo
{
…….
…….
}
class classpathdemo
{
public static void main(String args[])
{
Demo obj=new Demo();
………
}
}

Call this file classpathdemo.java and put it in a directory called MyPack.

Next, compile the file. Make sure that the resulting .class file is also in the MyPack directory.

Then, try executing the classpathdemo class, using the following command line:

java MyPack.classpathdemo

Remember, you will need to be in the directory above MyPack when you execute this
command.

5
Java Programming 6

2.1.4 Importing packages

There are three ways to access the package from outside the package.

1. import package.*;

2. import package.classname;

3. fully qualified name.

1) Using packagename.*

 If you use package.* then all the classes and interfaces of this package will be
accessible but not subpackages.
 The import keyword is used to make the classes and interface of another
package accessible to the current package.

Example of package that import the packagename.*

//let us save this program in D:/pack folder as A.java

package pack;
public class A
{
public void msg()
{
System.out.println("Hello");
}
}

6
Java Programming 7

Compile as: D:/pack>javac –d . A.java

//save it D floder as B.java

import pack.*;
class B
{
public static void main(String args[])
{
A obj = new A();
obj.msg();
}

Compile as: D:\>javac B.java

Run as :D:\> java B

Output:Hello

________________________________________

2) Using packagename.classname

 If you import package.classname then only declared class of this package will
be accessible.

7
Java Programming 8

Example of package by import package.classname

package pack;
public class A
{
public void msg()
{
System.out.println("Hello");
}
}

import pack.A;
class B
{
public static void main(String args[])
{
A obj = new A();
obj.msg();
}
}

Output:Hello

8
Java Programming 9

3) Using fully qualified name

 If you use fully qualified name then only declared class of this package will be
accessible. Now there is no need to import. But you need to use fully qualified
name every time when you are accessing the class or interface.
 It is generally used when two packages have same class name e.g. java.util and
java.sql packages contain Date class.

Example of package by import fully qualified name

package pack;
public class A
{
public void msg()
{
System.out.println("Hello");
}
}

class B
{
public static void main(String args[])
{
pack.A obj = new pack.A();//using fully
qualified name
obj.msg();
}
}

9
Java Programming 10

Output:Hello

Note: If you import a package, subpackages will not be imported.

If you import a package, all the classes and interface of that package will be imported
excluding the classes and interfaces of the subpackages. Hence, you need to import the
subpackage as well.

Implicit and Explicit import statement

Imports can be categorized as explicit (for example import java.util.List;) or implicit


(also known as 'on-demand', for example import java.util.*;):

Implicit imports give access to all visible types in the type (or package) that precedes
the ".*"; types imported in this way never shadow other types.

Explicit imports give access to just the named type; they can shadow other types that
would normally be visible through an implicit import, or through the normal package
visibility rules.

Example

The following example uses implicit imports. This means that it is not clear to a
programmer where the List type on line 5 is imported from.

import java.util.*; // AVOID: Implicit import statements


import java.awt.*;

public class Customers {


public List getCustomers() { // Compiler error: 'List' is ambiguous.
...
}
}
To improve readability, the implicit imports should be replaced by explicit imports. For
example, import java.util.*; should be replaced by import java.util.List; on line 1.

10
Java Programming 11

2.1.5 Access protection or Access Modifiers

There are two types of modifiers in java: access modifier and non-access modifier. The access modifiers
specifies accessibility (scope) of a datamember, method, constructor or class.

There are 4 types of access modifiers:

1. private

2. default

3. protected

4. public

There are many non-access modifiers such as static, abstract, synchronized, native, volatile, transient etc.

1) private access modifier:

The private datamembers, method ,contructor are accessible only within class in which their are declared and
out of the class the doesn’t have scope.
Example of private access modifier:
In this example, we have created two classes ‘A’ and ‘Simple’. ‘A’ class contains private data member and
private method. We are accessing these private members from outside the class, so there is compile time error.

class A
{
private int data=40;
private void msg()
{
System.out.println("Hello java");
}
}
public class Simple
{
public static void main(String args[])
{
A obj=new A();
System.out.println(obj.data);//Compile
11 Time Error
obj.msg();//Compile Time Error
}
}
Java Programming 12

Role of Private Constructor:


If you make any class constructor private, you cannot create the instance of that class from outside the class.
For example:

class A
{
private A( )
{
}//private constructor
void msg( )
{
System.out.println("Hello java");
}
}
public class Simple
{
public static void main(String args[])
{
A obj=new A( );//Compile Time Error
}
}

Note: A class cannot be private or protected except nested class


2) default access modifier:
If you don't use any modifier, it is treated as default by default. The default modifier is accessible only within
package.
Example of default access modifier:
In this example, We are accessing the A class from outside its package, since A class is not public, so it cannot
be accessed from outside the package.

12
Java Programming 13

//save by A.java

package pack;
class A
{
void msg( )
{
System.out.println("Hello");
}
}

//save by B.java

import pack.*;
class B
{
public static void main(String args[])
{
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
}

In the above example, the scope of class A and its method msg() is default so it cannot be accessed from outside
the package.

3) protected access modifier:


The protected access modifier is accessible within package and outside the package but through
inheritance only.

13
Java Programming 14

The protected access modifier can be applied on the data member, method and constructor. It can't be
applied on the class.

Example of protected access modifier


In this example, we have created the two packages “pack” and “ mypack”. The A class of pack package
is public, so can be accessed from outside the package. But msg method of this package is declared as protected,
so it can be accessed from outside the class only through inheritance.

package pack;
public class A
{
protected void msg()
{ System.out.println("Hello");
}
}

import pack.*;
class B extends A
{
public static void main(String args[])
{
B obj = new B();
obj.msg();
}
}

Output:Hello

14
Java Programming 15

4) public access modifier:


The public access modifier is accessible everywhere.
It has the widest scope among all other modifiers.
Example of public access modifier
//save by A.java
package pack;
public class A
{
public void msg()
{
System.out.println("Hello");
}
}

//save by B.java

package mypack;
import pack.*;
class B
{
public static void main(String args[])
{
A obj = new A();
obj.msg();
}
}

15
Java Programming 16

Output:Hello
ACCESS MODIFIER PUBLIC PROTECTED PRIVATE
Same class YES YES YES
Subclass in same YES YES NO
package
Other classes in same YES YES NO
package
Subclass in other YES YES NO
packages
Non subclasses in YES NO NO
other packages

2.2 INTERFACES

2.2.1 Introduction to Interfaces

Question: How multiple inheritance is achieved in java?

(or)

Explain about interface concept?

(or)

How a Is-A relationship is possible in java

An interface in java is a blueprint of a class. It has static final constants and abstract methods.

o The interface in java is a mechanism to achieve abstraction.


o There can be only abstract methods in the java interface not method body.
o It is used to achieve abstraction and multiple inheritance in Java.
o Java Interface also represents IS-A relationship.
o It cannot be instantiated just like abstract class.

They are mainly three reasons to use interface. They are given below.

 It is used to achieve abstraction.


 By interface, we can support the functionality of multiple inheritance.
 It can be used to achieve loose coupling.
16
Java Programming 17

2.2.2 Defining an Interface

Syntax:
public interface NameOfInterface

// Any number of final, static fields

// Any number of abstract method declarations\

In other words, Interface fields are public, static and final by default, and methods are public and abstract.

2.2.3 Implementation of Interface

Understanding relationship between classes and interfaces

As shown in the figure given below, a class extends another class, an interface extends another interface but a
class implements an interface

17
Java Programming 18

Example on class implementing interface

interface MyInterface
{
public void method();
}
class Demo implements MyInterface
{
public void method()
{
System.out.println("Implementation of method");
}
public static void main(String arg[])
{

Demo obj=new Demo();


obj. method();
}
}

Output: Implementation of method

18
Java Programming 19

Multiple inheritance is not supported through class in java but it is possible by interface, why?

As we have explained in the inheritance chapter, multiple inheritance is not supported in case of class because
of ambiguity. But it is supported in case of interface because there is no ambiguity as implementation is
provided by the implementation class.

For example:
interface Printable
{
void print();
}
interface Showable
{
void show();
}

class TestInterface implements Printable, Showable


{
public void print()
{
System.out.println("Hello");
}
public void show()
{
System.out.println("Welcome");
}
public static void main(String args[])
{
TestInterface obj = new TestInterface ();
obj.print();
obj.show();
}
}

Output:

Hello
19
Java Programming 20

Welcome

Difference between abstract class and interface

 Abstract class and interface both are used to achieve abstraction where we can declare the abstract

methods.

 Abstract class and interface both can't be instantiated.

But there are many differences between abstract class and interface that are given below.

Abstract class Interface


1) Abstract class can have abstract and non- Interface can have only abstract methods. Since Java 8, it can
abstract methods. have default and static methods also.
2) Abstract class doesn't support multiple
Interface supports multiple inheritance.
inheritance.
3) Abstract class can have final, non-final,
Interface has only static and final variables.
static and non-static variables.
4) Abstract class can provide the Interface can't provide the implementation of abstract
implementation of interface. class.
5) The abstract keyword is used to declare
The interface keyword is used to declare interface.
abstract class.
6) Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }

20
Java Programming 21

2.2.4 Nested Interfaces

 An interface which is declared within another interface or class is known as nested interface.
 The nested interfaces are used to group related interfaces so that they can be easy to maintain.
 The nested interface must be referred by the outer interface or class.
 It can't be accessed directly.

Points to remember for nested interfaces

• Nested interface must be public if it is declared inside the interface but it can have any access modifier if
declared within the class.

• Nested interfaces are declared static implicitely.

Syntax of nested interface which is declared within the interface:

interface interface_name
{
...
public interface nested_interface_name
{
...
}
}

21
Java Programming 22

-Example of nested interface which is declared within the interface


interface Outerinterface

void show();

public interface innerinterface

public void message();

class Test implements Outerinterface.innerinterface

void show()

System.out.println(" implementation of outerinterface show method");

public void message()

System.out.println("implementation of nestedinterface message method");

public static void main(String args[])

Test obj=new Test();

obj.show();

obj.message();

}
22
}
Java Programming 23

Output:

implementation of outerinterface show method


implementation of nestedinterface message method
Syntax of nested interface which is declared within the class
class class_name
{
...
interface nested_interface_name
{
...
}
}

Example of nested interface which is declared within the class


class A
{
public interface innerinterface
{
public void message();
}
}
class NestedTest implements A.innerinterface
{
public void message()
{
System.out.println("implementation of nestedinterface message method");
}
public static void main(String args[])
{
NestedTest obj=new NestedITest();
obj.message();
}
}

23
Java Programming 24

Output:

implementation of nestedinterface message method

Example2:

If class have any members and methods ,then to access this members and methods
 First extend the class and implement the interfaces
So that you will have access to members and methods of class also.

class A
{
void show()
{
System.out.println("Hello");
}
public interface innerinterface
{
public void message();
}
}
class NestedTest extends A implements A.innerinterface
{
public void message()
{
System.out.println("implementation of nestedinterface message method");
}
public static void main(String args[])
{
NestedTest obj=new NestedTest();
obj.show();
obj.message();
}
}

Output:

Hello

implementation of nestedinterface message method");

24
Java Programming 25

NOTE:

If we define a class inside the interface, java compiler creates a static nested class. Let's see how can we define
a class within the interface:

interface interface_name
{
class class_name
{
…..
}
}

2.2.5 Applying Interfaces


A sample example on Applying of interface

interface MyInterface
{
public void method();
}
class Demo implements MyInterface
{
public void method()
{
System.out.println("Implementation of method");
}
public static void main(String arg[])
{
Demo obj=new Demo();
obj. method();
}
}

Output: Implementation of method

25
Java Programming 26

2.2.6 Variables in Interface

 An interface can also contain variables just as classes but the variable in interface must be of
 Public,static and final access modifiers.
 If the variable are not specified with access specifier then during compilation process compiler will
provide this access specifier.

Syntax for declaring variables in interface:

interface interface_name
{

public static final datatype variablename=value;

….

Example for declaring a variable in interface:


interface hai
{
public static final min=5;
}
class demo impliments hai
{
public static void main(string args[])
{
demo obj=new demo();
System.out.println (“minimum value is”);
System.out.println (obj.min);
}
}

26
Java Programming 27

2.2.7 Extension of Interface

Example on interface extending interface:

Interface inheritance

A class implements interface but one interface extends another interface .


interface Printable
{
void print();
}
interface Showable extends Printable
{
void show();
}
class TestInterface implements Showable
{
public void print()
{
System.out.println("Hello");
}
public void show()
{
System.out.println("Welcome");
}

public static void main(String args[])


{
TestInterface obj = new TestInterface();
obj.print();
obj.show();
}
}

Output:

Hello

Welcome
27
Java Programming 28

2.3 STREAM BASED INPUT/OUTPUT

 A stream in java is a path along which data flows.


 A stream presents a uniform,easy-to-use ,object oriented interface between the program and the
input/output devices
 It has a source(of data )and destination(for that data).Both the source and destination ma be physical
devices or programs or other streams in the same program.

OutputStream:Java application uses an output stream to write data to a destination, it may be a file,an
array,peripheral device or socket.

InputStream:Java application uses an input stream to read data from a source, it may be a file,an
array,peripheral device or socket.

28
Java Programming 29

2.3.1 Stream Class


 Java’s Stream based input/output is built upon 4 abstract classes
1. InputStream
2. OutputStream
3. Reader
4. Writer

 InputStreams and OutputStreams are designed for Byte Streams.


 Reader and Writer are designed for Character Streams

2.3.2 Byte Streams- InputStream class and OutputStream class

Byte stream classes have been designed to provide functional features for creating and manipulating streams
and files for reading and writing Bytes.

Java provides two Byte streams

1. InputStream class
2. OutputStream class

1.InputStream Class:

 It is an abstract class that defines model of streaming byte input.


 It implements Closeable interface.
 It defines methods for perfoming input functions such as

 Reading Bytes
 Closing streams
 Marking positions in streams
 Skipping ahead in stream
 Finding the number of Bytes in a streams

29
Java Programming 30

Below table gives the methods provided by InputStream class

Method Description
int read() Reads a byte form the input stream.and return -1
when end of the file is encountered

int read(byte buffer[ ]) Reads an array of bytes into buffer and return -
1 when end of the file is encountered

int read(byte buffer[ ],int offset , int numbytes) Reads numbytes bytes into buffer starting from
offset.
return -1 when end of the file is encountered

int available() Returns number of bytes available for reading

int skip(long n) Skips over n bytes form the input stream


void reset( ) Goes back to the begining of the stream
void close( ) Close the input stream

2.OutputStream class:

 It is an abstract class that defines model of streaming byte output.


 It implements Closeable and Flushable interface.
 It defines methods for perfoming output functions such as

 Writing bytes
 Closing streams
 Flushing streams

30
Java Programming 31

Below table gives the methods provided by OutputStream class

Method Description
void write(int b) Write a byte to the output stream
void write(byte buffer[]) Write all bytes in the buffer array to the output
stream
write(byte buffer[ ],int offset , int numbytes) Writes numbtes from buffer starting from
offset
void close() Close the output stram
void flush() Flushes the output stream

2.3.3 Character Streams-Reader and Writer Stream class

 The character stream can be used to read and write Unicode characters.
 There are two kinds of character stream classes,namely

1.Reader
2.Writer

1.Reader Stream class:


 It is an abstract class that defines model of streaming character input.
 It implements Closeable and Readable interfaces

Below table gives the methods provided by Reader class

Method Description
abstract void close() Closes the input source
int read() Reads the character from the invoking input stream .
return -1 when end of the file is encountered
int read(char buffer[ ]) Reads an array of character into buffer and return -1
when end of the file is encountered
int read(char buffer[ ],int offset , int Reads numchar bytes into buffer starting from offset.

31
Java Programming 32

numchar) return -1 when end of the file is encountered


boolean ready() Returns true if the next input request will not wait
.otherwise it returns false
void mark(int numChars) Places a mark at the current point in the input stram that
will remain valid until numchars characters are read
void reset() Resets the input pointer to the previously set mark

2.Writer Stream class:


 It is an abstract class that defines model of streaming character output.
 It implements Closeable,Flushable and Appendable interfaces

Below table gives the methods provided by Writer class

Method Description
abstract void close() Closes the output stream.
abstract void flush() Flushes the output stream
Writer append(char ch) Appends ch to the end of output stream
Writer append(CharSequence chars) Appends the chars to the end of the output stream
Writer append(CharSequence chars,int begin,int end) Appends the subrange of chars specified by begin and
end-1 to the output stream.
void write(int ch) Write a single character to the output stream
void write(char buffer[]) Writes the complete array of characters to the output
stream
void write(String str) Write a string str to the output stream
abstract void write(char buffer[],int offset,int Write the subrange of numchars characters from
numChars) buffer beging of the offset to output stream

32
Java Programming 33

2.3.4 Reading Console Input And Writing Console Output


 Reading data from the console input(keyboard)
 There are many ways to read data from the console input keyboard. For example:
• InputStreamReader
• Console
• Scanner
• DataInputStream etc.

InputStreamReader class:InputStreamReader class can be used to read data from keyboard.It


performs two tasks: 1.connects to input stream of keyboard
2.converts the byte-oriented stream into character-oriented stream
BufferedReader class:BufferedReader class can be used to read data line by line by readLine()
method.
In below example, we are connecting the BufferedReader stream with the InputStreamReader stream
for reading the line by line data from the keyboard.

import java.io.*;
class IODemo
{
public static void main(String args[])throws Exception
{
InputStreamReader r=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(r);
System.out.println("Enter your name");
String name=br.readLine();
System.out.println("Welcome "+name);
}
}

Output:
Enter your name
Abc
Welcome Abc

33
Java Programming 34

Example2:In this example, we are reading and printing the data until the user prints stop.

import java.io.*;
class IODemo2
{
public static void main(String args[])throws Exception
{
InputStreamReader r=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(r);
String name="";
while(name.equals("stop"))
{
System.out.println("Enter data: ");
name=br.readLine();
System.out.println("data is: "+name);
}
br.close();
r.close();
}
}

Output:Enter data: Amit


data is: Amit

34
Java Programming 35

Enter data: 10
data is: 10
Enter data: stop
data is: stop
Reading the data from console(keyboard) using Scanner class
Scanner Class:
The Scanner class breaks the input into tokens using a delimiter which is whitespace bydefault.
It provides many methods to read and parse various primitive values.
Commonly used methods of Scanner class
Method Description
public String next() returns the next token from the scanner
public String nextLine() moves the scanner position to the next line and returns the value as
a string.
public byte nextByte() scans the next token as a byte.
public short nextShort() scans the next token as a short value.
public int nextInt() scans the next token as an int value
public long nextLong() scans the next token as a long value.
public float nextFloat() scans the next token as a float value.
public double nextDouble() scans the next token as a double value

Example of the Scanner class which reads the int, string and double value as an input:

import java.util.Scanner;
class ScannerTest
{
public static void main(String args[])
{

Scanner sc=new Scanner(System.in);


System.out.println("Enter your rollno");
int rollno=sc.nextInt();
System.out.println("Enter your name");
String name=sc.next();
System.out.println("Enter your fee");
double fee=sc.nextDouble();
System.out.println("Rollno:"+rollno+" name:"+name+" fee:"+fee);

}
35
}
Java Programming 36

Output:Enter your rollno


111
Enter your name
Ratan
Enter
450000
Rollno:111 name:Ratan fee:450000

2.3.5 File class

The java.io package include a File class for creating files and directories.

The File class contain several methods for supporting the various operations such as

 Creating a file
 Opening a file
 Closing a file
 Deleting a file
 Getting name of the file
 Renaming a file
 Getting the size of the file
 Checking the existence of a file
 Checking whether the file is writable.
 Checking whether the file is readable

Sntax for creating an object to File class


File fileobject=new File(“file name”);
Example:

File infile=new File(“demo.txt”);


36
Java Programming 37

2.3.6 Reading and Writing files

 To perform read or write operation the file must be opened first.This is done by creating a file stream
and then linking it to the filename
 A file stream can be defined using the classes of Reader/InputStream for reading data and
Writer/OutputStream for writing data.
 The constructor of Stream classes may be used to assign the desired filenames to the file stream
objects.

Commonly Stream class used for Reading and Writing files:

Source Characters Bytes


/Destination Read Write Read Write
File FileReader FileWriter FileInputStream FileOutputStream

Reading/Writing Characters:

 The subclasses of Reader and Writer implements streams that handle characters.
 The two subclasses used are

 FileReader-for reading characters


 FileWriter –for writing characters

37
Java Programming 38

Example to copy contents of file where file name are passed through command prompt (“input.txt” into file
“output.txt”)
//copying characters from one file into another
import java.io.*;
class CopyCharacters
{
public static void main(String args[])
{
//Declare and create input and output file
File inFile=new File(arsg[0]);
File outFile=new File(args[1]);
FileReader ins=null;//creates file stream ins
FileWriter outs=null;//creates file stream outs
try
{
ins=new FileReader(inFile); //opens inFile
outs=new FileWriter(outFile);//opens outFile
//read and write till the end
int ch;
while((ch=ins.read())!=-1)
{
outs.write(ch);
}
}
catch(IOException e)
{
System.out.println(e);
System.exit(-1);
}
finally
{
try
{

ins.close();
outs.close();
}
catch(IOException e)
{
}

}
}
} 38
Java Programming 39

C:\>Javac CopyCharacters.java

C:\>java CopyCharacters input.txt output.txt

Reading/Writing Bytes

 The subclasses of Reader and Writer implements streams that handle bytes.
 The two subclasses used are

 FileInputStream r-for reading bytes


 FileOutputStream r –for writing bytes
 Example to copy contents of file “in.txt” into file “out.txt”

//copying Bytes from one file into another


import java.io.*;
class CopyBytes
{
public static void main(String args[])
{
//Declare and create input and output file
File inFile=new File("in.txt");
File outFile=new File("out.txt");
FileInputStream ins=null;//creates file stream ins
FileOutputStream outs=null;//creates file stream outsbyte byteRead
byte byteRead;
try
{
ins=new FileInputStream (inFile); //opens inFile
outs=new FileOutputStream (outFile);//opens outFile
//read and write bytes till the end
do
{
byteRead=(byte)ins.read();
outs.write(byteRead);
}while(byteRead!=-1);

}
catch(IOException e)
{

System.out.println(e);

finally

{
39
Java Programming 40

try

ins.close();

outs.close();

catch(IOException e)

System.out.println(e);

2.3.7 Random Access Files


 RandamAccessFile class supported by java.io package allows us to create files that can be used for
reading and writing data with randam access.
 This class implements DataInput,and DataOutput and Closeable Interfaces
 It supports positioning request that means we can position the file pointer with in the file.
 It has two constructors

RandamAccessFile(File fileObj,String access)throws FileNotFoundException


RandamAccessFile(String filename,String access)throws FileNotFoundException
In both cases,access determines what type of file access is permited .

Access Purpose
r File opened for reading purpose
rw File opened for read-write purpose
rws File opened for read-write purpose and every change to ythe file’s data or ymetadata will be
immediately written to physical device
rwd File opened for read-write purpose and every change to ythe file’s data will be immediately
written to physical device

The method seek() is used to set the current position of the file pointer

Syntax:

void seek(long newPos)throws IOException

40
Java Programming 41

Here,newPos specifies the new position,in bytes,of the file pointer from the beginning of the file.

//writing and reading with random access


import java.io.*;
class RandomIO
{
public static void main(String args[])
{
RandamAccessFile file=null;
try
{
file=new RandomAccessFile(“rand.dat”, “rw”);
//Writing to the file
file.writeChar(‘x’);
file.writeInt(333);
file.writeDouble(3.1412);
file.seek(0);//go to the beginning
System.out.println(file.readChar());
System.out.println(file.readInt());
System.out.println(file.readDouble());
file.seek(2); //go to the second item
System.out.println(file.readInt());
//go to the end and append false to the file
file.seek(file.length());
file.writeBoolean(false);
file.seek(4);
System.out.println(file.readBoolean());
file.close();
}
catch(IOException e)
{
System.out.println(e);
}

Output:
x
333
3.1412
333
False
41
Java Programming 42

Explanation of the program


1. .Writes three items of data i.e
x
333
3.1412
2. Brings the file pointer to the beginning
3. Reads and display all the 3 iteam i.e
x
333
3.1412
4. Takes the pointer to the second item and then reads and displays the second item i.e
333
5. Places thepointer at the end and then adds a Boolean item to the file
6. Finally,takes pointer to the fourth item and display it.
7. At the end,closes the file

2.3.8 Console Class

 Console class is used to read from and write to the console.


 It implements the Flushable interface
 Console supplies no constructor ,a console object is obtained by calling System.console()
Syntax:
public static Console console ( )

If the console is available,its reference is returned other wise null is returned.

Below table gives the methods provided by Console class

Method Description
public String readLine() used to read a single line of text from the console
public String readLine(String fmt,Object... args) it provides a formatted prompt then reads the
single line of text from the console.
public char[] readPassword() used to read password that is not being displayed on

42
Java Programming 43

the console.
public char[] readPassword(String fmt,Object... args) it provides a formatted prompt then reads the
password that is not being displayed on the console.
void flush() Causes buffered output to be written physically to
the console
Console printf(String fmtString,Object …args) Writes args to the console using the format
specified by fmtstring
Reader reader() Returns a reference to Reader connected to the
console
PrintWriter writer() Returns a reference to the Writer connected to the
console

Example on Reading Console Input And Writing Console Output

import java.io.*;
class ConsoleDemo
{
public static void main(String args[])
{
String str;
Console con;
con=System.Console();
if (con==null)
return;
str=con.readLine(“Enter a string:”);
con.printf(“Here is ur string: %s”,str);
}
}

Output:

Enter a string: Have a nice day

Here is ur string: Have a nice day

43
Java Programming 44

2.3.9 Serialization

Serialization:

 Serialization is the mechanism of saving the state of the object permanently in the form of a file.
 It is a process in which current state of Object will be saved in stream of bytes. As byte stream create is
platform neutral hence once objects created in one system can be deserialized in other platform
Use of Serialization
 serialization will translate the Object state to Byte Streams.
 This Byte stream can be used for different purpose.
• Write to Disk
• Store in Memory
• Sent byte stream to other platform over network
In general we have four types of serializations, they are:
1. Complete serialization: It is one in which all the data members of the class will participate in serialization
process.
2. Selective serialization: It is one in which selective data members of the class (non-transient variables) will
participate in serialization process.
3. Manual serialization:It is one in which the derived class explicitly implements a predefined interface
called java.io.Serializable. The interface Serializable does not contain any abstract methods
and this type of interface is known as marked or tagged interface.
4. Automatic serialization:It is one in which the user defined derived class extends sub class of Serializable
interface.
Note:
o Serialization interface needs to be implemented in order to make object serialized.
o Transient instance variable doesn’t serialized with Object state.
o If Super class implements Serializable then sub class are also Serializable automatically.
o If Super class is not serializable then when sub class is de serialized then super class’s default
constructor will be invoked. Hence all variable will get default value and reference will be null.

44
Java Programming 45

Steps for developing SERIALIZABLE SUB CLASS:


A Serializable sub class is one which implements a predefined interface called java.io.Serializable

1. Choose the appropriate package to keep Serializable sub class.


2. Choose the user defined class whose object participates in Serializable process.
3. Every user defined class must implements a predefined interface called Serializable.
4. Choose the set of data members for Serializable sub class.
5. Develop the set of set methods for each and every data members of the class.
6. Develop the set of get methods for each and every data members of the class.
For example:
package ep; //step-1
import java.io.*;
public class Emp implements Serializable // Emp (step-2) & Serializable (step-3)
{
int empno;
String ename;
float sal;
// above data members (step-4)
public void setEmpno (int empno)
{
this.empno=empno;
}
public void setEname (String ename)
{
this.ename=ename;
}
public void setSal (float sal)
{
this.sal=sal;
} // above set methods (step-5)
public int getEmpno ()
{
return empno;
}
public String getEname ()
{
return ename;
}
public float getSal ()
{
return sal;
} // above get methods (step-6)
45
}
Java Programming 46

Serializable process:
Steps for SERIALIZATION process:
1. Create an object of Serializable sub class.
For example:
ep.Emp eo=new ep.Emp ();
2.Call set of set methods to place user defined values in a Serializable sub class object.
For example:
eo.setEmpno (10);
eo.setEname (“KVR”);
eo.setSal (10000.00f);
3. Choose the file name and open it into write mode or output mode with the help of
java.io.FileOutputStream
For example:
FileOutputStream fos=new FileOutputStream (“employee”);
4. Since an object of FileOutputStream cannot write the entire object at a time to the file.
Hence, it is recommended to use a predefined class called ObjectOutputStream class.
ObjectOutputStream class contains the following constructor which takes an object of
FileOutputStream class.
For example:
ObjectOutputStream oos=new ObjectOutputStream (fos);
5. In order to write the entire object at a time to the file ObjectOutputStream contains the
following method:
For example:
oos.writeObject (eo);
6. Close the files which are opened in write mode.
For example:
oos.close ();
fos.close ();

46
Java Programming 47

Java program which will save the Serializable sub class object into a file.

import ep.Emp;

import java.io.*;

class serp

public static void main (String [] args) throws Exception

Emp eo=new Emp ();

eo.setEmpno (100);

eo.setEname ("KVR");

eo.setSal (10000.00f);

FileOutputStream fos=new FileOutputStream ("employee");

ObjectOutputStream oos=new ObjectOutputStream (fos);

oos.writeObject (eo);

System.out.println ("EMPLOYEE OBJECT SAVED SUCCESSFULLY...");

oos.close ();

fos.close ();

Output:
EMPLOYEE OBJECT SAVED SUCCESSFULLY...

47
Java Programming 48

2.3.10 Enumeration

Enumeration is created using the enum keyword

Syntax for defining Enumeration:

enum enumerationtype{identifier,identifier2,…….}

Example:

enum Season { WINTER, SPRING, SUMMER, FALL }

enum Day{ SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY}

note:

 enum can be defined outside or inside of the class.


 The identifiers are called as enumeration constants or self -typed
 The identifier is implicitly declared as public ,static final members if enumerationtype
 However,even though enumerations define a class type, you do not instantiate an enum using new
keyword.Instead, enumeration variable are declared in same way as you do one of the primitive types.

Syntax for declaring Enumeration variable:

enumerationtype variablename1,variablename2,…..;

Example:

Season s;

Day d;

Note:

enumeration variable can accept only enumeration constant as its value.


48
Java Programming 49

s= Season. WINTER;

d= Day. SUNDAY

Initializing specific value to the enum constants:

The enum constants have initial value that starts from 0, 1, 2, 3 and so on. But we can initialize the specific
value to the enum constants by defining fields and constructors. As specified earlier, Enum can have fields,
constructors and methods.

enum Season{ WINTER(5), SPRING(10), SUMMER(15), FALL(20)};

The values( ) , valueOf( ) and Ordinal ()Methods of Enumeration

All enumerations automatically contain predefined methods: values( ) valueOf( )and ordinal()

Their general forms are shown here:

public static enum-type[ ] values( );

public static enum-type valueOf(String str);

public final int ordinal();

 The values( ) method returns an array that contains a list of the enumeration constants.
 The valueOf( ) method returns the enumeration constant whose value corresponds to the string

passed in str.

 The ordinal() method returns this enumeration constant's ordinal.

49
Java Programming 50

The following program demonstrates the values( ), valueOf( ) and ordinal() methods:

enum Season { WINTER, SPRING, SUMMER, FALL }

class EnumDemo2 {

public static void main(String args[])

Season s;

Season allseasons[] = Season.values(); // use values()

for(Season x : allseasons)

System.out.println(x);

System.out.println();

s = Season.valueOf("SUMMER"); // use valueOf()

System.out.println("s contains " + s);

System.out.println("WINTER ordinal="+Season.WINTER.ordinal());

System.out.println("SPRING ordinal="+Season.SPRING.ordinal());

System.out.println("SUMMER ordinal="+Season.SUMMER.ordinal());

System.out.println(" FALL ordinal="+Season. FALL.ordinal());

50
Java Programming 51

Output:
WINTER
SPRING
SUMMER
FALL
s contains SUMMER
WINTER ordinal=0
SPRING ordinal=1
SUMMER ordinal=2
FALL ordinal=3

2.3.11 Auto boxing


The automatic conversion of primitive data types into its equivalent Wrapper type is known as boxing and
opposite operation is known as unboxing.
This is the new feature of Java5. So java programmer doesn't need to write the conversion code.

Advantage of Autoboxing and Unboxing:


No need of conversion between primitives and Wrappers manually so less coding is required .

Simple Example of Autoboxing in java

class BoxingDemo

public static void main(String args[])

int a=50;
Integer a2=new Integer(a);//Boxing

Integer a3=5;//Boxing

System.out.println(a2+" "+a3);
}

51
Java Programming 52

Output:

50 5

Unboxing:

The automatic conversion of wrapper class type into corresponding primitive type, is known as Unboxing.
Let's see the example of unboxing

class UnboxingDemo
{
public static void main(String args[])
{
Integer i=new Integer(50);
int a=i;
System.out.println(a);
}
}

Output:

50

2.3.12 Generics
Introducution of Generics:
Generics means parameterized types. Parameterized types are important because they enable you to create
classes, interfaces, and methods in which the type of data upon which they operate is specified as a parameter.
Using generics, it is possible to create a single class, for example, that automatically works with different types
of data. A class, interface, or method that operates on a parameterized type is called generic, as in generic class
or generic method.

The General Form of a Generic Class


class class-name<type-param-list>
52 { // ...}
Java Programming 53

Syntax for declaring a generic class:

syntax for declaring a reference to a generic class:

class-name<type-arg-list> var-name =new class-name<type-arg-list>(cons-arg-list);

Note: In Parameter type we can ‘t use primitives like 'int','char' or 'double'.

// A Simple Java program to show working of user defined Generic classes


// We use < > to specify Parameter type
class Test<T>
{

T obj; // An object of type T is declared


Test(T obj) // constructor
{
this.obj = obj;
}
public T getObject()
{
return this.obj;
}
}
// Driver class to test above
class Main
{
public static void main (String[] args)
{
// instance of Integer type
Test <Integer> iObj = new Test<Integer>(15);
System.out.println(iObj.getObject());
// instance of String type
Test <String> sObj = new
Test<String>("JavaProgramming");
System.out.println(sObj.getObject());
}
}
Output:
JavaProgramming

53
Java Programming 54

Generic Functions:

We can also write generic functions that can be called with different types of arguments based on the type of
arguments passed to generic method, the compiler handles each method.

// A Simple Java program to show working of user defined Generic functions

class Test
{
// A Generic method example
static <T> void genericDisplay (T element)
{
System.out.println(element.getClass().getName() + " = " + element);
}

// Driver method
public static void main(String[] args)
{
// Calling generic method with Integer argument
genericDisplay(11);

// Calling generic method with String argument


genericDisplay("JavaProgramming");

// Calling generic method with double argument


genericDisplay(1.0);
}
}

Output :

java.lang.Integer = 11

java.lang.String = JavaProgramming

java.lang.Double = 1.0

Advantages of Generics:
Programs that uses Generics has got many benefits over non-generic code.

Code Reuse: We can write a method/class/interface once and use for any type we want.

Type Safety : Generics make errors to appear compile time than at run time (It’s always better to know problems in your
code at compile time rather than making your code fail at run time). Suppose you want to create an ArrayList that store
name of students and if by mistake programmer adds an integer object instead of string, compiler allows it. But, when we
retrieve this data from Array List, it causes problems at runtime.

54
Java Programming 55

Unit_ II previously asked 2 and 3 marks Questions


1. List the byte stream classes[3 M]
2. Explain about implicit and explicit import statement[3]
3. How to create and access a package? [3]
4. Write about the random access file operations[3]
5. What is a package? How to define it and access it? [3]
6. Differentiate class, abstract class and interface. [2]
7. How to create and use a package in Java program? [3]
8. Define a Package? What is its use in java? Explain. [2]
9. List out the benefits of Stream oriented I/O. [3]
10. What is the benefit of Generics[2]
11. Differentiate between Enumeration and Iterator interface. [3]
12. How to define a package in Java? [2]
13. Contrast between abstract class and interface. [3]
14. What are the methods available in the character streams? [2]
15. What is the significance of the CLASSPATH environment variable in creating/using a
package?[3]
16. What is Console class? What is its use in java? [2]
17. What is the use of auto boxing in java? Explain. [3]

55
Java Programming 56

Unit –II previous asked Essay Questions

1. How to define a package? How to access, import a package? Explain with examples[ 5 marks]
2. What is the need of Generics?[4 marks]
3. Explain the various access specifiers are used in java.[5 m]
4. Write a program to implement the operations of random access file [5 m]
5. Explain the file management using File class.[5m]
6. What is a java package?What is CLASSPATH? Explain how to create and access a java package with
an example. .[5m]
7. Create an interface with at least one method and implement that interface by within a method which
returns a reference to your interface.[5m]
8. Write a program to compute an average of the values in a file.[5m]
9. Explain multilevel inheritance with the help of abstract class in your program. .[5m]
10. Can inheritance be applied between interfaces? Justify your answer. .[5m]
11. Differentiate between interface and abstract class. .[5m]
12. Write a program to copy the contents of file1 to file 2. Read the names of files as command line
arguments.[5m]
13. What support is provided by File class for file management? Illustrate with suitable scenarios. .[5m]
14. What is an interface? What are the similarities between interfaces and classes? .[5m]
15. How can you extend one interface by the other interface? Discuss. .[5m]
16. Discuss about CLASSPATH environment variables. [5m]
17. Discuss the different levels of access protection available in Java. [5m]
18. Demonstrate ordinal( ) method of enum. [5m]
19. What is type wrapper? What is the role of auto boxing? [5m]
20. Explain the process of defining and creating a package with suitable examples. [5m]
21. Give an example where interface can be used to support multiple inheritance. [5m]
22. Describe the process of importing and accessing a package with suitable examples.[5m]
23. How to design and implement an interface in Java? Give an example[5m]
24. Give an example where interface can be used to support multiple inheritance. [5m]
25. What are the methods available in the Character Streams? Discuss. [5m]
26. Distinguish between Byte Stream Classes and Character Stream Classes. [5m]
27. What is the accessibility of a public method or field inside a nonpublic class or interface? Explain.
[5m]

56
Exception Handling
and Multi-threading
Java Programming 2

3.1.1 Fundamentals of Exception Handling

Exception

A Java Exception is an object that describes the exception that occurs in a program. When an exceptional
events occurs in java, an exception is said to be thrown. The code that's responsible for doing something about
the exception is called an exception handler.

Exception Handling

Exception Handling is the mechanism to handle runtime malfunctions. We need to handle such exceptions to
prevent abrupt termination of program. The term exception means exceptional condition, it is a problem that
may arise during the execution of program. A bunch of things can lead to exceptions, including programmer
error, hardware failures, files that need to be opened cannot be found, resource exhaustion etc.

Exception class Hierarchy

All exception types are subclasses of class Throwable, which is at the top of exception class hierarchy.
Java Programming 3

• Exception class is for exceptional conditions that program should catch. This class is extended to create
user specific exception classes.

• RuntimeException is a subclass of Exception. Exceptions under this class are automatically defined for
programs.

3.1.2 Exception Types

 Checked Exception

The exception that can be predicted by the programmer.The classes that extend Throwable class except
RuntimeException and Error are known as checked exceptions

e.g.IOException, SQLException etc. Checked exceptions are checked at compile-time.

 Unchecked Exception

Unchecked exceptions are the class that extends RuntimeException. Unchecked exception are ignored at
compile time.

Example :ArithmeticException, NullPointerException, Array Index out of Bound exception. Unchecked


exceptions are checked at runtime.

 Error

Errors are typically ignored in code because you can rarely do anything about an error.For example if stack
overflow occurs, an error will arise. This type of error is not possible handle in code. Error is irrecoverable

e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.

Common scenarios of Exception Handling where exceptions may occur

There are given some scenarios where unchecked exceptions can occur. They are as follows:

1) Scenario where ArithmeticException occurs

If we divide any number by zero, there occurs an ArithmeticException.

1. int a=50/0;//ArithmeticException

2) Scenario where NullPointerException occurs

If we have null value in any variable, performing any operation by the variable occurs anNullPointerException.
Java Programming 4

1. String s=null;
2. System.out.println(s.length());//NullPointerException

3) Scenario where NumberFormatException occurs

The wrong formatting of any value, may occur NumberFormatException. Suppose I have a string variable that
havecharacters, converting this variable into digit will occur NumberFormatException.

1. String s="abc";
2. int i=Integer.parseInt(s);//NumberFormatException

4) Scenario where ArrayIndexOutOfBoundsException occurs

If you are inserting any value in the wrong index, it would result ArrayIndexOutOfBoundsException as shown
below:

1. int a[]=new int[5];


2. a[10]=50; //ArrayIndexOutOfBoundsException

3.1.3 Termination & Resumptive models

There are two basic models in exception handling theory.

Introduction:

When an exception is thrown ,control is transferred to the catch block that handles the error. The programmer
now has two choices.

Programmer can print the error message and exit from the program. This technique is called as Termination
Model.

The Programmer can also continue execution by calling some other function after printing the error message
This technique is called as Resumptive model

If exception handling is not provided,then in a java application the program terminates automatically after
printing the default exception message.
Java Programming 5

Example for Termination Model

class terminationtest

public static void main(String[] args)


{
int i=50;
int j=0;
int data;
try
{
data=i/j; //may throw exception
}
// handling the exception
catch(Exception e)
{
// resolving the exception in catch block
System.out.println(e);
System.exit(0);
}

}
}

Explaination:

Once the exception is ariased repective catch will be executed.In catch we can do two things

i) we can just display error message and exit from program without executing the code after the catch block by
using System.exit(0) method as show in above example.[Termination Model]

ii)we can call another method which changes the value of b (or) changes the value of b in catch block so that
execution continues after catching the exception.[Resumptive Model]

Resumptive Model

“Resumption means that the exception handler is expected to do something to rectify the situation, and then the
faulting method is retried, presuming success the second time.If you want this, try placing your try-catch in a
while loop that keeps reentering the try block until the result is satisfactory”

Example for Resumptive Model

public class ResumeModel {


Java Programming 6

int change()
{
return 10;
}
public static void main(String[] args) {
int i=50;
int j=0;
int data;
try
{
data=i/j; //may throw exception
}
// handling the exception
catch(Exception e)
{
// resolving the exception in catch block
System.out.println(e);
ResumeModel obj =new ResumeModel();
j=obj.change();
}
data=i/j;
System.out.println("data value is"+data);

}
}
Output:
java.lang.ArithmeticException: / by zero
data value is 5

3.1.4
Uncaught Exceptions

When we don't handle the exceptions, they lead to unexpected program termination. Lets take an example for
better understanding.

class UncaughtException
{
public static void main(String args[])
{
int a = 0;
int b = 7/a; // Divide by zero, will lead to exception
}
}
Java Programming 7

This will lead to an exception at runtime, hence the Java run-time system will construct an exception and then
throw it. As we don't have any mechanism for handling exception in the above program, hence the default
handler will handle the exception and will print the details of the exception on the terminal.

3.1.5 Using try and catch statements

Exception Handling Mechanism

In java, exception handling is done using five keywords,

1. try
2. catch
3. throw
4. throws
5. finally

Exception handling is done by transferring the execution of a program to an appropriate exception handler
when exception occurs.

Using try and catch

Try is used to guard a block of code in which exception may occur. This block of code is called guarded
region. A catch statement involves declaring the type of exception you are trying to catch. If an exception
occurs in guarded code, the catch block that follows the try is checked, if the type of exception that occured is
listed in the catch block then the exception is handed over to the catch block which then handles it.
Java Programming 8

Example using Try and catch

class Excp {

public static void main(String args[])

int a,b,c;

try {

a=0;

b=10;

c=b/a;

System.out.println("This line will not be executed");

catch(ArithmeticException e) {

System.out.println("Divided by zero");

System.out.println("After exception is handled");

Output :

Divided by zero

After exception is handled

An exception will thrown by this program as we are trying to divide a number by zero inside try block. The
program control is transfered outside try block. Thus the line "This line will not be executed" is never parsed
by the compiler. The exception thrown is handle in catch block. Once the exception is handled the program
controls continue with the next line in the program. Thus the line "After exception is handled" is printed.
Java Programming 9

3.1.6 Multiple catch clauses

Multiple catch blocks:

A try block can be followed by multiple catch blocks. You can have any number of catch blocks after a single
try block.If an exception occurs in the guarded code the exception is passed to the first catch block in the list. If
the exception type of exception, matches with the first catch block it gets caught, if not the exception is passed
down to the next catch block. This continue until the exception is caught or falls through all catches.

Example for Multiple Catch blocks

class Excep {

public static void main(String[] args)

try {

int arr[]={1,2};

arr[2]=3/0;

catch(ArithmeticExceptionae)

System.out.println("divide by zero");

catch(ArrayIndexOutOfBoundsException e)

System.out.println("array index out of bound exception");

}
Java Programming 10

Output :

divide by zero

Example for Unreachable Catch block

While using multiple catch statements, it is important to remember that exception sub classes inside catch
must come before any of their super classes otherwise it will lead to compile time error.

class Excep {

public static void main(String[] args)

try

int arr[]={1,2};

arr[2]=3/0;

catch(Exception e) //This block handles all Exception

System.out.println("Generic exception");

catch(ArrayIndexOutOfBoundsException e) //This block is unreachable

System.out.println("array index out of bound exception");

}
Java Programming 11

3.1.7 Nested try statements

try statement can be nested inside another block of try. Nested try block is used when a part of a block may
cause one error while entire block may cause another error. In case if inner try block does not have a catch
handler for a particular exception then the outer try is checked for match.

class Excep {

public static void main(String[] args) {

try

int arr[]={5,0,1,2};

try

int x=arr[3]/arr[1];

catch(ArithmeticExceptionae)

System.out.println("divide by zero");

arr[4]=3;

catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("array index out of bound exception");
}
}
}
Java Programming 12

Important points to Remember

1. If you do not explicitly use the try catch blocks in your program, java will provide a default exception
handler, which will print the exception details on the terminal, whenever exception occurs.
2. Super class Throwable overrides toString() function, to display error message in form of string.
3. While using multiple catch block, always make sure that exception subclasses comes before any of their
super classes. Else you will get compile time error.
4. In nested try catch, the inner try block, uses its own catch block as well as catch block of the outer try, if
required.
5. Only the object of Throwable class or its subclasses can be thrown.

3.1.8 throw, throws and finally Statements

throw Keyword

throw keyword is used to throw an exception explicitly. Only object of Throwable class or its sub classes can
be thrown. Program execution stops on encountering throw statement, and the closest catch statement is
checked for matching type of exception.

Syntax :

throwThrowableInstance

Creating Instance of Throwable class

There are two possible ways to get an instance of class Throwable,

1. Using a parameter in catch block.


2. Creating instance with new operator.

Ex:newNullPointerException("test");

This constructs an instance of NullPointerException with name test.


Java Programming 13

Example demonstrating throw Keyword

class Test {

static void show() {

try {

throw new ArithmeticException("demo");

catch(ArithmeticException e) {

System.out.println("Exception caught");

public static void main(String args[])


{
show();
}
}
In the above example the avg() method throw an instance of ArithmeticException, which is successfully
handled using the catch statement.

throws Keyword

Any method capable of causing exceptions must list all the exceptions possible during its execution, so that
anyone calling that method gets a prior knowledge about which exceptions to handle. A method can do so by
using the throws keyword.

Syntax :

typemethod_name(parameter_list)throwsexception_list

//definition of method

}
Java Programming 14

NOTE : It is necessary for all exceptions, except the exceptions of type Error and RuntimeException, or any
of their subclass.

Example demonstrating throws Keyword

import java.io.*;

public class ThrowExample {

void mymethod(int num)throws IOException, ClassNotFoundException{

if(num==1)

throw new IOException("Exception Message1");

else

throw new ClassNotFoundException("Exception Message2");

class Demo

public static void main(String args[]){

try{

ThrowExample obj=new ThrowExample();

obj.mymethod(1);

catch(Exception ex)

System.out.println(ex);

}
Java Programming 15

Finally:

A finally keyword is used to create a block of code that follows a try block. A finally block of code always
executes whether or not exception has occurred. Using a finally block, lets you run any cleanup type statements
that you want to execute, no matter what happens in the protected code. A finally block appears at the end of
catch block.

Example demonstrating finally Clause

class ExceptionTest {

public static void main(String[] args)

int a[]= new int[2];

System.out.println("out of try");

try {
Java Programming 16

System.out.println("Access invalid element"+ a[3]);

/* the above statement will throw ArrayIndexOutOfBoundException */

catch(ArrayIndexOutOfBoundException ae)

System.out.println(“array exception”);

finally {

System.out.println("finally is always executed.");

Output :

Out of try

Array exception

finally is always executed.

Exception in thread main java. Lang. exception array Index out of bound exception.

3.1.9 finalize() method

finalize()

Description

The java.lang.Object.finalize() is called by the garbage collector on an object when garbage collection
determines that there are no more references to the object. A subclass overrides the finalize method to dispose
of system resources or to perform other cleanup.
Java Programming 17

Declaration

Following is the declaration for java.lang.Object.finalize() method

Protectedvoid finalize()

Finalize method does not have Parameters and return value

Exception

 Throwable -- the Exception raised by this method

Example on finalize method

class FinalizeExample{

public void finalize()

System.out.println("finalize called");

public static void main(String[] args){

FinalizeExample f1=new FinalizeExample();

FinalizeExample f2=new FinalizeExample();

f1=null;

f2=null;

System.gc();

Output:

finalize called
Java Programming 18

3.1.10 Built – in Exceptions

Java defines several exception classes inside the standard package java.lang.

The most general of these exceptions are subclasses of the standard type RuntimeException.

Since java.lang is implicitly imported into all Java programs, most exceptions derived from RuntimeException
are automatically available.

Java defines several other types of exceptions that relate to its various class libraries.

Following is the list of Java Unchecked RuntimeException.

Exception Description

ArithmeticException Arithmetic error, such as divide-by-zero.

ArrayIndexOutOfBoundsException Array index is out-of-bounds.

ArrayStoreException Assignment to an array element of an incompatible type.

ClassCastException Invalid cast.

IllegalArgumentException Illegal argument used to invoke a method.

IllegalMonitorStateException Illegal monitor operation, such as waiting on an


unlocked thread.

IllegalStateException Environment or application is in incorrect state.

IllegalThreadStateException Requested operation not compatible with the current


thread state.
Java Programming 19

IndexOutOfBoundsException Some type of index is out-of-bounds.

NegativeArraySizeException Array created with a negative size.

NullPointerException Invalid use of a null reference.

NumberFormatException Invalid conversion of a string to a numeric format.

SecurityException Attempt to violate security.

StringIndexOutOfBounds Attempt to index outside the bounds of a string.

StringIndexOutOfBounds UnsupportedOperationException
An unsupported operation was encountered.

Following is the list of Java Checked Exceptions Defined in java.lang.

Exception Description

ClassNotFoundException Class not found.

CloneNotSupportedException Attempt to clone an object that does not implement the Cloneable
interface.

IllegalAccessException Access to a class is denied.

InstantiationException Attempt to create an object of an abstract class or interface.

InterruptedException One thread has been interrupted by another thread.

NoSuchFieldException A requested field does not exist.


Java Programming 20

3.1.11 User –Defined Exceptions

User defined Exception subclass

You can also create your own exception sub class simply by extending java Exception class. You can define a
constructor for your Exception sub class (not compulsory) and you can override the toString() function to
display your customized message on catch.

class MyException extends Exception {

private int ex;

MyException(int a) //constructor

ex=a;

public String toString()

return "MyException[" + ex +"] is less than zero";

class UserException {

static void sum(inta,int b) throws MyException

if(a<0) {

throw new MyException(a);

}
Java Programming 21

else {

System.out.println(a+b);

public static void main(String[] args)

try {

sum(-10, 10);

catch(MyException me) {

System.out.println(me);

Points to Remember

1. Extend the Exception class to create your own ecxeption class.


2. You don't have to implement anything inside it, no methods are required.
3. You can have a Constructor if you want.
4. You can override the toString() function, to display customized message.
Java Programming 22

3.2 MultiThreading

Definition of Process

An executing program itself is called a process. In a process-based multitasking, more than two processes can
run simultaneously on the computer. A process can contain multiple threads, where every thread is responding
different request of the user.

Process are also called heavyweight task. Process-based multitasking leads to more overhead. Inter-process
communication is very expensive is also limited. Switching from one process to also expensive. Java does not
control the process based multitasking

Definition of Thread

A thread is a part of a process. A process can contain multiple threads. These multiple threads in a process
share the same address space of the process. Each thread has its own stack and register to operate on.

BASIS FOR
PROCESS THREAD
COMPARISON

Basic An executing program is called a A thread is a small part of a process.


process.

Address Space Every process has its separate address All the threads of a process share the
space. same address space cooperatively as
that of a process.

Multitasking Process-based multitasking allows a Thread-based multitasking allows a


computer to run two or more than two single program to run two or more
programs concurrently. threads concurrently.

Communication Communication between two processes Communication between two threads


is expensive and limited. is less expensive as compared to
process.

Switching Context switching from one process to Context switching from one thread to
another process is expensive. another thread is less expensive as
compared to process.

Components A process has its own address space, A thread has its own register, state,
Java Programming 23

BASIS FOR
PROCESS THREAD
COMPARISON

global variables, signal handlers, open stack, program counter.


files, child processes, accounting
information.

Substitute Process are also called heavyweight task. Thread are also called lightweight task.

Control Process-based multitasking is not under Thread-based multitasking is under the


the control of Java. control of Java.

Example You are working on text editor it refers You are printing a file from text editor
to the execution of a process. while working on it that resembles the
execution of a thread in the process.

Multithreading:

Multithreading is a process of executing multiple threads simultaneously.Thread is basically a lightweight


subprocess, a smallest unit of processing. Multiprocessing and multithreading, both are used to achieve
multitasking. But we use multithreading than mulitprocessing because threads share a common memory area.
They don't allocate separate memory area so save memory, and context-switching between the threads takes
less time than processes.

Multitasking:

Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to utilize the CPU.
The processor time is divided among the tasks that are executed

Example : Windows

Context Switching: The process of loading and unloading the process into the memory.

Time Slicing: The amount of processor time that is given to a particular task for execution.

Multitasking can be achieved by two ways:

 Process-based Multitasking(Multiprocessing)
 Thread-based Multitasking(Multithreading)
Java Programming 24

1)Process-based Multitasking (Multiprocessing)

 Execution of different processes simultaneously


 Each process have its own address in memory i.e. each process allocates separate memory area.
 Process is heavyweight.
 Cost of communication between the process is high.
 Switching from one process to another require some time for saving and loading registers, memory
maps, updating lists etc.

Ex: painting, printing, listening to music

2)Thread-based Multitasking (Multithreading)

 Executing the different parts(dependent or independent) of the same process simltaneously


 Threads share the same address space.
 Thread is lightweight.
 Cost of communication between the thread is low.

Example : games, webapplications

Note:At a time only one thread is executed.

Note:At least one process is required for each thread.

Process Based Multi-tasking Thread Based muti-tasking


A process is essence of program that is executing Thread is a such part of multithreaded program which
which running parallel defines separate path for execution
It allow us to run java compiler and text editor at aIt does not support java compiler and text editor run
same time simultaneously
Process multitasking has more overhead than thread Thread multitasking has less overhead than process
multitasking multitasking
It is unable to gain access over idle time of CPU It allow taking gain access over idle time taken by
CPU
It is not under control of java It is totally under control of java
It is heavyweight process comparing to thread based It is a lightweight process
multitasking
Inter process communication is expensive and limited Inter thread communication is inexpensive and
context switching from one thread to other is easy
It has slower data rate multitasking It has faster data rate multithreading
Java Programming 25

3.2.2 Java Thread model

Thread :

A thread is a part of a process. A process can contain multiple threads. These multiple threads in a process
share the same address space of the process. Each thread has its own stack and register to operate on.

There is context-switching between the threads. There can be multiple processes inside the OS and one process
can have multiple threads.

In Java, the word thread means two different things.

 An instance of Thread class.


 or, A thread of execution.

An instance of Thread class is just an object, like any other object in java. But a thread of execution means an
individual "lightweight" process that has its own call stack. In java each thread has its own call stack.
Java Programming 26

Life cycle of a Thread

1. New : A thread begins its life cycle in the new state. It remains in this state until the start() method is
called on it.
2. Runnable : After invocation of start() method on new thread, the thread becomes runnable.
3. Running : A method is in running thread if the thread scheduler has selected it.
4. Blocking : A thread is waiting for another thread to perform a task(such as sleep , I/O operations, block
suspend, wait ) . In this stage the thread is still alive.
5. Terminated : A thread enter the terminated state when it complete its task.
Java Programming 27

3.2.3 Creating a Threads

We can a thread by instantiating an object of type Thread. This can be accomplish by in two ways

1. By extending Thread class.


2. By implementing ‘Runnable’ interface.

1. Steps for Creation of Thread by extending Thread class:

a)Create a class as subclass to Thread Class

Ex: class ThreadDemo extends Thread

b) Write the functionality of user thread with in run method

Ex:public void run()

Functionality;

c)Create the object of the class that is extending Thread class

Ex:ThreadDemo td=new ThreadDemo()

d) Attach the above created object to the Thread class

Ex:Thread t=new Thread(td);

e)Execute the user thread by invoking start()

t.start( )

package threads;

public class ThreadDemo extends Thread

public void run()


Java Programming 28

for(int i=1;i<=3;i++)

System.out.println("user thread:"+i);

public static void main(String args[])

ThreadDemo td=new ThreadDemo();

Thread t=new Thread(td);

t.start();

Output:

user thread:1

user thread:2

user thread:3

2. Steps for Creation of Thread by implementing ‘Runnable’ interface:

a) Create a class implementing Runnable interface

Ex: class RunnableDemo implements Runnable

b) Write the functionality of user thread with in run method

Ex:public void run() {

Functionality;
Java Programming 29

c) Create the object class that is implementing Runnable interface

Ex:RunnableDemo rd=new RunnableDemo();

d) Attach the above created object to the Thread class

Ex:Thread t=new Thread(rd);

e) Execute the user thread by invoking start()

t.start( )

package threads;

public class RunnableDemo implements Runnable

public void run()

for(int i=1;i<=10;i++)

System.out.println("user thread:"+i);

public static void main(String args[])

RunnableDemo rd=new RunnableDemo();

Thread t=new Thread(rd);

t.start();

}
Java Programming 30

Output:

user thread:1

user thread:2

user thread:3

user thread:4

user thread:5

user thread:6

user thread:7

user thread:8

user thread:9

user thread:10

The main thread :

Even if you don't create any thread in your program, a thread called main thread is still created. Although the
main thread is automatically created, you can control it by obtaining a reference to it by calling
currentThread() method.

Two important things to know about main thread are,

 It is the thread from which other threads will be produced.


 main thread must be always the last thread to finish execution.

classMainThread

public static void main(String[] args)

Thread t=Thread.currentThread();
Java Programming 31

t.setName("MainThread");

System.out.println("Name of thread is "+t);

3.2.4 Thread Priorities

Every thread has a priority that helps the operating system determine the order in which threads are scheduled
for execution. In java thread priority ranges between,

 MIN-PRIORITY (a constant of 1)
 MAX-PRIORITY (a constant of 10)

By default every thread is given a NORM-PRIORITY(5). The mainthread always have NORM-PRIORITY.

Example on Thread Priority

class Multi implements Runnable{

public void run() {

System.out.println("running thread name is:"+Thread.currentThread().getName());

System.out.println("running thread priority is:"+Thread.currentThread().getPriority());

public static void main(String args[]) {

Multi m1=new Multi ();

Multi m2=new Multi ();

m1.setPriority(Thread.MIN_PRIORITY);
Java Programming 32

m2.setPriority(Thread.MAX_PRIORITY);

m1.start();

m2.start();

Output:

running thread name is:Thread-0

running thread priority is:10

running thread name is:Thread-1

running thread priority is:1

3.2.5 Thread Synchronizing

Synchronization is the capability of control the access of multiple threads to any shared resource.
Synchronization is better in case we want only one thread can access the shared resource at a time.

Use of Synchronization

The synchronization is mainly used to

1. To prevent thread interference.


2. To prevent consistency problem.

Types of Synchronization

There are two types of synchronization

1. Process Synchronization
2. Thread Synchronization

Here, we will discuss only thread synchronization.


Java Programming 33

Thread Synchronization

There are two types of thread synchronization mutual exclusive and inter-thread communication.

 Mutual Exclusive

1. Synchronized method.
2. Synchronized block.
3. static synchronization.

 Cooperation (Inter-thread communication)

Mutual Exclusive

Mutual Exclusive helps keep threads from interfering with one another while sharing data. This can be done by
three ways in java by using:

1. synchronized method
2. synchronized block
3. static synchronization

Understanding the concept of Lock

Synchronization is built around an internal entity known as the lock or monitor.Every object has an lock
associated with it. By convention, a thread that needs consistent access to an object's fields has to acquire the
object's lock before accessing them, and then release the lock when it's done with them.
From Java 5 the package java.util.concurrent.locks contains several lock implementations.

Understanding the problem without Synchronization

class First

public void display(String msg)

System.out.print("["+msg);

try

Thread.sleep(2000);
Java Programming 34

catch(InterruptedException e)

System.out.println("error is"+e);

System.out.print("]");

class Second extends Thread

String msg;

First fobj;

Second(First fp,String str)

fobj=fp;

msg=str;

start();

public void run()

fobj.display(msg);

}
Java Programming 35

public class UnSynchroMethod

public static void main(String args[])

First fnew=new First();

Second s1=new Second(fnew,"welcome");

Second s2=new Second(fnew,"new");

Second s3=new Second(fnew,"program");

Output:

[welcome[program[new]]]

1.Thread synchronization using synchronized method

 If you declare any method as synchronized, it is known as synchronized method.


 Synchronized method is used to lock an object for any shared resource.

When a thread invokes a synchronized method, it automatically acquires the lock for that object and releases it
when the method returns

class First

synchronized public void display(String msg)

System.out.print("["+msg);

try {

Thread.sleep(2000);
Java Programming 36

catch(InterruptedException e)

System.out.println("error is"+e);

System.out.print("]");

class Second extends Thread

String msg;

First fobj;

Second(First fp,String str)

fobj=fp;

msg=str;

start();

public void run()

fobj.display(msg);

}
Java Programming 37

public class SynchroBlock

public static void main(String args[])

First fnew=new First();

Second s1= new Second(fnew,"welcome");

Second s2= new Second(fnew,"new");

Second s3= new Second(fnew,"program");

Output:

[welcome][new][program]

2.Thread synchronization using Synchronized block

Synchronized block can be used to perform synchronization on any specific resource of the method.

Suppose you have 50 lines of code in your method, but you want to synchronize only 5 lines, you can use
synchronized block.

If you put all the codes of the method in the synchronized block, it will work same as the synchronized
method.

Points to remember for Synchronized block

 Synchronized block is used to lock an object for any shared resource.


 Scope of synchronized block is smaller than the method.

Syntax to use synchronized block

synchronized (object reference expression) {

//code block

}
Java Programming 38

Example on Thread synchronization using synchronized block

class First

public void display(String msg)

System.out.print("["+msg);

try

Thread.sleep(2000);

catch(InterruptedException e)

System.out.println("error is"+e);

System.out.print("]");

class Second extends Thread

String msg;

First fobj;

Second(First fp,String str)

{
Java Programming 39

fobj=fp;

msg=str;

start();

public void run()

synchronized(fobj)

fobj.display(msg);

public class SynchroBlock

public static void main(String args[])

First fnew=new First();

Second s1=new Second(fnew,"welcome");

Second s2=new Second(fnew,"new");

Second s3=new Second(fnew,"program");

Output:
Java Programming 40

[welcome][new][program]

3.Thread synchronization using Static synchronization

If you make any static method as synchronized, the lock will be on the class not on object.

Problem without static synchronization

Suppose there are two objects of a shared class(e.g. Table) named object1 and object2.In case of synchronized
method and synchronized block there cannot be interference between t1 and t2 or t3 and t4 because t1 and t2
both refers to a common object that have a single lock.But there can be interference between t1 and t3 or t2 and
t4 because t1 acquires another lock and t3 acquires another lock.I want no interference between t1 and t3 or t2
and t4.Static synchronization solves this problem.

Example of static synchronization

In this example we are applying synchronized keyword on the static method to perform static synchronization.

class Table{

synchronized static void printTable(int n){

for(int i=1;i<=10;i++){

System.out.println(n*i);

try{
Java Programming 41

Thread.sleep(400);

}catch(Exception e){}

class MyThread1 extends Thread{

public void run(){

Table.printTable(1);

class MyThread2 extends Thread{

public void run(){

Table.printTable(10);

class MyThread3 extends Thread{

public void run(){

Table.printTable(100);

class MyThread4 extends Thread{

public void run(){


Java Programming 42

Table.printTable(1000);

class Use{

public static void main(String t[]){

MyThread1 t1=new MyThread1();

MyThread2 t2=new MyThread2();

MyThread3 t3=new MyThread3();

MyThread4 t4=new MyThread4();

t1.start();

t2.start();

t3.start();

t4.start();

3.2.6 Inter Thread Communication

Inter-thread communication or Co-operation is all about allowing synchronized threads to communicate


with each other.

Cooperation (Inter-thread communication) is a mechanism in which a thread is paused running in its critical
section and another thread is allowed to enter (or lock) in the same critical section to be executed.It is
implemented by following methods of Object class:

 wait()
 notify()
 notifyAll()

1) wait() method
Java Programming 43

Causes current thread to release the lock and wait until either another thread invokes the notify() method or the
notifyAll() method for this object, or a specified amount of time has elapsed.

The current thread must own this object's monitor, so it must be called from the synchronized method only
otherwise it will throw exception.

Method Description
public final void wait()throws InterruptedException waits until object is notified.
public final void wait(long timeout)throws
waits for the specified amount of time.
InterruptedException

2) notify() method

Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this object, one
of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation.
Syntax:

public final void notify()

3) notifyAll() method

Wakes up all threads that are waiting on this object's monitor. Syntax:

public final void notifyAll()

Why wait(), notify() and notifyAll() methods are defined in Object class not Thread class?

It is because they are related to lock and object has a lock.

Difference between wait and sleep?

Let's see the important differences between wait and sleep methods. package interthreadcommunication;

wait() sleep()

wait() method releases the lock sleep() method doesn't release the lock.

is the method of Object class is the method of Thread class

is the non-static method is the static method

should be notified by notify() or notifyAll() after the specified amount of time, sleep is
methods completed.
Java Programming 44

Example1: Inter Thead Communication on Banking application

class Customer {

int amount=10000;

synchronized void withdraw(int amount) {

System.out.println("going to withdraw");

if(this.amount<amount) {

System.out.println("insuffient funds,waiting for deposit");

try {

wait();

catch(Exception e)

System.out.println("error"+e);

this.amount=this.amount-amount;

System.out.println("withdraw is completed");

System.out.println("remaining balance amount:"+this.amount);

synchronized void deposit(int amount) {

System.out.println("going to deposit amount");

this.amount=this.amount+amount;

System.out.println("deposite completed");
Java Programming 45

System.out.println("balance after deposit:"+this.amount);

notify();

public class interthread {

public static void main(String args[])

final Customer c=new Customer();

new Thread() {

public void run() {

c.withdraw(15000);

}.start();

new Thread() {

public void run() {

c.deposit(10000);

}.start();

Output :

going to withdraw

insuffient funds,waiting for deposit


Java Programming 46

going to deposit amount

deposite completed

balance after deposit:20000

withdraw is completed

remaining balance amount:5000

Example:2 Producer-Consumer Problem Using Inter-thread Communication

Aim: Write a Java program that correctly implements the producer – consumer problem using the
concept of inter thread communication.

THEORY: Inter-thread communication or Co-operation is all about allowing synchronized threads to


communicate with each other.

Program:

class Q
{
int n;
boolean valueSet=false;
synchronized int get()
{
if(!valueSet) try
{
wait();
}
catch(InterruptedException e)
{
System.out.println("Interrupted Exception caught");
}
System.out.println("Got:"+n); valueSet=false;
notify();
return n;
}
synchronized void put(int n)
{
if(valueSet) try
{
wait();
}
catch(InterruptedException e)
{
System.out.println("Interrupted Exception caught");
Java Programming 47

}
this.n=n; valueSet=true;
System.out.println("Put:"+n); notify();
}
}
class Producer implements Runnable
{
Q q; Producer(Q q)
{
this.q=q;
new Thread(this,"Producer").start();
}
public void run()
{
int i=0;
while(true)
{
q.put(i++);
}
}
}
class Consumer implements Runnable
{
Q q; Consumer(Q q)
{
this.q=q;
new Thread(this,"Consumer").start();
}
public void run()
{
while(true)
{
q.get();
}
}
}
class ProdCons
{
public static void main(String[] args)
{
Q q=new Q();
new Producer(q);

new Consumer(q);
System.out.println("Press Control-c to stop");
}
}
Output:
Java Programming 48
Java Programming 49

Multithreaded Program

Aim: Write a Java program that implements a multithreaded program has three threads. First thread
generates a random integer every 1 second and if the value is even, second thread computes the square
of the number and prints. If the value is odd the third thread will print the value of cube of the number.

Program:
import java.io.*;

import java.util.*;

class First1 extends Thread

public void run()

for(;;)

int roll;

Random d = new Random();

roll = d.nextInt(200) + 1;

System.out.println(roll);

Thread t2=new Second2(roll);

Thread t3=new Third3(roll);

try

Thread.sleep(1000);

if(roll%2==0)

t2.start();

else

t3.start();

catch(InterruptedException e){}

}
Java Programming 50

class Second2 extends Thread

int r1;

Second2(int r)

r1=r;

public void run()

System.out.println("The square of
number"+r1+"is:"+r1*r1);

class Third3 extends Thread

int r1;

Third3(int r)

r1=r;

public void run()

System.out.println("The Cube of the Number"+r1+"is: "+r1*r1*r1);

class Mthread

{
Java Programming 51

public static void main(String[] args)

Thread t1=new First1();

System.out.println("press Ctrl+c to stop......");

t1.start();

}
Java Programming 52

UNIT-III JNTUH- Previously Asked Short Answer question

1. What is the difference between array and vector?[2M]


2. What are the advantages of multithreading? [2]
3. Explain the types of exceptions. [3]
4. **Difference between process and thread
5. Explain how multiple catch statement works
6. List the thread states.
7. What keywords are essential in handling user-defined exception?
8. Differentiate between error and exception. [2]
9. How to assign priorities to threads? [3]
10. How does Java support inter thread communication? [2]
11. List any four unchecked exception. [3]
12. How do we start and stop a thread? [2]
13. Write the complete life cycle of a thread. [3]
14. Define exception. [2]
15. What is the difference between error and an exception? [2]
16. What is synchronization and why is it important? [3]
17. What is thread based preemptive multitasking? [2]
18. How do we set priorities for threads? [3]
Java Programming 53

UNIT-III JNTUH- Previously Asked Essay Answer question

1.a)With a suitable Java program explain user-defined exception handling.


b)What is meant by re-throwing exception? Discuss a suitable scenario for this. [5+5]

2.Does Java support thread priorities? Justify your answer with suitable discussion.
b)**Describe producer-consumer pattern using inter-thread communication. [5+5]

3.a)Write a program that demonstrate the priority setting in threads.


b)Write a program that includes a try block and a catch clause which processes the arithmetic exception
generated by division-by-zero error. [5+5]

4.a)Write a program that creates a thread that forces preemptive scheduling for lower- priority threads.
b)Explain the checked and unchecked exception With an example [5+5]

5 a) Write a program for user defined exception that check the internal and external marks are greater
than 40 it raise the exception “internal marks are exceed” and if external marks greater than 60
exception in raised the exception “external marks Exceed”

6a) Explain about Synchronization method with an example.


b)Explain about built in Exceptions

7.What is an exception? How are exceptions handled in Java programming? Explain with suitable
program. [10]

8.Describe the need of thread synchronization. How is it achieved in Java programming? Explain with a
suitable program[10]

9a)Write a program to illustrate the use of multiple catch blocks for a try block.
b)What are the uses of ‘throw’ and ‘throws’ clauses for exception handling? [5+5]

10.a) What is the difference between a thread and a process?


b)How to achieve synchronization among threads? Write suitable code. [5+5]

11.a)With a program illustrate user defined exception handling


b)How to handle multiple catch blocks for a nested try block? Explain with an example. [5+5]

12.a)Describe how to create a thread with an example.


b)Write a program to explain thread priorities usage. [5+5]

13a)What are advantages of using Exception handling mechanism in a program?


b)Write a java program that demonstrates how certain exception types are not allowed to be thrown.
[5+5]

14a)What are the different ways that are possible to create multiple threaded programs in java? Discuss
the differences between them.
b)Write a program to create four threads using Runnable interface.
Java Programming 54

15Write a program to create three threads in your program and context switch among the threads using
sleep functions. [10]

16a)Write a program with nested try statements for handling exception.


b)How to create a user defined exception? [5+5]

17a)Differentiate between Checked and UnChecked Exceptions with examples.


b)Write a program to create four threads using Runnable interface. [5+5]

18a)What are the different ways to handle exceptions? Explain.


b)How many ways are possible in java to create multiple threaded programs? Discuss the differences
between them. [5+5]

19a)What is an Exception? How is an Exception handled in JAVA?


b)Write a java program that illustrates the application of multiple catch statements. [5+5]

20a)Differentiate between multiprocessing and multithreading.What is to be done to implement these


in a program?
b)Write a program that creates two threads. Fist thread prints the numbers
from 1 to 100 and the other thread prints the numbers from 100 to 1. [5+5]
The Collections
Framework
Java Programming 2

4.1.1 Collections Introduction


Collections in Java

1. Java Collection Framework


2. Hierarchy of Collection Framework
3. Collection interface
4. Iterator interface

Collections in java is a framework that provides an architecture to store and manipulate the group of objects.

All the operations that you perform on a data such as searching, sorting, insertion, manipulation, deletion etc.
can be performed by Java Collections.

Java Collection simply means a single unit of objects. Java Collection framework provides many interfaces
(Set, List, Queue, Deque etc.) and classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet,
LinkedHashSet, TreeSet etc).

Collection :

Collection represents a single unit of objects i.e. a group.

Framework :

o provides readymade architecture.


o represents set of classes and interface.
o is optional.

Collection Framework :

Collection framework represents a unified architecture for storing and manipulating group of objects. It has:

1. Interfaces and its implementations i.e. classes


2. Algorithm

Hierarchy of Collection Framework :

Let us see the hierarchy of collection framework.The java.util package contains all the classes and interfaces
for Collection framework.
Java Programming 3
Java Programming 4

4.1.2 Collection Interface


Methods of Collection interface

There are many methods declared in the Collection interface. They are as follows:

No. Method Description

1 public boolean add(Object element) is used to insert an element in this collection.

is used to insert the specified collection elements in the


2 public boolean addAll(Collection c)
invoking collection.

3 public boolean remove(Object element) is used to delete an element from this collection.

is used to delete all the elements of specified collection


4 public boolean removeAll(Collection c)
from the invoking collection.

is used to delete all the elements of invoking collection


5 public boolean retainAll(Collection c)
except the specified collection.

6 public int size() return the total number of elements in the collection.

7 public void clear() removes the total no of element from the collection.

8 public boolean contains(Object element) is used to search an element.

is used to search the specified collection in this


9 public boolean containsAll(Collection c)
collection.

10 public Iterator iterator() returns an iterator.

11 public Object[] toArray() converts collection into array.

12 public boolean isEmpty() checks if collection is empty.


Java Programming 5

13 public boolean equals(Object element) matches two collection.

14 public int hashCode() returns the hashcode number for collection.

Iterator interface

Iterator interface provides the facility of iterating the elements in forward direction only.

Methods of Iterator interface

There are only three methods in the Iterator interface. They are:

1. public boolean hasNext() it returns true if iterator has more elements.

2. public object next() it returns the element and moves the cursor pointer to the next element.

3. public void remove() it removes the last elements returned by the iterator. It is rarely used.

4. The Collection classes- Array List

Java ArrayList class


Java Programming 6

Java ArrayList class uses a dynamic array for storing the elements. It inherits AbstractList class and
implements List interface.

The important points about Java ArrayList class are:

o Java ArrayList class can contain duplicate elements.


o Java ArrayList class maintains insertion order.
o Java ArrayList class is non synchronized.
o Java ArrayList allows random access because array works at the index basis.
o In Java ArrayList class, manipulation is slow because a lot of shifting needs to be occurred if any
element is removed from the array list.

Hierarchy of ArrayList class

As shown in above diagram, Java ArrayList class extends AbstractList class which implements List interface.
The List interface extends Collection and Iterable interfaces in hierarchical order.

ArrayList class declaration

Let us see the declaration for java.util.ArrayList class.

1. public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable,


Serializable

Constructors of Java ArrayList

Constructor Description

ArrayList() It is used to build an empty array list.

ArrayList(Collection c) It is used to build an array list that is initialized with the elements of
the collection c.

ArrayList(int capacity) It is used to build an array list that has the specified initial capacity.
Java Programming 7

Methods of Java ArrayList

Method Description

void add(int index, Object It is used to insert the specified element at the specified position
element) index in a list.

boolean addAll(Collection c) It is used to append all of the elements in the specified collection
to the end of this list, in the order that they are returned by the
specified collection's iterator.

void clear() It is used to remove all of the elements from this list.

int lastIndexOf(Object o) It is used to return the index in this list of the last occurrence of
the specified element, or -1 if the list does not contain this
element.

Object[] toArray() It is used to return an array containing all of the elements in this
list in the correct order.

Object[] toArray(Object[] a) It is used to return an array containing all of the elements in this
list in the correct order.

boolean add(Object o) It is used to append the specified element to the end of a list.

boolean addAll(int index, It is used to insert all of the elements in the specified collection
Collection c) into this list, starting at the specified position.

Object clone() It is used to return a shallow copy of an ArrayList.

int indexOf(Object o) It is used to return the index in this list of the first occurrence of
the specified element, or -1 if the List does not contain this
element.

void trimToSize() It is used to trim the capacity of this ArrayList instance to be the
list's current size.

Two ways to iterate the elements of collection in java

There are two ways to traverse collection elements:

1. By Iterator interface.

2. By for-each loop.
Java Programming 8

Example1: program on creating , displaying the elements of ArrayList.

import java.util.*;

class TestCollection1{

public static void main(String args[]){

ArrayList<String> list1=new ArrayList<String>();//Creating arraylist

list1.add("Ravi");//Adding object in arraylist

list1.add("Vijay");

list1.add("Giri");

list1.add("Ajay");

System.out.println(“arraylist elements using Iterator interface”);

//Traversing list through Iterator

Iterator itr=list1.iterator();

while(itr.hasNext()){

System.out.println(itr.next());

System.out.println(“arraylist elements using for-each loop”);

//Traversing list through for-each loop

for(String obj:list1)

System.out.println(obj);

ArrayList<String> list2=new ArrayList<String>();

list2.add("Sonoo");//Adding object in arraylist list2

list2.add("Vijay");

System.out.println(“elements in list2”);
Java Programming 9

for(String obj:list2)

System.out.println(obj);

list1.addAll(list2);//adding second list in first list

System.out.println(“elements of list1 after adding list2 elements”);

Iterator itr=list1.iterator();

while(itr.hasNext()){

System.out.println(itr.next());

list1.removeAll(list2);

System.out.println("iterating the elements after removing the elements of list2...");

Iterator itr=list1.iterator();

while(itr.hasNext()){

System.out.println(itr.next());

Output :

arraylist elements using Iterator interface

Ravi

Vijay

Giri
Java Programming 10

Ajay

arraylist elements using for-each loop

Ravi

Vijay

Giri

Ajay

elements in list2

Sonoo

Vijay

elements of list1 after adding list2 elements

Ravi

Vijay

Giri

Ajay

Sonoo

Vijay

iterating the elements after removing the elements of list2

Ravi

Vijay

Giri

Ajay
Java Programming 11

Example2: program to store class objects in ArrayList

class Student{

int rollno;

String name;

int age;

Student(int rollno,String name,int age){

this.rollno=rollno;

this.name=name;

this.age=age;

import java.util.*;

public class TestCollection3{

public static void main(String args[]){

//Creating user-defined class objects

Student s1=new Student(101,"Sonoo",23);

Student s2=new Student(102,"Ravi",21);

Student s2=new Student(103,"Hanumat",25);

//creating arraylist

ArrayList<Student> al=new ArrayList<Student>();

al.add(s1);//adding Student class object

al.add(s2);
Java Programming 12

al.add(s3);

//Getting Iterator

Iterator itr=al.iterator();

//traversing elements of ArrayList object

while(itr.hasNext()){

Student st=(Student)itr.next();

System.out.println(st.rollno+" "+st.name+" "+st.age);

Output :

101 Sonoo 23

102 Ravi 21

103 Hanumat 25
Java Programming 13

Linked List
Java LinkedList class

Java LinkedList class uses doubly linked list to store the elements. It provides a linked-list data structure. It
inherits the AbstractList class and implements List and Deque interfaces.

The important points about Java LinkedList are:

o Java LinkedList class can contain duplicate elements.

o Java LinkedList class maintains insertion order.

o Java LinkedList class is non synchronized.

o In Java LinkedList class, manipulation is fast because no shifting needs to be occurred.

o Java LinkedList class can be used as list, stack or queue.

Hierarchy of LinkedList class

As shown in above diagram, Java LinkedList class extends AbstractSequentialList class and implements List
and Deque interfaces.
Java Programming 14

Doubly Linked List

In case of doubly linked list, we can add or remove elements from both side.

LinkedList class declaration

Let's see the declaration for java.util.LinkedList class.

public class LinkedList<E> extends AbstractSequentialList<E> implements List<E>, Deque<E>, Cloneable,


Serializable

Constructors of Java LinkedList

Constructor Description

LinkedList() It is used to construct an empty list.

LinkedList(Collection c) It is used to construct a list containing the elements of the specified


collection, in the order they are returned by the collection's iterator.

Methods of Java LinkedList

Method Description

void add(int index, Object It is used to insert the specified element at the specified position index in
element) a list.

void addFirst(Object o) It is used to insert the given element at the beginning of a list.

void addLast(Object o) It is used to append the given element to the end of a list.

int size() It is used to return the number of elements in a list

boolean add(Object o) It is used to append the specified element to the end of a list.
Java Programming 15

boolean contains(Object o) It is used to return true if the list contains a specified element.

boolean remove(Object o) It is used to remove the first occurence of the specified element in a list.

Object getFirst() It is used to return the first element in a list.

Object getLast() It is used to return the last element in a list.

int indexOf(Object o) It is used to return the index in a list of the first occurrence of the
specified element, or -1 if the list does not contain any element.

int lastIndexOf(Object o) It is used to return the index in a list of the last occurrence of the
specified element, or -1 if the list does not contain any element.

Java LinkedList Example

import java.util.*;

public class TestCollection7{

public static void main(String args[]){

LinkedList<String> al=new LinkedList<String>();

al.add("Ravi");

al.add("Vijay");

al.add("Ravi");

al.add("Ajay");

Iterator<String> itr=al.iterator();

while(itr.hasNext()){

System.out.println(itr.next());

Output:
Java Programming 16

Ravi

Vijay

Ravi

Ajay

Difference between ArrayList and LinkedList

ArrayList and LinkedList both implements List interface and maintains insertion order. Both are non
synchronized classes.

ArrayList LinkedList

1) ArrayList internally uses dynamic array to store LinkedList internally uses doubly linked list to
the elements. store the elements.

2) Manipulation with ArrayList is slow because it Manipulation with LinkedList is faster than
internally uses array. If any element is removed ArrayList because it uses doubly linked list so no
from the array, all the bits are shifted in memory. bit shifting is required in memory.

3) ArrayList class can act as a list only because it LinkedList class can act as a list and queue both
implements List only. because it implements List and Deque interfaces.

4) ArrayList is better for storing and LinkedList is better for manipulating data.
accessing data.

Question:Make a comparison of List, array and ArrayList.[3 marks]


Ans:
Array: Simple fixed sized arrays that we create in Java, like below
int arr[] = new int[10]
ArrayList : Dynamic sized arrays in Java that implement List interface.
ArrayList<Type> arrL = new ArrayList<Type>();
Here Type is the type of elements in ArrayList to be created

Differences between List ,Array and ArrayList

Array
 An array is basic functionality provided by Java and it fixed length.
 Array provide both direct and sequential access to elements
 Array is a static memory allocation so there is a wastage of memory
 Array can sote only objects
 Array is a static memory allocation so there is a wastage of memory
Java Programming 17

 Insertion and deletion is a time consummation process in array


List and ArrayList
 List and ArrayList is part of collection framework in Java and have variable length.
 ArrayList has a set of methods to access elements and modify them.
 List provide only sequential access to elements
 List dynamic allocation so no wastage of memory
 Arraylist can store primitive datatype and Object.
 Insertion and deletion is not time consummation process in arraylist and list
// A Java program to demonstrate differences between array and ArrayList
import java.util.ArrayList;
import java.util.Arrays;

class Test
{
public static void main(String args[])
{
/* ........... Normal Array............. */
int[] arr = new int[2];
arr[0] = 1;
arr[1] = 2;
System.out.println(arr[0]);

/*............ArrayList..............*/
// Create an arrayList with initial capacity 2
ArrayList<Integer> arrL = new ArrayList<Integer>(2);

// Add elements to ArrayList


arrL.add(1);
arrL.add(2);

// Access elements of ArrayList


System.out.println(arrL.get(0));
}
}

Hash Set

Collections that use a hash table for storage are usually created by the Java HashSet class. As the name
suggests, HashSet implements the Set interface and it also uses a hash table which is a HashMap instance. The
order of the elements in HashSet is random. The null element is permitted by this class. In terms of complexity,
HashSet offers constant time performance for the basic operations like add, remove, contains and size
assuming the elements are properly dispersed by the function.
Java Programming 18

Important to know about HashSet

 HashSet stores the elements by using a mechanism called hashing.


 Duplicate elements cannot exist in a HashSet.
 Null value is permitted by HashSet.
 HashSet class is non synchronized.
 HashSet’s order is not maintained by the insertion order. The elements (in this class) are inserted on the
basis of their hashcode.
 In terms of search operations, HashSet is the best approach due to its constant time complexity.

Constructors in HashSet

1. HashSet hashSet = new HashSet();


2. HashSet hashSet = new HashSet(int initialCapacity);
3. HashSet hashSet = new HashSet(int initialCapacity, float loadFactor);
4. HashSet hashSet = new HashSet(Collection C);

The main difference between these constructors is that in #1 constructor, initial capacity is 16 and the default
load factor is 0.75 but in #2 you can actually set the capacity. The load factor’s default value is still 0.75. In
constructor #3 you can set both the capacity and the load factor.

Methods in HashSet class

1. boolean add(Object o): Used to add the element provided as a parameter and if not present, return false.
Syntax: HashSet.add(Object o);

2. void clear(): Used to remove all elements.


Syntax: HashSet.clear();

3. boolean contains(Object o): Returns true if the specified Object is in the HashSet and false if otherwise.
Syntax: HashSet.contains(Object o)

4. boolean remove(Object o): Used to remove the specified Object from the HashSet (if present).
Syntax: HashSet.remove(Object o)

5. Iterator iterator(): Used to return an iterator over the element in the set.
Syntax: Iterator iterator = HashSet.iterator();

6. boolean isEmpty(): Used to check whether the HashSet is empty or not. Returns true if it is empty and
false if otherwise.
Syntax: HashSet.isEmpty();

7. int size(): Returns the size of the set.


8. Object clone(): Creates a copy of the set.
Java Programming 19

There are two ways to iterate through HashSet:

 Using iterator
 Without using iterator

Example: program to demonstrate HashSet

import java.io.*;

import java.util.*;

public class HashSetExample {

public static void main(String args[]) {

// Creating an empty HashSet

HashSet<String> animals = new HashSet<String>();

animals.add("Elephant");

animals.add("Tiger");

animals.add("Lion");

// Displaying the HashSet

System.out.println("HashSet: " + animals);

// Get the size of the hash set

System.out.println("The size of the hash set is: " + animals.size());

// Creating an iterator

Iterator iterator = animals.iterator();

// Displaying the values after iterating through the set

System.out.println("The iterator values are: ");


Java Programming 20

while (iterator.hasNext()) {

System.out.println(iterator.next());

System.out.println("The HashSet values using for-each: ");

for (String animal : animals) {

System.out.println(animal);

// Checking for "Tiger" in the hash set

System.out.println("Does the HashSet contain 'Tiger'? " + animals.contains("Tiger"));

// Checking for "Chicken" in the hash set

System.out.println("Does the HashSet contain 'Chicken'? " + animals.contains("Chicken"));

// Creating a new set

HashSet clonedSet = new HashSet();

// Cloning the set using clone() method

clonedSet = (HashSet)animals.clone();

// Displaying the new hashset;

System.out.println("The new closnedset is : " + clonedSet);

animals.remove("Elephant");
animals.remove("Lion");

// Displaying the HashSet after removal


System.out.println("HashSet after removing elements: " + animals);

// Check for the empty set

System.out.println("Is the hash set empty: " + animals.isEmpty());


Java Programming 21

animals.clear();

// Checking after we've cleared it out

System.out.println("Is the hash set empty: " + animals.isEmpty());

Output:

HashSet: [Elephant, Tiger, Lion]

The size of the hash set is:3

The iterator values are:

Elephant

Tiger

Lion

The HashSet values using for-each:

Elephant

Tiger

Lion

Does the Set contain 'Tiger'? true

Does the Set contain 'Chicken'? false

The new closnedset is : [Elephant, Tiger, Lion]

HashSet after removing elements: [Tiger]

Is the hash set empty: false

Is the hash set empty: true


Java Programming 22

Tree Set
TreeSet is similar to HashSet except that it sorts the elements in the ascending order while HashSet doesn’t
maintain any order. TreeSet allows null element but like HashSet it doesn’t allow. Like most of the other
collection classes this class is also not synchronized, however it can be synchronized explicitly like this:

SortedSet s = Collections.synchronizedSortedSet(new TreeSet(...));

In this tutorial we are going to see TreeSet example and the difference between TreeSet and other similar
collection classes.

TreeSet Example:

In this example we have two TreeSet (TreeSet<String> & TreeSet<Integer>). We have added the values to both
of them randomly however the result we got is sorted in ascending order.

import java.util.TreeSet;

public class TreeSetExample {

public static void main(String args[]) {

// TreeSet of String Type

TreeSet<String> tset = new TreeSet<String>();

// Adding elements to TreeSet<String>

tset.add("ABC");

tset.add("String");

tset.add("Test");

tset.add("Pen");

tset.add("Ink");

tset.add("Jack");

//Displaying TreeSet

System.out.println(tset);

// TreeSet of Integer Type

TreeSet<Integer> tset2 = new TreeSet<Integer>();


Java Programming 23

// Adding elements to TreeSet<Integer>

tset2.add(88);

tset2.add(7);

tset2.add(101);

tset2.add(0);

tset2.add(3);

tset2.add(222);

System.out.println(tset2);

Output:

You can see both the TreeSet have been sorted in ascending order implicitly.

[ABC, Ink, Jack, Pen, String, Test]

[0, 3, 7, 88, 101, 222]

4. Priority Queue[3 marks]

A PriorityQueue is used when the objects are supposed to be processed based on the priority. It is known that a
queue follows First-In-First-Out algorithm, but sometimes the elements of the queue are needed to be
processed according to the priority, that’s when the PriorityQueue comes into play. The PriorityQueue is based
on the priority heap. The elements of the priority queue are ordered according to the natural ordering, or by a
Comparator provided at queue construction time, depending on which constructor is used.

In the below priority queue, element with maximum ASCII value will have the highest priority.
Java Programming 24

Few important points on Priority Queue are as follows:

 PriorityQueue doesn’t permit null.


 We can’t create PriorityQueue of Objects that are non-comparable
 PriorityQueue are unbound queues.
 The head of this queue is the least element with respect to the specified ordering. If multiple elements
are tied for least value, the head is one of those elements — ties are broken arbitrarily.
 The queue retrieval operations poll, remove, peek, and element access the element at the head of the
queue.
 It inherits methods from AbstractQueue, AbstractCollection, Collection and Object class.

Mostly used Constructors of PriorityQueue class

 PriorityQueue(): Creates a PriorityQueue with the default initial capacity (11) that orders its elements
according to their natural ordering.
 PriorityQueue(Collection<E> c): Creates a PriorityQueue containing the elements in the specified
collection.

Methods in PriorityQueue class:


1) boolean add(E element): This method inserts the specified element into this priority queue.
2) public remove(): This method removes a single instance of the specified element from this
queue, if it is present
3) public poll(): This method retrieves and removes the head of this queue, or returns null if this
queue is empty.
Java Programming 25

4) public peek(): This method retrieves, but does not remove, the head of this queue, or returns null
if this queue is empty.
5) Iterator iterator(): Returns an iterator over the elements in this queue.
6) boolean contains(Object o): This method returns true if this queue contains the specified
element
7) void clear(): This method is used to remove all of the contents of the priority queue.
8) boolean offer(E e): This method is used to insert a specific element into the priority queue.
9) int size(): The method is used to return the number of elements present in the set.
10) toArray(): This method is used to return an array containing all of the elements in this queue.
11) Comparator comparator(): The method is used to return the comparator that can be used to
order the elements of the queue.

Below program illustrates the basic operations of PriorityQueue:


// Java program to demonstrate working of priority queue in Java

import java.util.*;

class Example {

public static void main(String args[]) {

// Creating empty priority queue

PriorityQueue<String> pQueue =new PriorityQueue<String>();

// Adding items to the pQueue using add()

pQueue.add("C");

pQueue.add("C++");

pQueue.add("Java");

pQueue.add("Python");

// Printing the most priority element

System.out.println("Head value using peek function:" + pQueue.peek());

// Printing all elements

System.out.println("The queue elements:");

Iterator itr = pQueue.iterator();


Java Programming 26

while (itr.hasNext())

System.out.println(itr.next());

// Removing the top priority element (or head) and

// printing the modified pQueue using poll()

pQueue.poll();

System.out.println("After removing an element" +"with poll function:");

Iterator<String> itr2 = pQueue.iterator();

while (itr2.hasNext())

System.out.println(itr2.next());

// Removing Java using remove()

pQueue.remove("Java");

System.out.println("after removing Java with" +" remove function:");

Iterator<String> itr3 = pQueue.iterator();

while (itr3.hasNext())

System.out.println(itr3.next());

// Check if an element is present using contains()

boolean b = pQueue.contains("C");

System.out.println ( "Priority queue contains C " + "or not?: " + b);

// Getting objects from the queue using toArray()

// in an array and print the array

Object[] arr = pQueue.toArray();

System.out.println ( "Value in array: ");

for (int i = 0; i<arr.length; i++)


Java Programming 27

System.out.println ( "Value: " + arr[i].toString()) ;

Output:

Head value using peek function:C

The queue elements:

C++

Java

Python

After removing an elementwith poll function:

C++

Python

Java

after removing Java with remove function:

C++

Python

Priority queue contains C or not?: false

Value in array:

Value: C++

Value: Python
Java Programming 28

4. Array Deque

The java.util.ArrayDeque class provides resizable-array and implements the Deque interface. Following
are the important points about Array Deques −

 Array deques have no capacity restrictions so they grow as necessary to support usage.
 They are not thread-safe; in the absence of external synchronization.
 They do not support concurrent access by multiple threads.
 Null elements are prohibited in the array deques.
 They are faster than Stack and LinkedList.

This class and its iterator implement all of the optional methods of the Collection and Iterator interfaces.

Array Deque Class declaration

Following is the declaration for java.util.ArrayDeque class –

public class ArrayDeque<E> extends AbstractCollection<E> implements Deque<E>, Cloneable, Serializable

Here <E> represents an Element, which could be any class. For example, if you're building an array list of
Integers then you'd initialize it as −

ArrayList<Integer> list = new ArrayList<Integer>();

Class constructors

Constructor Description

ArrayDeque() This constructor is used to create an empty array deque with an


initial capacity sufficient to hold 16 elements.

ArrayDeque(Collection<? extends E> c) This constructor is used to create a deque containing the elements
of the specified collection.

ArrayDeque(int numElements) This constructor is used to create an empty array deque with an
initial capacity sufficient to hold the specified number of
elements.
Java Programming 29

Below table represents some of Array Deque Class methods

Method &Description

boolean add(E e) This method inserts the specified element at the end of this deque.

void addFirst(E e) This method inserts the specified element at the front of this deque.

void addLast(E e) This method inserts the specified element at the end of this deque.

void clear() This method removes all of the elements from this deque.

ArrayDeque<E> clone() This method returns a copy of this deque.

boolean contains(Object o) This method returns true if this deque contains the specified element.

Iterator<E> iterator() This method returns an iterator over the elements in this deque.

E getFirst() This method retrieves, but does not remove, the first element of this deque.

E getLast() This method retrieves, but does not remove, the last element of this deque.

boolean isEmpty() This method returns true if this deque contains no elements.

E pop() This method pops an element from the stack represented by this deque.

void push(E e) This method pushes an element onto the stack represented by this deque.

E remove() This method retrieves and removes the head of the queue represented by this
deque.

boolean remove(Object o) This method removes a single instance of the specified element from this
deque.

object[] toArray() This method returns an array containing all of the elements in this deque in
proper sequence.
Java Programming 30

4.1.4 Accessing a Collection via an Iterator

To access, modify or remove any element from any collection we need to first find the element, for which we
have to cycle through the elements of the collection. There are three possible ways to cycle through the
elements of any collection.

1. Using Iterator interface


2. Using ListIterator interface
3. Using for-each loop

Steps to use an Iterator

1. Obtain an iterator to the start of the collection by calling the collection's iterator() method.
2. Set up a loop that makes a call to hasNext() method. Make the loop iterate as long
as hasNext() method returns true.
3. Within the loop, obtain each element by calling next() method.

Accessing elements using Iterator

Iterator Interface is used to traverse a list in forward direction, enabling you to remove or modify the elements
of the collection. Each collection classes provide iterator() method to return an iterator.

Methods of Iterator:

Method Description

boolean hasNext() Returns true if there are more elements in the collection. Otherwise, returns false.

E next() Returns the next element present in the collection. Throws


NoSuchElementException if there is not a next element.

void remove() Removes the current element. Throws IllegalStateException if an attempt is made
to call remove() method that is not preceded by a call to next() method.

import java.util.*;

class Test_Iterator

public static void main(String[] args)


Java Programming 31

ArrayList< String> ar = new ArrayList< String>();

ar.add("ab");

ar.add("bc");

ar.add("cd");

ar.add("de");

Iterator it = ar.iterator(); //Declaring Iterator

while(it.hasNext())

System.out.print(it.next()+" ");

Output:

ab bc cd de

4.1.5 Using an Iterator


Before you can access a collection through an iterator, you must obtain one. Each of the collection classes
provides an iterator( ) method that returns an iterator to the start of the collection. By using this iterator object,
you can access each element in the collection, one element at a time. In general, to use an iterator to cycle
through the contents of a collection, follow these steps:

1. Obtain an iterator to the start of the collection by calling the collection’s iterator( ) method.

2. Set up a loop that makes a call to hasNext( ). Have the loop iterate as long as hasNext( ) returns true.

3. Within the loop, obtain each element by calling next( ).

For collections that implement List, you can also obtain an iterator by calling listIterator( ). As explained, a list
iterator gives you the ability to access the collection in either the forward or backward direction and lets you
Java Programming 32

modify an element. Otherwise, ListIterator is used just like Iterator. The following example implements these
steps, demonstrating both the Iterator and ListIterator interfaces. It uses an ArrayList object, but the general
principles apply to any type of collection. Of course, ListIterator is available only to those collections that
implement the List interface.

Accessing elements using ListIterator

ListIterator Interface is used to traverse a list in both forward and backward direction. It is available to only
those collections that implements the List Interface.

Methods of ListIterator:

Method Description

void add(E obj) Inserts obj into the list in front of the element that will be returned by the next
call to next() method.

boolean hasNext() Returns true if there is a next element. Otherwise, returns false.

boolean hasPrevious() Returns true if there is a previous element. Otherwise, returns false.

E next() Returns the next element. A NoSuchElementException is thrown if there is not


a next element.

int nextIndex() Returns the index of the next element. If there is not a next element, returns the
size of the list.

E previous() Returns the previous element. A NoSuchElementException is thrown if there is


not a previous element.

int previousIndex() Returns the index of the previous element. If there is not a previous element,
returns -1.

void remove() Removes the current element from the list. An IllegalStateException is thrown
if remove() method is called before next() or previous() method is invoked.

void set(E obj) Assigns obj to the current element. This is the element last returned by a call to
either next() or previous() method.
Java Programming 33

import java.util.*;

class Test_Iterator {

public static void main(String[] args) {

ArrayList< String> ar = new ArrayList< String>();

ar.add("ab");

ar.add("bc");

ar.add("cd");

ar.add("de");

ListIterator litr = ar.listIterator();

while(litr.hasNext()) //In forward direction {

System.out.print(litr.next()+" ");

while(litr.hasPrevious()) //In backward direction {

System.out.print(litr.previous()+" ");

Output:

ab bc cd de

de cd bc ab
Java Programming 34

4.1.6 The for-each alternative

Using for-each loop

for-each version of for loop can also be used for traversing the elements of a collection. But this can only be
used if we don't want to modify the contents of a collection and we don't want any reverse access. for-
each loop can cycle through any collection of object that implements Iterable interface.

The use of enhanced for loop is easier to write and makes your code more readable. Hence, it's recommended
over standard form whenever possible.

Syntax of for-each loop

Let's first look at the syntax of for each loop:

for(data_type item : collection) {

...

import java.util.*;

class ForEachDemo {

public static void main(String[] args) {

LinkedList< String> ls = new LinkedList< String>();

ls.add("a");

ls.add("b");

ls.add("c");

ls.add("d");

for(String str : ls) {

System.out.print(str+" ");

}
Java Programming 35

Output:

abcd

4.1.7 Map Interface and Classes

Java Map Interface

A map contains values on the basis of key, i.e. key and value pair. Each key and value pair is known as an entry.
A Map contains unique keys.

A Map is useful if you have to search, update or delete elements on the basis of a key.

Java Map Hierarchy

There are two interfaces for implementing Map in java: Map and SortedMap, and three classes: HashMap,
LinkedHashMap, and TreeMap. The hierarchy of Java Map is given below:
Java Programming 36

A Map doesn't allow duplicate keys, but you can have duplicate values. HashMap and LinkedHashMap allow
null keys and values, but TreeMap doesn't allow any null key or value.

A Map can't be traversed, so you need to convert it into Set using keySet() or entrySet() method.

Class Description

HashMap HashMap is the implementation of Map, but it doesn't maintain any order.

LinkedHashMap LinkedHashMap is the implementation of Map. It inherits HashMap class. It


maintains insertion order.

TreeMap TreeMap is the implementation of Map and SortedMap. It maintains


ascending order.

Useful methods of Map interface

Method Description

V put(Object key, Object value) It is used to insert an entry in the map.

void putAll(Map map) It is used to insert the specified map in the map.

V putIfAbsent(K key, V value) It inserts the specified value with the specified key in the map only
if it is not already specified.

V remove(Object key) It is used to delete an entry for the specified key.

boolean remove(Object key, Object It removes the specified values with the associated specified keys
value) from the map.

Set keySet() It returns the Set view containing all the keys.

Set<Map.Entry<K,V>> entrySet() It returns the Set view containing all the keys and values.

void clear() It is used to reset the map.


Java Programming 37

V compute(K key, BiFunction<? super It is used to compute a mapping for the specified key and its
K,? super V,? extends V> current mapped value (or null if there is no current mapping).
remappingFunction)

V computeIfAbsent(K key, Function<? It is used to compute its value using the given mapping function, if
super K,? extends V> the specified key is not already associated with a value (or is
mappingFunction) mapped to null), and enters it into this map unless null.

V computeIfPresent(K key, It is used to compute a new mapping given the key and its current
BiFunction<? super K,? super V,? mapped value if the value for the specified key is present and non-
extends V> remappingFunction) null.

boolean containsValue(Object value) This method returns true if some value equal to the value exists
within the map, else return false.

boolean containsKey(Object key) This method returns true if some key equal to the key exists within
the map, else return false.

boolean equals(Object o) It is used to compare the specified Object with the Map.

void forEach(BiConsumer<? super K,? It performs the given action for each entry in the map until all
super V> action) entries have been processed or the action throws an exception.

V get(Object key) This method returns the object that contains the value associated
with the key.

V getOrDefault(Object key, V It returns the value to which the specified key is mapped, or
defaultValue) defaultValue if the map contains no mapping for the key.

int hashCode() It returns the hash code value for the Map

boolean isEmpty() This method returns true if the map is empty; returns false if it
contains at least one key.

V merge(K key, V value, If the specified key is not already associated with a value or is
BiFunction<? super V,? super V,? associated with null, associates it with the given non-null value.
Java Programming 38

extends V> remappingFunction)

V replace(K key, V value) It replaces the specified value for a specified key.

boolean replace(K key, V oldValue, V It replaces the old value with the new value for a specified key.
newValue)

void replaceAll(BiFunction<? super It replaces each entry's value with the result of invoking the given
K,? super V,? extends V> function) function on that entry until all entries have been processed or the
function throws an exception.

Collection values() It returns a collection view of the values contained in the map.

int size() This method returns the number of entries in the map.

Java Map Example: Non-Generic (Old Style)

//Non-generic

import java.util.*;

public class MapExample1 {

public static void main(String[] args) {

Map map=new HashMap();

//Adding elements to map

map.put(1,"Amit");

map.put(5,"Rahul");

map.put(2,"Jai");

map.put(6,"Amit");

//Traversing Map
Java Programming 39

Set set=map.entrySet();//Converting to Set so that we can traverse

Iterator itr=set.iterator();

while(itr.hasNext()){

//Converting to Map.Entry so that we can get key and value separately

Map.Entry entry=(Map.Entry)itr.next();

System.out.println(entry.getKey()+" "+entry.getValue());

Output:

1 Amit

2 Jai

5 Rahul

6 Amit

Java Map Example: Generic (New Style)

import java.util.*;

class MapExample2{

public static void main(String args[]){

Map<Integer,String> map=new HashMap<Integer,String>();

map.put(100,"Amit");
Java Programming 40

map.put(101,"Vijay");

map.put(102,"Rahul");

//Elements can traverse in any order

for(Map.Entry m : map.entrySet()){

System.out.println(m.getKey()+" "+m.getValue());

Output:

102 Rahul

100 Amit

101 Vijay

Java Map Example: comparingByKey()

import java.util.*;

class MapExample3{

public static void main(String args[]){

Map<Integer,String> map=new HashMap<Integer,String>();

map.put(100,"Amit");

map.put(101,"Vijay");

map.put(102,"Rahul");
Java Programming 41

//Returns a Set view of the mappings contained in this map

map.entrySet()

//Returns a sequential Stream with this collection as its source

stream()

//Sorted according to the provided Comparator

System.out.println(“comparingByKey in ascending order”);

sorted(Map.Entry.comparingByKey())

//Performs an action for each element of this stream

forEach(System.out::println);

System.out.println(“comparingByKey in descending order”);

//Sorted according to the provided Comparator

sorted(Map.Entry.comparingByKey(Comparator.reverseOrder()))

//Performs an action for each element of this stream

forEach(System.out::println);

System.out.println(“comparingByValue in ascending order”);

//Sorted according to the provided Comparator

sorted(Map.Entry.comparingByValue())

//Performs an action for each element of this stream

forEach(System.out::println);
Java Programming 42

System.out.println(“comparingByValue in descending order”);

//Sorted according to the provided Comparator

sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))

//Performs an action for each element of this stream

forEach(System.out::println);

Output:

comparingByKey in ascending order

100=Amit

101=Vijay

102=Rahul
comparingByKey in descending order

102=Rahul

101=Vijay

100=Amit

comparingByValue in ascending order

100=Amit

102=Rahul

101=Vijay
Java Programming 43

comparingByValue in descending order

101=Vijay

102=Rahul

100=Amit

4.1.8 Comparators

By default, TreeSet and TreeMap store their elements by using what Java refers to as “natural ordering,” which
is usually the ordering that you would expect (A before B, 1 before 2, and so forth). If you want to order
elements a different way, then specify a Comparator when you construct the set or map. Doing so gives you
the ability to govern precisely how elements are stored within sorted collections and maps.

Comparator is a generic interface that has this declaration:

Syntax: interface Comparator<T>

Here, T specifies the type of objects being compared.

The Comparator interface defines two methods:

1. compare( )
2. equals( )

1.The compare( ) method, shown here, compares two elements for order:

Syntax: int compare(T obj1, T obj2);

 obj1 and obj2 are the objects to be compared.


 This method returns zero if the objects are equal.
 It returns a positive value if obj1 is greater than obj2.
 Otherwise, a negative value is returned.
 The method can throw a ClassCastException if the types of the objects are not compatible for
comparison.
Java Programming 44

 By overriding compare( ), you can alter the way that objects are ordered. For example, to sort in reverse
order, you can create a comparator that reverses the outcome of a comparison.
2.The equals( ) method, shown here, tests whether an object equals the invoking comparator:

Syntax: boolean equals(Object obj);

Here, obj is the object to be tested for equality.

The method returns true if obj and the invoking object are both Comparator objects and use the same ordering.
Otherwise, it returns false. Overriding equals( ) is unnecessary, and most simple comparators will not do so.

Using a Comparator

The following is an example that demonstrates the power of a custom comparator. It implements the
compare( ) method for strings that operates in reverse of normal. Thus, it causes a tree set to be stored in
reverse order.

// Use a custom comparator.

import java.util.*;

// A reverse comparator for strings.

class MyComp implements Comparator<String> {

public int compare(String a, String b) {

String aStr, bStr;

aStr = a;

bStr = b;

// Reverse the comparison.

return bStr.compareTo(aStr);

// No need to override equals.

class CompDemo {
Java Programming 45

public static void main(String args[]) {

// Create a tree set.

TreeSet<String> ts = new TreeSet<String>(new MyComp());

// Add elements to the tree set.

ts.add("C");

ts.add("A");

ts.add("B");

ts.add("E");

ts.add("F");

ts.add("D");

// Display the elements.

for(String element : ts)

System.out.print(element + " ");

System.out.println();

As the following output shows, the tree is now stored in reverse order:

FEDCBA

Look closely at the MyComp class, which implements Comparator and overrides compare( ). (As explained
earlier, overriding equals( ) is neither necessary nor common.) Inside compare( ), the String method
compareTo( ) compares the two strings. However, bStr— not aStr—invokes compareTo( ). This causes the
outcome of the comparison to be reversed.

.
Java Programming 46

4.1.9 Collection algorithms

The collections framework defines several algorithms that can be applied to collections and maps.These
algorithms are defined as static methods within the Collections class. Several of the methods can throw
a ClassCastException, which occurs when an attempt is made to compare incompatible types, or
an UnsupportedOperationException, which occurs when an attempt is made to modify an unmodifiable
collection.The few methods defined in collection framework's algorithm are summarized in the following table

Method Description

static int binarySearch(List list, Object value); Searches for value in the list. The list must be
sorted. Returns the position of value in list, or -1
if value is not found.

static void copy(List list1, List list2); Copies the elements of list2 to list1.

static ArrayList list(Enumeration enum); Returns an ArrayList that contains the elements
of enum.

static Object max(Collection c); Returns the maximum element in c as


determined by natural ordering. The collection
need not be sorted.

static Object min(Collection c); Returns the minimum element in c as


determined by natural ordering.

static boolean replaceAll(List list, Object old, Replaces all occurrences of old with new in the
list. Returns true if at least one replacement
Object new);
occurred. Returns false, otherwise.

static Comparator reverseOrder( );

Returns a reverse comparator.

static void shuffle(List list); Shuffles (i.e., randomizes) the elements in list.

static void sort(List list); Sorts the elements of the list as determined by
their natural ordering.

static void swap(List list, int idx1, int idx2); Exchanges the elements in the list at the indices
specified by idx1 and idx2.
Java Programming 47

Example

Following is an example, which demonstrates various algorithms.

import java.util.*;

public class AlgorithmsDemo {

public static void main(String args[]) {

// Create and initialize linked list

LinkedList ll = new LinkedList();

ll.add(new Integer(-8));

ll.add(new Integer(20));

ll.add(new Integer(-20));

ll.add(new Integer(8));

Comparator r = Collections.reverseOrder(); // Create a reverse order comparator

Collections.sort(ll, r); // Sort list by using the comparator

Iterator li = ll.iterator(); // Get iterator

System.out.print("List sorted in reverse: ");

while(li.hasNext()) {

System.out.print(li.next() + " ");

System.out.println();

Collections.shuffle(ll);
Java Programming 48

// display randomized list

li = ll.iterator();

System.out.print("List shuffled: ");

while(li.hasNext()) {

System.out.print(li.next() + " ");

System.out.println();

System.out.println("Minimum: " + Collections.min(ll));

System.out.println("Maximum: " + Collections.max(ll));

This will produce the following result −

Output

List sorted in reverse: 20 8 -8 -20

List shuffled: 20 -20 8 -8

Minimum: -20

Maximum: 20
Java Programming 49

4.1.10 Arrays

Arrays are objects they inherit all the characteristics of java.lang.Object

All array objects also have some other characteristics; i.e., each array has an associated field named length.

Notice it is a field named length, unlike the instance method named length() associated with String objects.

Creating an array

... is like creating an object from a class:

 declaration - assigns a name to the reference


 instantiation - creates space for the object
 initialization - gives the objects values for the first time

Arrays of primitive data types are initialized to 0

int[] grades;

grades = new int[60];

Arrays of Objects are initialized to null

Arrays of non-primitive data types are not initialized to 0

Student[] students;

students = new Student[60];

The students array has been declared and instantiated, but not yet initialized: no

Student object references have been assigned to the array elements.

To initialize the array elements, you need to instantiate each individually:

for (int nextStudent = 0; nextStudent < 10; nextStudent++ ) {

students[nextStudent] = new CSEStudent();

}
Java Programming 50

Arrays Can Be Made of Any Type or Class

"Declaring a variable of array type does not create an array object or allocate any space for array components.
It creates only the variable itself, which can contain a reference to an array."

 Arrays are created (instantiated) with new, just like other objects.
 Once an array is created, its length never changes.

4.1.11 The Legacy Classes and Interfaces- Dictionary

Java consists of several classes and interfaces to hold the objects before Java 1.2 version. Before this version,
there was no existence of Collection Framework. classes and interfaces are used to hold objects in that
scenario. These classes are also known as Legacy classes and interface

 Legacy classes in Java

 Dictionary

 Properties

 HashTable

 Vector

 Stack

 Legacy Interface

 Enumeration

Legacy Interface The Enumeration

The Enumeration interface defines the methods by which you can enumerate (obtain one at a time) the
elements in a collection of objects. This legacy interface has been superseded by Iterator. Although not
deprecated, Enumeration is considered obsolete for new code. However, it is used by several methods defined
by the legacy classes (such as Vector and Properties) and is used by several other API classes. Because it is
still in use, it was retrofitted for generics by JDK 5. It has this declaration:

Syntax: interface Enumeration<E>


Java Programming 51

where E specifies the type of element being enumerated.

Enumeration specifies the following two methods:

 boolean hasMoreElements( )

 E nextElement( )

When implemented, hasMoreElements( ) must return true while there are still more elements to extract,
and false when all the elements have been enumerated.

nextElement( ) returns the next object in the enumeration. That is, each call to nextElement( ) obtains the next
object in the enumeration. It throws NoSuchElementException when the enumeration is complete.

import java.util.*;
class VectorDemo
{
public static void main(String args[])
{
// initial size is 3, increment is 2
Vector<Integer> v = new Vector<Integer>(3, 2);

System.out.println("Initial size: " + v.size());


System.out.println("Initial capacity: " +v.capacity());
v.addElement(1);
v.addElement(2);
v.addElement(3);
v.addElement(4);
Enumeration<Integer> vEnum = v.elements();
System.out.println("\nElements in vector:");
while(vEnum.hasMoreElements())
System.out.print(vEnum.nextElement() + " ");
System.out.println();
}
}
The output from this program is shown here:
Initial size: 0
Initial capacity: 3
Elements in vector:
1234
Java Programming 52

Legacy class Dictionary

Dictionary is an abstract class. The main work is to hold the data as the key or value pair. It works in the form
of Map Collection. Given a key and value, you can store the value in a Dictionary object. Once the value is
stored, you can retrieve it by using its key. Thus, like a map, a dictionary can be thought of as a list of key/value
pairs.

With the advent of JDK 5, Dictionary was made generic. It is declared as shown here:

Syntax: class Dictionary<K, V>

Here, K specifies the type of keys, and V specifies the type of values. The abstract methods defined
by Dictionary are listed in Table below.

Method Purpose
Enumeration<V> elements( ) Returns an enumeration of the values contained in the dictionary.
V get(Object key) Returns the object that contains the value associated with key. If key is
not in the dictionary, a null object is returned
boolean isEmpty( ) Returns true if the dictionary is empty, and returns false if it contains at
least one key
Enumeration<K> keys( ) Returns an enumeration of the keys contained in the dictionary.
V put(K key, V value) Inserts a key and its value into the dictionary. Returns null if key is not
already in the dictionary; returns the previous value associated with key
if key is already in the dictionary
V remove(Object key) Removes key and its value. Returns the value associated with key. If key
is not in the dictionary, a null is returned.
int size( ) Returns the number of entries in the dictionary
Java Programming 53

Example program on Dictionary methods:


import java.util.*;

public class Dict

public static void main(String[] args)

Dictionary dictionary = new Hashtable();

dictionary.put("surname", "abc"); // put method

dictionary.put("middlename", "def"); // put method

System.out.println("\nsurname: " + dictionary.get("surname")); // get method

System.out.println("middlename: " + dictionary.get("middlename ")); // get method

System.out.println();

// elements method

for (Enumeration i = dictionary.elements(); i.hasMoreElements();)

System.out.println("Values contained in Dictionary : " + i.nextElement());

System.out.println();

// keys method :

for (Enumeration k = dictionary.keys(); k.hasMoreElements();) {

System.out.println("Keys contianed in Dictionary : " + k.nextElement());

// isEmpty method

System.out.println("\nThe dictionary is empty? " + dictionary.isEmpty());


Java Programming 54

// remove method :

dictionary.remove("surname");

// Checking if the value is removed or not

System.out.println("\surname: " + dictionary.get("surname"));

// size method

System.out.println("\nSize of Dictionary : " + dictionary.size());

Output:

surname:abc

middlename:def

Values contained in Dictionary:

abc

def

Keys contianed in Dictionary

sur name

middlename

surname:null

The dictionary is empty? False

Size of Dictionary

1
Java Programming 55

Legacy class
Hashtable

Hashtable was part of the original java.util and is a concrete implementation of a Dictionary..

Hashtable stores key/value pairs in a hash table. However, neither keys nor values can be null. When using
a Hashtable, you specify an object that is used as a key, and the value that you want linked to that key. The
key is then hashed, and the resulting hash code is used as the index at which the value is stored within the
table.

Hashtable was made generic by JDK 5. It is declared like this:

Syntax: class Hashtable<K, V>

Here, K specifies the type of keys, and V specifies the type of values.

The Hashtable constructors are::[2 marks]

Syntax:

Hashtable( );

Hashtable(int size);

Hashtable(int size, float fillRatio);

Hashtable(Map<? extends K, ? extends V> m);

Hashtable defines the legacy methods listed in below . Several methods throw NullPointerException if an
attempt is made to use a null key or value.

Method Description
void clear( ) Resets and empties the hash table
Object clone( ) Returns a duplicate of the invoking object
boolean contains(Object value) Returns true if some value equal to value exists within
the hash table. Returns false if the value isn’t found.
boolean containsKey(Object key) Returns true if some key equal to key exists within the
hash table. Returns false if the key isn’t found
boolean containsValue(Object value) Returns true if some value equal to value exists within
the hash table. Returns false if the value isn’t found
Enumeration<V> elements( ) Returns an enumeration of the values contained in the
hash table.
V get(Object key) Returns the object that contains the value associated
Java Programming 56

with key. If key is not in the hash table, a null object


is returned.
boolean isEmpty( ) Returns true if the hash table is empty; returns false if
it contains at least one key
Enumeration<K> keys( ) Returns an enumeration of the keys contained in the
hash table.
V put(K key, V value): Inserts a key and a value into the hash table. Returns
null if key isn’t already in the hash table; returns the
previous value associated with key if key is already in
the hash table
void rehash( ) Increases the size of the hash table and rehashes all of
its keys.
V remove(Object key) Removes key and its value. Returns the value
associated with key. If key is not in the hash table, a
null object is returned
int size( ) Returns the number of entries in the hash table.
String toString( ) Returns the string equivalent of a hash table.

// Demonstrate a Hashtable.

import java.util.*;

class HTDemo

public static void main(String args[]) {

Hashtable<String, Double> balance =new Hashtable<String, Double>();

Enumeration<String> names;

String str;

double bal;

balance.put("John Doe", 3434.34);

balance.put("Tom Smith", 123.22);


Java Programming 57

balance.put("Jane Baker", 1378.00);


balance.put("Tod Hall", 99.22);
balance.put("Ralph Smith", -19.08);
// Show all balances in hashtable.
names = balance.keys();
while(names.hasMoreElements())
{
str = names.nextElement();
System.out.println(str + ": " +balance.get(str));
}
System.out.println();
// Deposit 1,000 into John Doe's account.
bal = balance.get("John Doe");
balance.put("John Doe", bal+1000);
System.out.println("John Doe's new balance: " + balance.get("John Doe"));
}
}
The output from this program is shown here:
Todd Hall: 99.22

Ralph Smith: -19.08

John Doe: 3434.34

Jane Baker: 1378.0

Tom Smith: 123.22

John Doe's new balance: 4434.34


Java Programming 58

Legacy class Properties


Properties is a subclass of Hashtable. It is used to maintain lists of values in which the key is a String and the
value is also a String.

Properties instance variable:

Syntax: Properties defaults;

This variable holds a default property list associated with a Properties object.

Properties constructors:

Syntax:

 Properties( );

 Properties(Properties propDefault);

The first version creates a Properties object that has no default values.

The second creates an object that uses propDefault for its default values.

In both cases, the property list is empty.

Properties defines the methods listed in below Table.


Java Programming 59

Example program to demonstrate Properties.

It creates a property list in which the keys are the names of states and the values are the names of their capitals.
Notice that the attempt to find the capital for Florida includes a default value.

// Demonstrate a Property list.


import java.util.*;

class PropDemo {

public static void main(String args[])


{
Properties capitals = new Properties();
capitals.put("Illinois", "Springfield");
capitals.put("Missouri", "Jefferson City");
capitals.put("Washington", "Olympia");
capitals.put("California", "Sacramento");
Java Programming 60

capitals.put("Indiana", "Indianapolis");

//Get a set-view of the keys.


Set<?> states = capitals.keySet();

//Show all of the states and capitals.

for(Object name : states)

System.out.println("The capital of " +name + " is " + capitals.getProperty((String)name) + ".");

System.out.println();

// Look for state not in list -- specify default.

String str = capitals.getProperty("Florida", "Not Found");


System.out.println("The capital of Florida is " + str + ".");
}

The output from this program is shown here:

The capital of Missouri is Jefferson City.

The capital of Illinois is Springfield.

The capital of Indiana is Indianapolis.

The capital of California is Sacramento.

The capital of Washington is Olympia.

The capital of Florida is Not Found.

Since Florida is not in the list, the default value is used.


Java Programming 61

Legacy class Stack[3 marks]

Stack is a subclass of Vector that implements a standard “last-in, first-out” stack. Stack only defines the
default constructor, which creates an empty stack. With the release of JDK 5, Stack was retrofitted for generics
and is declared as shown here:

Syntax: class Stack<E>

Here, E specifies the type of element stored in the stack.

Stack includes all the methods defined by Vector and adds several of its own, shown in belowTable.

Method Description
boolean empty( ) Returns true if the stack is empty, and returns false if the stack contains elements.
E peek( ) Returns the element on the top of the stack, but does not remove it
E pop( ) Returns the element on the top of the stack, removing it in the : process
E push(E element) Pushes element onto the stack. element is also returned.
int search(Object element) Searches for element in the stack. If found, its offset from the top of the stack is
returned. Otherwise, –1 is returned.

Example program to demonstrate Stack Class

Here is an example that creates a stack, pushes several Integer objects onto it, and then pops them off again:

import java.util.*;

class StackDemo

static void showpush(Stack<Integer> st, int a)

st.push(a);

System.out.println("push(" + a + ")");

System.out.println("stack: " + st);

}
Java Programming 62

static void showpop(Stack<Integer> st)

System.out.print("pop -> ");

Integer a = st.pop();

System.out.println(a);

System.out.println("stack: " + st);

public static void main(String args[])

Stack<Integer> st = new Stack<Integer>();

System.out.println("stack: " + st);

showpush(st, 42);

showpush(st, 66);

showpush(st, 99);

showpop(st);

showpop(st);

showpop(st);

try

showpop(st);
Java Programming 63

catch (EmptyStackException e)

System.out.println("empty stack");

Output:

stack: [ ] push(42)
stack: [42] push(66)
stack: [42, 66] push(99)
stack: [42, 66, 99] pop -> 99
stack: [42, 66] pop -> 66
stack: [42]
pop -> 42
stack: [ ]pop -> empty stack
Java Programming 64

Legacy class Vector

Vector implements a dynamic array. It is similar to ArrayList, but with two differences −

• Vector is synchronized.

• Vector contains many legacy methods that are not part of the collections framework.

Vector proves to be very useful if you don't know the size of the array in a dvance or you just need one that can
change sizes over the lifetime of a program.

Syntax: class Vector<E>

Following is the list of constructors provided by the vector class.

Constructor Description

Vector( )
This constructor creates a default vector, which has an initial size of 10.

Vector(int size)
This constructor accepts an argument that equals to the required size, and
creates a vector whose initial capacity is specified by size.

Vector(int size, int incr)


This constructor creates a vector whose initial capacity is specified by size
and whose increment is specified by incr. The increment specifies the
number of elements to allocate each time that a vector is resized upward.

Vector(Collection c)
This constructor creates a vector that contains the elements of collection c.

Method Description

int size() It returns the size of the Vector

int capacity() It returns the capacity of the Vector

addElement(element ); It add an element to the Vector

firstElement() It returns the first element in Vector

lastElement() It returns the last element in Vector


Java Programming 65

Example program to Demonstrate various Vector operations.

import java.util.*;
class VectorDemo
{
public static void main(String args[])
{
// initial size is 3, increment is 2
Vector<Integer> v = new Vector<Integer>(3, 2);

System.out.println("Initial size: " + v.size());


System.out.println("Initial capacity: " +v.capacity());
v.addElement(1);
v.addElement(2);
v.addElement(3);
v.addElement(4);
System.out.println("Capacity after four additions: " + v.capacity());
v.addElement(5); System.out.println("Current capacity: " +v.capacity());
v.addElement(6);
v.addElement(7);
System.out.println("Current capacity: " + v.capacity());
v.addElement(9);
v.addElement(10);
System.out.println("Current capacity: " + v.capacity());
v.addElement(11);
v.addElement(12);
System.out.println("First element: " + v.firstElement());
System.out.println("Last element: " + v.lastElement());
if(v.contains(3))
System.out.println("Vector contains 3.");
// Enumerate the elements in the vector.
Enumeration<Integer> vEnum = v.elements();
System.out.println("\nElements in vector:");
while(vEnum.hasMoreElements())
System.out.print(vEnum.nextElement() + " ");
System.out.println();
}
}

The output from this program is shown here:


Initial size: 0
Initial capacity: 3
Capacity after four additions: 5
Current capacity: 5
Current capacity: 7
Current capacity: 9
First element: 1
Java Programming 66

Last element: 12
Vector contains 3.
Elements in vector:
1 2 3 4 5 6 7 9 10 11 12

What is the difference between array and vector?[3 marks]

Concept name array vector


Resize Length of the array is fixed i.e once it is A vector is a resizable – array
created we cannot added or remove which works by reallocating
elements storage

Sychronized Array is not Sychronized Vector is Sychronized


Performance Array is faster Vector is relatively slow
Storage It does not reserve any additional storage Vector reserves O(n) additional
storage
trimToSize() Array doesnot have trimToSize() Vector uses trimToSize()
To remove additional storage
Elements It can hold both primitives and java It can hold only java objects
objects
size It uses length property to store length. It uses size() method to get size .
Dimensions java support single and multi dimensional Vectors doesnot have a concept of
array dimensions,but it supports vector of
Vectors
Generics It does not support Generics It support Generics to ensure type
safety
Java Programming 67

4.2 Utility classes

The final java package,java.util contains a collection of utility classes.

utility classes includes:

 -String Tokenizer
 -Bit Set
 -Date
 -Caleneder
 -Random
 -Formatter
 -Scanner

4.2.1 String Tokenizer *** [3 marks]


The string tokenizer class allows an application to break a string into tokens. The StringTokenizer methods do
not distinguish among identifiers, numbers, and quoted strings, nor do they recognize and skip comments.

The set of delimiters (the characters that separate tokens) may be specified either at creation time or on a per -
token basis.

String Tokenizer Constructors:

Constructor Description

StringTokenizer(String str) Constructs a string tokenizer for the specified string.

StringTokenizer(String str, String delim) Constructs a string tokenizer for the specified string.

StringTokenizer(String str, String delim, boolean Constructs a string tokenizer for the specified string.
returnDelims)

An instance of StringTokenizer behaves in one of two ways, depending on whether it was created with
the returnDelims flag having the value true or false:

 If the flag is false, delimiter characters serve to separate tokens. A token is a maximal sequence of
consecutive characters that are not delimiters.

 If the flag is true, delimiter characters are themselves considered to be tokens. A token is thu s either one
delimiter character, or a maximal sequence of consecutive characters that are not delimiters.

A StringTokenizer object internally maintains a current position within the string to be tokenized. Some
operations advance this current position past the characters processed.
Java Programming 68

A token is returned by taking a substring of the string that was used to create the StringTokenizer object.

String Tokenizer Methods:

Method Description

int countTokens() Calculates the number of times that this okenizer's nextToken method
can be called before it generates an exception.

boolean hasMoreElements() Returns the same value as the hasMoreTokens method.

boolean hasMoreTokens() Tests if there are more tokens available from this tokenizer's string.

Object nextElement() Returns the same value as the nextToken method, except that its
declared return value is Object rather than String.

String nextToken() Returns the next token from this string tokenizer.

String nextToken(String delim) Returns the next token in this string tokenizer's string.

StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in
new code. It is recommended that anyone seeking this functionality use the split method of String or
the java.util.regex package instead.

Example for String Tokenizer :

import java.util.StringTokenizer;

class StringTokenizerDemo
{
public static void main(String arg[])
{
StringTokenizer st1 = new StringTokenizer("Welcome to CMREC" + " Campus."); // LINE A
while (st1.hasMoreTokens()) {
System.out.println(st1.nextToken());
}
System.out.print("---------\n");
StringTokenizer st2 = new StringTokenizer("It's an,Education," + "Website." , ","); // LINE B
while (st2.hasMoreTokens()) {
System.out.println(st2.nextToken());
}
System.out.print("---------\n");
StringTokenizer st3 = new StringTokenizer("Learn~programming~with Java.", "~", true); // LINE C
Java Programming 69

while (st3.hasMoreTokens()) {
System.out.println(st3.nextToken());
}
}
}

OUTPUT

Welcome
to
Merit
Campus.
---------
It's an
Education
Website.
---------
Learn
~
programming
~
with Java.

DESCRIPTION

In LINE A the StringTokenizer breaks the String "Welcome to Merit Campus." into tokens and the tokens are
printed. In LINE B the StringTokenizer breaks the String "It's an, Education, Website." into tokens using "," as
a delimiter and the tokens are printed. In LINE C the StringTokenizer breaks the String "Learn, programming,
with Java." into tokens using "~" as a delimiter, includes the delimiter as returnDelims flag is true and the
tokens are printed.

4.2.2 Bit Set[3marks]


 The BitSet class creates a special type of array that holds bit values.
 This array can increase in size as needed.
 This makes it similar to a vector of bits.
 The bits of a BitSet are indexed by nonnegative integers.
 Individual indexed bits can be examined, set, or cleared.
 One BitSet may be used to modify the contents of another BitSet through logical AND, logical
inclusive OR, and logical exclusive OR operations.

Constructors :
BitSet class has two constructors:
Java Programming 70

Constructor Description
BitSet() Creates a default object
BitSet( int size ) Allows us to specify the initial size i.e. the no. of bits that the BitSet can hold

NOTE: By default, all bits are initialized to zero.

Some Important Methods :

Method Description
Object clone() Creates a copy of the invoking BitSet object.
void set( int index ) Sets the bit specified by index.
void set( int index, boolean v ) Sets the bit specified by index to the value passed in v.
true sets the bit and false clears the bit
void or( BitSet bitSet ) ORs the contents of the invoking BitSet object with
that specified by bitSet and places the result into the
invoking object.
void and( BitSet bitSet ) ANDs the contents of the invoking BitSet object with
that specified by bitSet and places the result into the
invoking object
void andNot( BitSet bitSet ) For each 1 bit in bitSet, the corresponding bit in the
invoking BitSet is cleared
void xor( BitSet bitSet ) XORs the contents of the invoking BitSet object with
that specified by bitSet and places the result into the
invoking object
void set( int startIndex, int endIndex ) Sets the bits from startIndex to (endIndex – 1)
void set( int startIndex, int endIndex, boolean v ) Sets the bits from startIndex to (endIndex – 1) to the
value passed in v. true sets the bits and false clears the
bits
void flip(int index) Reverse the bit specified by index.
void flip(int startIndex, int endIndex) Reverse the bits from startIndex to endIndex-1
Java Programming 71

Example for BitSet:

class BitSetDemo
{
public static void main(String arg[])
{
BitSet bitSetA = new BitSet();
bitSetA.set(2);
bitSetA.set(3);
bitSetA.set(4);
bitSetA.set(5);
System.out.println("bitSetA = " + bitSetA);
BitSet bitSetB = new BitSet();
bitSetB.set(1, 5);
System.out.println("bitSetB = " + bitSetB);
// Clone of bitSetA
BitSet bitSetC = new BitSet();
bitSetC = (BitSet) bitSetA.clone();
System.out.println("bitSetC = " + bitSetC);
// AND bits
bitSetA.and(bitSetB);
System.out.println("bitSetA and bitSetB = " + bitSetA);
// OR bits
bitSetA.or(bitSetB);
System.out.println("bitSetA or bitSetB = " + bitSetA);
// AND NOT
bitSetA.andNot(bitSetB);
System.out.println("bitSetA and not bitSetB = " + bitSetA);
// XOR bits
bitSetC.xor(bitSetB);
System.out.println("bitSetC xor bitSetB = " + bitSetC);
}
}

OUTPUT

bitSetA = {2, 3, 4, 5}
bitSetB = {1, 2, 3, 4}
bitSetC = {2, 3, 4, 5}
bitSetA and bitSetB = {2, 3, 4}
bitSetA or bitSetB = {1, 2, 3, 4}
bitSetA and not bitSetB = {}
bitSetC xor bitSetB = {1, 5}
Java Programming 72

DESCRIPTION

From the output of the above program, it is clear that when toString() converts a BitSet object to its string
equivalent, each set bit is represented by its position i.e., with toString() call in the statements ---
System.out.println( bitSetA )

Then with and() method call, corresponding bits in the invoking BitSet (bitSetA) and the passed BitSet
(bitSetB) are ANDed and the result is placed into the invoking BitSet (i.e., bitSetA). The result follows from
normal AND semantics. Same applies for or() and xor()method calls with respective semantics.

With bitSetA.andNot( bitSetB ) method call, since bits at positions {1, 2, 3, 4} are set in bitSetB,
corresponding bits in bitSetA are cleared. So bitSetA will become {}.

4.2.3 Date

Date class is available in java.util package, it represents a specific instant of time, with millisecond
precision. Date allows the interpretation of dates as year, month, day, hour, minute, and second values. It also
allows the formatting and parsing of date strings.

Date Constructors:

Constructor Description
Allocates a Date object and initializes it so that it represents the time at which it
Date()
was allocated, measured to the nearest millisecond.
Allocates a Date object and initializes it to represent the specified number of
Date(long date) milliseconds since the standard base time known as "the epoch",
namely January 1, 1970, 00:00:00 GMT.

Date Methods:

Method Description
boolean after(Date date) Tests if this date is after the specified date.
boolean before(Date date) Tests if this date is before the specified date.
Object clone() Return a copy of this object.
int compareTo(Date date) Compares two dates for ordering.
boolean equals(Object date) Compares two dates for equality.
Java Programming 73

long getTime() Returns the number of milliseconds since January 1, 1970,


00:00:00 GMT represented by this Date object.
int hashCode() Returns a hash code value for this object.
void setTime(long time) Sets this Date object to represent a point in time that is time
milliseconds after January 1, 1970 00:00:00 GMT.
String toString() Converts this Date object to a String.

Simple Date Format Codes:

Character Description Example


y Year in four digits 2013

M Month in a year July or 07

d Day in a month 10

h Hour in A.M./P.M. (1~12) 12

H Hour in day (0~23) 22

m Minute in hour 30

s Second in minute 56

S Millisecond 234

E Day in week Friday

D Day in year 364

F Day of week in month 2 (second Wed. in July)

w Week in year 40

W Week in month 1

a A.M./P.M. marker PM

k Hour in day (1~24) 23

K Hour in A.M./P.M. (0~11) 10


Java Programming 74

z Time zone Eastern Standard Time

' Escape for text Delimiter

" Single quote '

G Era designator AD

Example program to demonstrate Date Methods:

import java.text.SimpleDateFormat;
import java.util.Date;
class DateMethodTest

{
public static void main(String arg[])

{
try

{
Date date1 = new Date(); // LINE A
// Current date is stored in date1
String dateInString = "15-08-1947 02:25:56";
SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
Date date2 = df.parse(dateInString); // LINE B
System.out.println("The date1 is after date2 : " + date1.after(date2));
System.out.println("The date2 is before date1 : " + date2.before(date1));
Date date3 = (Date) date1.clone();
// Copies date1 into date3
System.out.println(date1.compareTo(date3)); // LINE C
// Prints 0
System.out.println(date1.compareTo(date2)); // LINE D
// Prints 1
System.out.println("The date3 is equals to date1 : " + date3.equals(date1));
System.out.println("Milli second for date1 : " + date1.getTime());
Java Programming 75

System.out.println("Hash code for date1 : " + date1.hashCode());


System.out.println("The date1 before setTime : " + date1);
date1.setTime(10000); // LINE E
System.out.println("The date1 after setTime : " + date1);
String dateString = date1.toString(); // LINE F
System.out.println("The string form of date1 : " + dateString);
} catch (Exception e)
{
e.printStackTrace();
}
}
}

OUTPUT

The date1 is after date2 : true


The date2 is before date1 : true
0
1
The date3 is equals to date1 : true
Milli second for date1 : 1397812350984
Hash code for date1 : 1947980109
The date1 before setTime : Fri Apr 18 14:42:30 IST 2014
The date1 after setTime : Thu Jan 01 05:30:10 IST 1970
The string form of date1 : Thu Jan 01 05:30:10 IST 1970

DESCRIPTION

In this program, At LINE A current date is stored in date1 and at LINE B the value of String dateInstring is
stored in date2. The after, before, clone, compareTo, equals, getTime, hashCode, setTime()
and toString methods are applied on these two dates, compareTo returns 0 if they are same else 1. The output
varies as the time various so it need not be same as the present output for current date.
Java Programming 76

4.2.4 Calender

Calender is an abstract class. It provides a set of methods to manipulate the date and time. The subclass of
calender class provides the specific implementation to the abstract methods defined by calender to meet their
own requirements.

For example Java GregorianCalendar is a subclass of calender class. The calender class does not define its
constructor. Therefore an object of an abstract calender class can’t be created. The calender defines several
methods. some commonly used methods are as follows:

Calender Methods:

Method Description
This method returns the object of calender class for the
static Calender getInstance()
default location and time zone.
This method returns the value of the requested component
of the invoking object. This component is specified be
Int get(int const)
‘const’. It can be any one of the integer constants. For
example Calender.DATE, Calender.HOUR etc.
This method sets the value of the date or time component
Void set(int const,int value) specified by const.This const must be one of the constant
defined by calender class. For example Calender.HOUR.
final void set(int year, int month, int Sets various date and time components of the invoking
dayOfMonth) object.
final void set(int year, int month, int Sets various date and time components of the invoking
dayOfMonth, int hours, int minutes) object.
final void set(int year, int month, int Sets various date and time components of the invoking
dayOfMonth, int hours, int minutes, int object.
seconds)
These methods get and set the time zone for the invoking
TimeZonegetTimeZone()
object. +zObj parameter of setTimeZone() method
Void setTimeZone(TimeZone+zObj)
specifies the TimeZone object to be set.
This method returns true if both the invoking calender
Boolean equals(Object calObj) object and the one specified by calObj Object. Otherwise
returns false.
This method returns true if the invoking calender object
Boolean after(Object calObj) contains a date that comes after the date specified
by calObj object. Otherwise returns false.
This method returns true if the invoking calender object
Boolean before(Object calObj) contains a date that comes before the date specified
by calObj object. Otherwise returns false.
Java Programming 77

Calendar defines the following int constants, which are used when you get or set components of the calendar:

ALL_STYLES FRIDAY PM

AM HOUR SATURDAY

AM_PM HOUR_OF_DAY SECOND

APRIL JANUARY SEPTEMBER

AUGUST JULY SHORT

DATE JUNE SUNDAY

DAY_OF_MONTH LONG THURSDAY

DAY_OF_WEEK MARCH TUESDAY

DAY_OF_WEEK_IN_MONTH MAY UNDECIMBER

DAY_OF_YEAR MILLISECOND WEDNESDAY

DECEMBER MINUTE WEEK_OF_MONTH

DST_OFFSET MONDAY WEEK_OF_YEAR

ERA MONTH YEAR

FEBRUARY NOVEMBER ZONE_OFFSET

FIELD_COUNT OCTOBER

DateAndTime Example :

import java.util.Calendar;

class ExampleOfDateAndTime
{
public static void main(String arg[])
{
String months[] = {"JAN", "FEB", "MAR", "APR", "MAY", "JUNE", "JULY", "AUG", "SEPT", "OCT",
"NOV", "DEC"};

/*Create a calendar initialized with the current date and time in the default locale and timezone.*/
Java Programming 78

Calendar cal = Calendar.getInstance();


//Display current time and date information.
System.out.println("Date :");
System.out.print(months[cal.get(java.util.Calendar.MONTH)]);
System.out.print(" " + cal.get(Calendar.DATE) + " ");// LINE D
System.out.println(cal.get(Calendar.YEAR));

System.out.println("Current Time: "); // LINE A


System.out.print(cal.get(Calendar.HOUR) + ":");
System.out.print(cal.get(Calendar.MINUTE) + ":");
System.out.println(cal.get(Calendar.SECOND));

//Set the time and date information and display it.


cal.set(Calendar.HOUR, 10); // LINE C
cal.set(Calendar.MINUTE, 29); // LINE C
cal.set(Calendar.SECOND, 22); // LINE C

System.out.println("Updated time"); // LINE B


System.out.print(cal.get(Calendar.HOUR) + ":");
System.out.print(cal.get(Calendar.MINUTE) + ":");
System.out.println(cal.get(Calendar.SECOND));

}
}

OUTPUT

Date :
APR 9 2019
Current Time:
7:40:20
Updated time
10:29:22

DESCRIPTION

In the above program we have created a String array months and stored all the months and we created
a Calendar reference cal and invoked all the respective methods at LINE A to print the current date and time
Java Programming 79

4.2.5 Random

java.util.Random instance is used to generate a stream of pseudo-random numbers.

Random Constructors:

Constructor Description
Random() Creates a new random number generator.
Random(long seed) Creates a new random number generator using a single long seed.

Random Methods:

Method Description
protected int next(int bits) Generates the next pseudorandom number.
boolean nextBoolean() Returns the next pseudorandom, uniformly distributed boolean value from
this random number generator's sequence.
void nextBytes(byte[] bytes) Generates random bytes and places them into a user-supplied byte array.
double nextDouble() Returns the next pseudorandom, uniformly distributed double value
between 0.0 and 1.0 from this random number generator's sequence.
float nextFloat() Returns the next pseudorandom, uniformly distributed float value between
0.0 and 1.0 from this random number generator's sequence.
double nextGaussian() Returns the next pseudorandom, Gaussian ("normally") distributed double
value with mean 0.0 and standard deviation 1.0 from this random number
generator's sequence.
int nextInt() Returns the next pseudorandom, uniformly distributed int value from this
random number generator's sequence.
int nextInt(int n) Returns a pseudorandom, uniformly distributed int value between 0
(inclusive) and the specified value n (exclusive), drawn from this random
number generator's sequence.
long nextLong() Returns the next pseudorandom, uniformly distributed long value from
this random number generator's sequence.
void setSeed(long seed) Sets the seed of this random number generator using a single long seed.
Java Programming 80

Random

import java.util.Random;

class RandomTest
{
public static void main(String arg[])
{
Random r = new Random();

System.out.println("The next Integer value : " + r.nextInt()); // LINE A


System.out.println("The next Boolean value : " + r.nextBoolean());

byte[] b = new byte[30];


r.nextBytes(b); // Puts the next byte in array
System.out.println("Value of Byte array : " + b);

System.out.println("The next Double value : " + r.nextDouble());


System.out.println("The next Float value : " + r.nextFloat());
System.out.println("The next Gaussian value : " + r.nextGaussian());
System.out.println("The next Integer value between 0 to 4 : " + r.nextInt(5));
System.out.println("The next Long value : " + r.nextLong());
r.setSeed(20);
System.out.println("The set Seed value : " + r.nextInt());

}
}

OUTPUT

The next Integer value : 1129872169


The next Boolean value : true
Value of Byte array : [B@103074e
The next Double value : 0.47766930003831065
Java Programming 81

The next Float value : 0.13917398


The next Gaussian value : 0.8715938816913958
The next Integer value between 0 to 4 : 1
The next Long value : 3604397887200514771
The set Seed value : -1150867590

DESCRIPTION

In this program, a random object is created and respective Integer, Boolean, Byte, Double, Float, Gaussian,
Long values are generated. Note that when you run the program, the same output might not come. For every run
the output will be different.

4.2.6 Formatter

Introduction

The java.util.Formatter class provides support for layout justification and alignment, common formats for
numeric, string, and date/time data, and locale-specific output.Following are the important points about
Formatter −

 Formatters are not necessarily safe for multithreaded access.Thread safety is optional and is the
responsibility of users of methods in this class.

Class declaration

Following is the declaration for java.util.Formatter class −

public final class Formatter extends Object implements Closeable, Flushable

Formatte Class constructors

Constructor Description
Formatter() This constructor constructs a new formatter.
This constructor constructs a new formatter with the specified
Formatter(Appendable a)
destination.
This constructor constructs a new formatter with the specified
Formatter(Appendable a, Locale l)
destination and locale.
Formatter(File file) This constructor constructs a new formatter with the specified file.
Formatter(File file, String csn) This constructor constructs a new formatter with the specified file
Java Programming 82

and charset.
Formatter(File file, String csn, This constructor constructs a new formatter with the specified file,
Locale l) charset, and locale.
Formatter(Locale l) This constructor constructs a new formatter with the specified locale.
This constructor constructs a new formatter with the specified output
Formatter(OutputStream os)
stream.
Formatter(OutputStream os, String This constructor constructs a new formatter with the specified output
csn) stream and charset.
Formatter(OutputStream os, String This constructor constructs a new formatter with the specified output
csn, Locale l) stream, charset, and locale.
This constructor constructs a new formatter with the specified print
Formatter(PrintStream ps)
stream.
This constructor constructs a new formatter with the specified file
Formatter(String fileName)
name.

Formatter(String fileName, String


csn) This constructor constructs a new formatter with the specified file
name and charset.
Formatter(String fileName, String This constructor constructs a new formatter with the specified file
csn, Locale l) name, charset, and locale.

Formatte Class methods

Method Description
void close() This method closes this formatter.
void flush() This method flushes this formatter.
This method writes a formatted string to this object's
Formatter format(Locale l, String format, Object...
destination using the specified locale, format string,
args)
and arguments.
This method writes a formatted string to this object's
Formatter format(String format, Object... args) destination using the specified format string and
arguments.
This method returns the IOException last thrown by
IOException ioException()
this formatter's Appendable.
This method returns the locale set by the construction
Locale locale()
of this formatter.
Appendable out() This method returns the destination for the output.

This method returns the result of invoking toString()


String toString()
on the destination for the output.
Java Programming 83

Format Specifier Conversion Applied

%a %A Floating-point hexadecimal

%b %B Boolean

%c Character

%d Decimal Integer

%h %H Hash code of the argument

%e %E Scientfic notation

%f Decimal floating-point

%g %G Uses %e or %f, whichever is shorter

%o Octal Integer

%n Inserts a newline character

%s %S String

%t %T Time and date

%x %X Integer hexadecimal

%% Inserts a % sign
Java Programming 84

Example program to demonstrate Formatte Class methods

import java.util.*;

class BasicFormatterDemo
{
public static void main(String arg[])
{
Formatter formatter = new Formatter();

formatter.format("Learn Java by %s in %d days and score %f", " U r self ", 90, 100.00);

System.out.println(formatter);
formatter.close();
}
}

Output:
Learn Java by U r self in 90 days and score 100.000000

4.2.7 Scanner

Introduction

The java.util.Scanner class is a simple text scanner which can parse primitive types and strings using regular
expressions.Following are the important points about Scanner −

 A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
 A scanning operation may block waiting for input.
 A Scanner is not safe for multithreaded use without external synchronization.

Scanner Class declaration

Following is the declaration for java.util.Scanner class −

public final class Scanner extends Object implements Iterator<String>


Java Programming 85

Scanner Class constructors


Constructor Description
Scanner(File source)
This constructs a new Scanner that produces values
scanned from the specified file.

This constructs a new Scanner that produces values


Scanner(File source, String charsetName)
scanned from the specified file.
This constructs a new Scanner that produces values
Scanner(InputStream source)
scanned from the specified input stream.
Scanner(InputStream source, String charsetName) This constructs a new Scanner that produces values
scanned from the specified input stream.
Scanner(Readable source) This constructs a new Scanner that produces values
scanned from the specified source.
Scanner(ReadableByteChannel source) This constructs a new Scanner that produces values
scanned from the specified channel.
Scanner(ReadableByteChannel source, String This constructs a new Scanner that produces values
charsetName) scanned from the specified channel.

Scanner(String source) This constructs a new Scanner that produces values


scanned from the specified string.

Scanner Class methods


Method. Description
void close() This method closes this scanner.

Pattern delimiter() This method returns the Pattern this Scanner is currently using to
match delimiters.
boolean hasNext() This method returns true if this scanner has another token in its
input.
boolean hasNext(Pattern pattern) This method returns true if the next complete token matches the
specified pattern.
boolean hasNext(String pattern) This method returns true if the next token matches the pattern
constructed from the specified string.
This method returns true if the next token in this scanner's input can
boolean hasNextInt() be interpreted as an int value in the default radix using the nextInt()
method.
String next() This method finds and returns the next complete token from this
scanner.
int nextInt() This method scans the next token of the input as an int.
String nextLine() This method advances this scanner past the current line and returns
Java Programming 86

the input that was skipped.


long nextLong()
This method scans the next token of the input as a long.

void remove() The remove operation is not supported by this implementation of


Iterator.

Example program on Scanner class


import java.util.*;
public class ScannerClassExample1 {
public static void main(String args[]){
String s = "Hello, This is JavaProgramming.";
//Create scanner Object and pass string in it
Scanner scan = new Scanner(s);
//Check if the scanner has a token
System.out.println("Boolean Result: " + scan.hasNext());
//Print the string
System.out.println("String: " +scan.nextLine());
scan.close();
System.out.println("--------Enter Your Details-------- ");
Scanner in = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = in.next();
System.out.println("Name: " + name);
System.out.print("Enter your age: ");
int i = in.nextInt();
System.out.println("Age: " + i);
System.out.print("Enter your salary: ");
double d = in.nextDouble();
System.out.println("Salary: " + d);
in.close();
}
}
Output:
Boolean Result: true
String: Hello, This is JavaProgramming.
-------Enter Your Details---------
Enter your name:abc
Name: abc
Enter your age: 23
Age: 23
Enter your salary: 25000
Salary: 25000.0
Java Programming 87

UNIT_IV JNTUH PREVIOUSLY ASKED SHORT ANSWER QUESTIONS

1. What is the difference between array and vector?

2. List the hash table constructors.

3. Explain the methods defined by Vector.

4. Explain the use of String tokenizer with an example

5. Write about any 3 methods defined by Iterator

6. What is the use of String Tokenizer class?

7. List the functions of Stack class.

8. What is the use of Iterator class?

9. What is the benefit of Generics in Collections Framework?

10. Differentiate between Enumeration and Iterator interface.

11. Which methods of deque enable it to be used as a stack?

12. Make a comparison of List, array and ArrayList.

13. What is the significance of Legacy class? Give example.

14. is the purpose of String Tokenizer class? Explain.

15. What is a Java Priority queue?

16. What is a Collection Class? Give an example.


Java Programming 88

UNIT-IV JNTUH-PREVIOUSLY ASKD ESSAY QUESTIONS


1 .a) Give an account of Random collection class
b) Discuss the methods of Stack class
c) What is the need of Generics? [3+3+4]

2.a) Explain the file management using File class.


b) Write a program which stores a list of strings in an Array List and then displays the contents of the list.
[5+5]
3 .Write the name of bank depositor and their balance using Hash table.

4. a) Differentiate between ArrayList and Vector.


b) List the methods of Stack class. [5+5]
5 .a) What is a vector? How does it differ from array, list?
b) Write a program to count number of words in a given sentence. [5+5]

6 .a) What is Java Collections Framework? List out some benefits of Collections framework
and explain.
b) What is the importance of hashCode() and equals() methods? [5+5]
7 a) What are the common algorithms implemented in Collections Framework? Discuss.
b) What is difference between ArrayList and LinkedList in collection framework? Explain.
[5+5]

8 a) Contrast sorted map and navigable map interfaces.


b) What is the purpose of BitSet class? What is the functionality of the following functions
of BitSet class: cardinality( ) , flip( ) and intersects( ) [5+5]

9 a) Differentiate between ArrayList and a Vector? Why ArrayList is faster than Vector?
Explain.
b) How an Hashtable can change the iterator? Explain. [5+5]

10 a) Explain the Bit Set and Calander classes in detail.


b) Discuss the differences between HashList and HashMap, Set and List. [5+5]

11 a) What are similarities and difference between ArrayList and Vector? Explain.
b) What is different between Iterator and ListIterator? Explain different ways to iterate over
a list. [5+5]
12 .a) What are the best practices related to Java Collections Framework? Discuss.
b) What is Comparable and Comparator interface? Differentiate between them. [5+5]
GUI Programming with Swing
Event Handling, SWING
Application AND APPLETS
Java Programming 2

5.1 GUI Programming with Swings

5.1.1 Introduction
Computer users today expect to interact with their computers using a graphical user interface (GUI). Java can
be used to write GUI programs ranging from simple applets which run on a Web page to sophisticated stand-
alone applications.

GUI programs differ from traditional “straight-through” programs that you have encountered in the first few
chapters of this book. One big difference is that GUI programs are event-driven. That is, user actions such as
clicking on a button or pressing a key on the keyboard generate events, and the program must respond to these
events as they occur.

And of course, objects are everywhere in GUI programming. Events are objects. Colors and fonts are objects.
GUI components such as buttons and menus are objects. Events are handled by instance methods contained in
objects. In Java, GUI programming is object-oriented programming.

The Basic GUI Application

There are two basic types of GUI program in Java: stand-alone applications and applets. An applet is a
program that runs in a rectangular area on a Web page. very complex. We will look at applets in the next
section.

A stand-alone application is a program that runs on its own, without depending on a Web browser. You’ve
been writing stand-alone applications all along. Any class that has a main() routine defines a stand-alone
application; running the program just means executing this main() routine.

A GUI program offers a much richer type of user interface, where the user uses a mouse and keyboard to
interact with GUI components such as windows, menus, buttons, check boxes, text input boxes, scroll bars, and
so on. The main routine of a GUI program creates one or more such components and displays them on the
computer screen. Very often, that’s all it does. Once a GUI component has been created, it follows its own
programming—programming that tells it how to draw itself on the screen and how to respond to events such as
being clicked on by the user.
Java Programming 3

A GUI program doesn’t have to be immensely complex. We can, for example, write a very simple GUI “Hello
World” program that says “Hello” to the user, but does it by opening a window where the the greeting is
displayed:

import javax.swing.JOptionPane;

public class HelloWorldGUI1 {

public static void main(String[] args) {

JOptionPane.showMessageDialog( null, "Hello World!" );

When this program is run, a window appears on the screen that contains the message “Hello World!”. The
window also contains an “OK” button for the user to click after reading the message. When the user clicks this
button, the window closes and the program ends. By the way, this program can be placed in a file named
HelloWorldGUI1.java, compiled, and run just like any other Java program.

5.1.2 Limitations of AWT

The AWT defines a basic set of controls, windows, and dialog boxes that support a usable, but limited
graphical interface. One reason for the limited nature of the AWT is that it translates its various visual
components into their corresponding, platform-specific equivalents or peers. This means that the look and feel
of a component is defined by the platform, not by java. Because the AWT components use native code
resources, they are referred to as heavy weight.The use of native peers led to several problems. First, because
of variations between operating systems, a component might look, or even act, differently on different

platforms. This variability threatened java’s philosophy: write once, run anywhere.Second, the look and feel of
each component was fixed and could not be changed. Third,the use of heavyweight components caused some
frustrating restrictions.
Java Programming 4

Summary on limitations of AWT

AWT supports limited number of GUI components

AWT component are Heavy weight components

AWT components are developed by using platform specific code

AWT components behaves differently in different Operating Systems.

AWT components is converted by the native code of the Operating System.

5.1.3 MVC Architecture


In real time applications, in the case of server side programming one must follow the architecture to develop a
distributed application.To develop any distributed application, it is always recommended to follow either 3-tier
architecture or 2-tier architecture or n-tier architecture.

3-tier architecture is also known as MVC architecture.

M stands for Model (database programming),


V stands for View (client side programming, HTML/AWT/APPLET/Swing/JSP) and
C stands for Controller (server side programming, Servlets).

Model :

 This is the data layer which consists of the business logic of the system.
 It consists of all the data of the application
 It also represents the state of the application.
 It consists of classes which have the connection to the database.
 The controller connects with model and fetches the data and sends to the view layer.
 The model connects with the database as well and stores the data into a database which is connected to
it.

View :

 This is a presentation layer.


 It consists of HTML, JSP, etc. into it.
 It normally presents the UI of the application.
 It is used to display the data which is fetched from the controller which in turn fetching data from model
layer classes.
 This view layer shows the data on UI of the application.
Java Programming 5

Controller:

 It acts as an interface between View and Model.


 It intercepts all the requests which are coming from the view layer.
 It receives the requests from the view layer and processes the requests and does the necessary validation
for the request.
 This requests is further sent to model layer for data processing, and once the request is processed, it
sends back to the controller with required information and displayed accordingly by the view.

The general architecture of MVC or 3-tier:

1. Client makes a request.

2. Server side program receives the request.

3. The server looks for or search for the appropriate resource in the resource pool.

4. If the resource is not available server side program displays a user friendly message (page cannot be
displayed). If the resource is available, that program will execute gives its result to server, server interns gives
response to that client who makes a request.

5. When server want to deals with database to retrieve the data, server side program sends a request to the
appropriate database.

6. Database server receives the server request and executes that request.

7. The database server sends the result back to server side program for further processing.

8. The server side program is always gives response to ‘n’ number of clients concurrently.
Java Programming 6

MVC in Swing

Swing actually uses a simplified variant of the MVC design called the model-delegate . This design combines
the view and the controller object into a single element, the UI delegate , which draws the component to the
screen and handles GUI events. Bundling graphics capabilities and event handling is somewhat easy in Java,
since much of the event handling is taken care of in AWT. As you might expect, the communication between
the model and the UI delegate then becomes a two-way street, as shown in Figure below.

So let’s review: each Swing component contains a model and a UI delegate. The model is responsible for
maintaining information about the component’s state. The UI delegate is responsible for maintaining
information about how to draw the component on the screen. In addition, the UI delegate (in conjunction with
AWT) reacts to various events that propagate through the component.

Note that the separation of the model and the UI delegate in the MVC design is extremely advantageous. One
unique aspect of the MVC architecture is the ability to tie multiple views to a single model. For example, if
you want to display the same data in a pie chart and in a table, you can base the views of two components on a
single data model. That way, if the data needs to be changed, you can do so in only one place—the views
update themselves accordingly
Java Programming 7

5.1.4 Components

Component is an object having a graphical representation that can be displayed on the screen and that can
interact with the user. For examples buttons, checkboxes, list and scrollbars of a graphical user interface.

A Component is an abstract super class for GUI controls and it represents an object with graphical
representation.

Every AWT controls inherits properties from Component class


Java Programming 8

Component Description

Label The easiest control to use is a label. A label is an object of type Label, and it contains a
string,which it displays. Labels are passive controls that do not support any interaction
with theuser. Label defines the following constructors

Button This class creates a labeled button.

Check Box A check box is a graphical component that can be in either an on (true) or off (false)
state.

Check Box Group The CheckboxGroup class is used to group the set of checkbox.

List The List component presents the user with a scrolling list of text items.

Text Field A TextField object is a text component that allows for the editing of a single line of text.

Text Area A TextArea object is a text component that allows for the editing of a multiple lines of
text.

Choice A Choice control is used to show pop up menu of choices. Selected choice is shown on
the top of the menu.

Canvas A Canvas control represents a rectangular area where application can draw something or
can receive inputs created by user.

Image An Image control is superclass for all image classes representing graphical images.

Scroll Bar A Scrollbar control represents a scroll bar component in order to enable user to select
from range of values.

Dialog A Dialog control represents a top-level window with a title and a border used to take
Java Programming 9

some form of input from the user.

File Dialog A FileDialog control represents a dialog window from which the user can select a file.

Commonly used Methods of Component class:

Method Description

public void add(Component c) inserts a component on this component.

public void setSize(intwidth,int height) sets the size (width and height) of the component.

public void setLayout(LayoutManager m) defines the layout manager for the component.

public void setVisible(boolean status) changes the visibility of the component, by default false.

void remove(Component obj) Here, obj is a reference to the control you want to
remove.

void removeAll( ). You can remove all controls by


Java Programming 10

Labels

The easiest control to use is a label. A label is an object of type Label, and it contains a string,

which it displays. Labels are passive controls that do not support any interaction with the

user.

Label defines the following constructors:

 Label( ) throws HeadlessException


 Label(String str) throws HeadlessException
 Label(String str, int how) throws HeadlessException

The first version creates a blank label.

The second version creates a label that contains thestring specified by str. This string is left-justified.

The third version creates a label that contains the string specified by str using the alignment specified by how.
The value of how must be one of these three constants: Label.LEFT, Label.RIGHT, or Label.CENTER.

You can set or change the text in a label by using the setText( ) method. You can obtain the current label by
calling getText( ).

These methods are shown here:

void setText(String str)

String getText( )

For setText( ), str specifies the new label. For getText( ), the current label is returned.

The below figure represents the appears of Label


Java Programming 11

Buttons

Perhaps the most widely used control is the push button. A push button is a component that contains a label
and that generates an event when it is pressed. Push buttons are objects of type Button.

Button defines these two constructors:

 Button( ) throws HeadlessException


 Button(String str) throws HeadlessException

The first version creates an empty button.

The second creates a button that contains str as a label.

After a button has been created, you can set its label by calling setLabel( ). You can retrieve its label by calling
getLabel( ).

These methods are as follows:

void setLabel(String str)

String getLabel( )

Here, str becomes the new label for the button

The below figure represents the appears of Buttons

1.
Java Programming 12

Check Box

A check box is a control that is used to turn an option on or off. It consists of a small box that can either
contain a check mark or not. There is a label associated with each check box that describes what option the box
represents. You change the state of a check box by clicking on it. Check boxes can be used individually or as
part of a group. Check boxes are objects of the Checkbox class.

Checkbox supports these constructors:

 Checkbox( ) throws HeadlessException


 Checkbox(String str) throws HeadlessException
 Checkbox(String str, boolean on) throws HeadlessException
 Checkbox(String str, boolean on, CheckboxGroup cbGroup) throws HeadlessException
 Checkbox(String str, CheckboxGroup cbGroup, boolean on) throws HeadlessException

The first form creates a check box whose label is initially blank. The state of the check box isunchecked.

The second form creates a check box whose label is specified by str. The state ofthe check box is unchecked.
The third form allows you to set the initial state of the checkbox. If on is true, the check box is initially checked;
otherwise, it is cleared.

The fourth and fifth forms create a check box whose label is specified by str and whose group is specified by
cbGroup. If this check box is not part of a group, then cbGroup must be null. (Check box groups are described
in the next section.) The value of on determines the initial state of thecheck box.

To retrieve the current state of a check box, call getState( ). To set its state, callsetState( ). You can obtain the
current label associated with a check box by callinggetLabel( ). To set the label, call setLabel( ).

These methods are as follows:

boolean getState( )

void setState(boolean on)

String getLabel( )
Java Programming 13

void setLabel(String str)Here, if on is true, the box is checked. If it is false, the box is cleared. The string passed
in str becomes the new label associated with the invoking check box.

The below figure represents the appears of CheckBox

CheckboxGroup

It is possible to create a set of mutually exclusive check boxes in which one and only one check box in the
group can be checked at any one time. These check boxes are often called radio buttons. To create a set of
mutually exclusive check boxes, you must firstdefine the group to which they will belong and then specify that
group when you constructthe check boxes.

You can determine which check box in a group is currently selected by calling getSelectedCheckbox( ). You
can set a check box by calling setSelectedCheckbox( ).

These methods are as follows:

Checkbox getSelectedCheckbox( )

void setSelectedCheckbox(Checkbox which)

Here, which is the check box that you want to be selected. The previously selected check box will be turned off.
Java Programming 14

The below figure represents the appears of CheckboxGroup

What are the differences between JToggle buttion and Radio buttion? [2marks]

Toggle Button:

Toggles should be used to represent an action, like turning something on or off, or starting or stopping an
activity. It should be clear which state is on and which state is off. As the name suggest a button whose state can
be toggled from on to off or vice-versa. For example a Switch in your home to turn a particular light on or off.

Toggle button has immediate effect on selection.

Radio Button:
Java Programming 15

Radio buttons should be used when the user can select one, and only one, option from a list of items. The button
should be circular and become filled in when it is selected. Its name comes from the concept of buttons in Radio
where for first station you press first button and for second station you press second button and so forth. So you
can choose from multiple options. But at a time only one will be selected.

Radio Button has effect only after pressing Submit button

Choice

The Choice class is used to create a pop-up list of items from which the user may choose.Thus, a Choice control
is a form of menu. When inactive, a Choice component takes up only enough space to show the currently
selected item. When the user clicks on it, the whole list of choices pops up, and a new selection can be made.
Each item in the list is a string that appears as a left-justified label in the order it is added to the Choice object.
Choice only defines the default constructor, which creates an empty list.

 To add a selection to the list, call add( ). It has this general form:

void add(String name);

Here, name is the name of the item being added. Items are added to the list in the order inwhich calls to add( )
occur.

To determine which item is currently selected, you may call either getSelectedItem( )or getSelectedIndex( ).
These methods are shown here:

String getSelectedItem( );
Java Programming 16

int getSelectedIndex( );

The getSelectedItem( ) method returns a string containing the name of the item.getSelectedIndex( ) returns the
index of the item. The first item is at index 0. By default,the first item added to the list is selected.

To obtain the number of items in the list, call getItemCount( ). You can set the currently selected item using the
select( ) method with either a zero-based integer index or a string that will match a name in the list. Given an
index you can obtain the name associated with the item at that index by calling getItem( ),

These methods are shown here:

int getItemCount( );

void select(int index);

void select(String name);

String getItem(int index);

Here, index specifies the index of the desired item

The below figure represents the appears of Choice


Java Programming 17

Lists

The List class provides a compact, multiple-choice, scrolling selection list. Unlike theChoice object, which
shows only the single selected item in the menu, a List object can be constructed to show any number of choices
in the visible window. It can also be created toallow multiple selections.

List constructors:

 List( ) throws HeadlessException


 List(int numRows) throws HeadlessException
 List(int numRows, boolean multipleSelect) throws HeadlessException

The first version creates a List control that allows only one item to be selected at any onetime.

In the second form, the value of numRows specifies the number of entries in the list that will always be visible
(others can be scrolled into view as needed).

In the third form, if multipleSelect is true, then the user may select two or more items at a time. If it is false,
then only one item may be selected.

To add a selection to the list, call add( ). It has the following two forms:

void add(String name);

void add(String name, int index);

Here, name is the name of the item added to the list. The first form adds items to the end of the list. The second
form adds the item at the index specified by index. Indexing begins at zero. You can specify –1 to add the item
to the end of the list.

For lists that allow only single selection, you can determine which item is currently selected by calling either
getSelectedItem( ) or getSelectedIndex( ).
Java Programming 18

These methods are shown here:

String getSelectedItem( )

int getSelectedIndex( )

For lists that allow multiple selection, you must use either getSelectedItems( ) or getSelectedIndexes( ), shown
here, to determine the current selections:

String[ ] getSelectedItems( )

int[ ] getSelectedIndexes( )

getSelectedItems( ) returns an array containing the names of the currently selected items.

getSelectedIndexes( ) returns an array containing the indexes of the currently selected items.

To obtain the number of items in the list, call getItemCount( ). You can set the currently

selected item by using the select( ) method with a zero-based integer index. Given an index, you can obtain the
name associated with the item at that index bycalling getItem( )

These methods

are shown here:

int getItemCount( );

void select(int index);

String getItem(int index);

Here, index specifies the index of the desired item


Java Programming 19

The below figure represents the appears of List

TextField

The TextField class implements a single-line text-entry area, usually called an edit control.Text fields allow the
user to enter strings and to edit the text using the arrow keys, cut and paste keys, and mouse selections.
TextField is a subclass of TextComponent.

TextField constructors:

 TextField( ) throws HeadlessException


 TextField(int numChars) throws HeadlessException
 TextField(String str) throws HeadlessException
 TextField(String str, int numChars) throws HeadlessException

The first version creates a default text field.

The second form creates a text field that is numChars characters wide.

The third form initializes the text field with the string contained in str.

The fourth form initializes a text field and sets its width.

TextField provides several methods that allow you to utilize a text field.
Java Programming 20

These methods are as follows:

String getText( )------ To obtain the string currently contained in the text field,

void setText(String str)------ To set the text Here, str is the new string.

String getSelectedText( )------ program can obtain the currently selected text

void select(int startIndex, int endIndex)------ The user can select a portion of the text in a text field. Also, you
can select a portion of text under program control. The select( ) method selects the charactersbeginning at
startIndex and ending at endIndex–1.

boolean isEditable( )------ returns true if the text may be changed and false if not

void setEditable(boolean canEdit)------= if canEdit is true, the text may be changed. If it is false, the text cannot
be altered.

The below figure represents the appears of Textfield


Java Programming 21

TextArea

Sometimes a single line of text input is not enough for a given task. To handle these situations,the AWT
includes a simple multiline editor called TextArea.

Constructorsn for TextArea:

 TextArea( ) throws HeadlessException


 TextArea(int numLines, int numChars) throws HeadlessException
 TextArea(String str) throws HeadlessException
 TextArea(String str, int numLines, int numChars) throws HeadlessException
 TextArea(String str, int numLines, int numChars, int sBars) throws HeadlessException

Here, numLines specifies the height, in lines, of the text area, and numChars specifies its width,

in characters. Initial text can be specified by str. In the fifth form, you can specify the scroll bars that you want
the control to have. sBars must be one of these values: SCROLLBARS_BOTH, SCROLLBARS_NONE,
SCROLLBARS_HORIZONTAL_ONLY, SCROLLBARS_VERTICAL_ONLY

TextArea adds the following methods:

void append(String str);------ appends the string specified by str to the end of the current text

void insert(String str, int index);------ inserts the string passed in str at the specified index

void replaceRange(String str, int startIndex, int endIndex);------ It replaces the characters from startIndex to
endIndex–1, with the replacement text passed in str
Java Programming 22

The below figure represents the appears of TextArea.

.5.1.5 Container
Abstract Windowing Toolkit (AWT): Abstract Windowing Toolkit (AWT) is used for GUI programming in
java.

AWT Container Hierarchy:


Java Programming 23

Container:

The Container is a component in AWT that can contain another components like buttons, textfields, labels etc.
The classes that extends Container class are known as container.

Window:

The window is the container that have no borders and menubars. You must use frame, dialog or another
window for creating a window.

Panel:

The Panel is the container that doesn't contain title bar and MenuBars. It can have other components like
button, textfield etc.

Frame:

The Frame is the container that contain title bar and can have MenuBars. It can have other components like
button, textfield etc.

There are two ways to create a frame:

1.By extending Frame class (inheritance)

2.By creating the object of Frame class (association)

Example program to create a frame by extending Frame class (inheritance)

import java.awt.*;
class First extends Frame
{
First()
{
Button b=new Button("click me");
b.setBounds(30,100,80,30);/*setting button position public void setBounds(int xaxis, int yaxis, int width, int
height); have been used in the above example that sets the position of the button.*/
add(b);//adding button into frame
Java Programming 24

setSize(300,300);//frame size 300 width and 300 height


setLayout(null);//no layout now bydefault BorderLayout
setVisible(true);//now frame willbe visible, bydefault not visible
}
public static void main(String args[])
{
First f=new First();
}
}
2.Example program to create a frame by creating the object of Frame class

import java.awt.*;
class First2{
First2(){
Frame f=new Frame();
Button b=new Button("click me");
b.setBounds(30,50,80,30);
f.add(b);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[]){
First2 f=new First2();
}
}
Java Programming 25

5.1.6 Layout Manager [2 marks-usage]

A container has a so‐called layout manager to arrange its components. The layout managers provide a level of
abstraction to map your user interface on all windowing systems, so that the layout can be
platform‐independent.

AWT provides the following layout managers ﴾in package java.awt﴿:

 Flow Layout

 Border Layout

 Grid Layout

 Card Layout

 Grid Bag Layout

Container's setLayout() method

A container has a setLayout() method to set its layout manager:

// java.awt.Container

public void setLayout(LayoutManager mgr)

To set up the layout of a Container (such as Frame, JFrame, Panel, or JPanel), you have to:

1. Construct an instance of the chosen layout object, via new and constructor, e.g., new FlowLayout())

2. Invoke the setLayout() method of the Container, with the layout object created as the argument;

3. Place the GUI components into the Container using the add() method in the correct order; or into the
correct zones.

For example,

// Allocate a Panel (container)

Panel pnl = new Panel();

// Allocate a new Layout object. The Panel container sets to this layout.

pnl.setLayout(new FlowLayout());

// The Panel container adds components in the proper order.

pnl.add(new JLabel("One"));
Java Programming 26

pnl.add(new JLabel("Two"));

pnl.add(new JLabel("Three"));

......

Container's getLayout() method

You can get the current layout via Container's getLayout() method.

Panel pnl = new Panel();

System.out.println(pnl.getLayout());

// java.awt.FlowLayout[hgap=5,vgap=5,align=center]

Panel's Initial Layout

Panel (and Swing's JPanel) provides a constructor to set its initial layout manager. It is because a primary
function of Panel is to layout a group of component in a particular layout.

public void Panel(LayoutManager layout)

// Construct a Panel in the given layout

Note: By default, Panel (and JPanel) has FlowLayout

// For example, create a Panel in BorderLayout

Panel pnl = new Panel(new BorderLayout());


Java Programming 27

FlowLayout:

In the java.awt.FlowLayout, components are arranged from left-to-right inside the container in the order that
they are added (via method aContainer.add(aComponent)). When one row is filled, a new row will be started.
The actual appearance depends on the width of the display window.

Constructors

public FlowLayout();

public FlowLayout(int alignment);

public FlowLayout(int alignment, int hgap, int vgap);

Note: alignment :

FlowLayout.LEFT (or LEADING), FlowLayout.RIGHT (or TRAILING), or FlowLayout.CENTER

hgap, vgap: horizontal/vertical gap between the components

Default value:

By default: hgap = 5, vgap = 5, alignment = FlowLayout.CENTER

Example

import java.awt.*;

import java.awt.event.*;

// An AWT GUI program inherits the top-level container java.awt.Frame

public class AWTFlowLayoutDemo extends Frame

private Button btn1, btn2, btn3, btn4, btn5, btn6;

// Constructor to setup GUI components and event handlers

public AWTFlowLayoutDemo ()

setLayout(new FlowLayout());

// "super" Frame sets layout to FlowLayout, which arranges the components


Java Programming 28

// from left-to-right, and flow from top-to-bottom.

btn1 = new Button("Button 1");

add(btn1);

btn2 = new Button("This is Button 2");

add(btn2);

btn3 = new Button("3");

add(btn3);

btn4 = new Button("Another Button 4");

add(btn4);

btn5 = new Button("Button 5");

add(btn5);

btn6 = new Button("One More Button 6");

add(btn6);

setTitle("FlowLayout Demo"); // "super" Frame sets title

setSize(280, 150); // "super" Frame sets initial size

setVisible(true); // "super" Frame shows

// The entry main() method

public static void main(String[] args)

new AWTFlowLayoutDemo(); // Let the constructor do the job

}
Java Programming 29

GridLayout
In java.awt.GridLayout, components are arranged in a grid (matrix) of rows and columns inside the Container.
Components are added in a left-to-right, top-to-bottom manner in the order they are added (via
method aContainer.add(aComponent)).

Constructors

 public GridLayout(int rows, int columns);

 public GridLayout(int rows, int columns, int hgap, int vgap);

// By default: rows = 1, cols = 0, hgap = 0, vgap = 0

Example

import java.awt.*;

import java.awt.event.*;

// An AWT GUI program inherits the top-level container java.awt.Frame

public class AWTGridLayoutDemo extends Frame

private Button btn1, btn2, btn3, btn4, btn5, btn6;

// Constructor to setup GUI components and event handlers

public AWTGridLayoutDemo () {

setLayout(new GridLayout(3, 2, 3, 3));

// "super" Frame sets layout to 3x2 GridLayout, horizontal and vertical gaps of 3 pixels

// The components are added from left-to-right, top-to-bottom


Java Programming 30

btn1 = new Button("Button 1");

add(btn1);

btn2 = new Button("This is Button 2");

add(btn2);

btn3 = new Button("3");

add(btn3);

btn4 = new Button("Another Button 4");

add(btn4);

btn5 = new Button("Button 5");

add(btn5);

btn6 = new Button("One More Button 6");

add(btn6);

setTitle("GridLayout Demo"); // "super" Frame sets title

setSize(280, 150); // "super" Frame sets initial size

setVisible(true); // "super" Frame shows

// The entry main() method

public static void main(String[] args)

new AWTGridLayoutDemo(); // Let the constructor do the job

}
Java Programming 31

BorderLayout
In java.awt.BorderLayout, the container is divided into 5 zones: EAST, WEST, SOUTH, NORTH,
and CENTER. Components are added using method aContainer.add(aComponent, zone), where zone is
either BorderLayout.NORTH (or PAGE_START), BorderLayout.SOUTH (or PAGE_END), BorderLayout.WE
ST (or LINE_START), BorderLayout.EAST (or LINE_END), or BorderLayout.CENTER.

You need not place components to all the 5 zones. The NORTH and SOUTH components may be stretched
horizontally; the EAST and WEST components may be stretched vertically; the CENTER component may
stretch both horizontally and vertically to fill any space left over.

Constructors

public BorderLayout();

public BorderLayout(int hgap, int vgap);

// By default hgap = 0, vgap = 0

Example

import java.awt.*;

import java.awt.event.*;

// An AWT GUI program inherits the top-level container java.awt.Frame

public class AWTBorderLayoutDemo extends Frame

private Button btnNorth, btnSouth, btnCenter, btnEast, btnWest;

// Constructor to setup GUI components and event handlers

public AWTBorderLayoutDemo ( )

setLayout(new BorderLayout(3, 3));

// "super" Frame sets layout to BorderLayout, horizontal and vertical gaps of 3 pixels

// The components are added to the specified zone

btnNorth = new Button("NORTH");

add(btnNorth, BorderLayout.NORTH);
Java Programming 32

btnSouth = new Button("SOUTH");

add(btnSouth, BorderLayout.SOUTH);

btnCenter = new Button("CENTER");

add(btnCenter, BorderLayout.CENTER);

btnEast = new Button("EAST");

add(btnEast, BorderLayout.EAST);

btnWest = new Button("WEST");

add(btnWest, BorderLayout.WEST);

setTitle("BorderLayout Demo"); // "super" Frame sets title

setSize(280, 150); // "super" Frame sets initial size

setVisible(true); // "super" Frame shows

// The entry main() method

public static void main(String[] args) {

new AWTBorderLayoutDemo(); // Let the constructor do the job

}
Java Programming 33

Question: differentiate between grid layout and border layout managers.[2 marks]
BorderLayout - Lays out components in BorderLayout.NORTH, EAST, SOUTH, WEST, and CENTER
sections.
bord = new BorderLayout(); Creates BorderLayout. Widgets
added with constraint to tell where.
bord = new BorderLayout(h, v); Creates BorderLayout with horizonal
and vertical gaps sizes in pixels.
p.add(widget, pos); Adds widget to one of the 5 border
layout regions, pos (see list above).
GridLayout - Lays out components in equal sized rectangular grid, added r-t-l, top-to-bottom.
grid = new GridLayout(r, c); Creates GridLayout with specified
rows and columns.
grid = new GridLayout(r,c,h,v); As above but also specifies
horizontal and vertical space
between cells.
p.add(widget); Adds widget to the next left-to-right,
top-to-bottom cell.

GridLayout

 Arranges components into rows and columns

 A GridLayout puts all the components in a rectangular grid and is divided into equal-sized rectangles and each
component is placed inside a rectangle

 A GridLayout is constructed with parameters

 When a component is added, it is placed in the next position in the grid, which is filled row by row, from the first
to last column

BorderLayout

 Arranges components into five areas: North, South, East, West, and Center

 The class BorderLayout arranges the components to fit in the five regions: east, west, north, south and center.
Each region is can contain only one component and each component in each region is identified by the
corresponding constant NORTH, SOUTH, EAST, WEST, and CENTER.

 A BorderLayout can be constructed with no parameters

 We can add a single component at each of the four compass directions (specified by the Strings "North", "South",
"East", or "West", as well as at the "Center". Of course, the component we add can be a container, which contains
multiple components (managed by another layout manager).
Java Programming 34

Java CardLayout

The CardLayout class manages the components in such a manner that only one component is visible at a time. It
treats each component as a card that is why it is known as CardLayout.

Constructors of CardLayout class


1. CardLayout(): creates a card layout with zero horizontal and vertical gap.
2. CardLayout(int hgap, int vgap): creates a card layout with the given horizontal and vertical gap.

Commonly used methods of CardLayout class


o public void next(Container parent): is used to flip to the next card of the given container.
o public void previous(Container parent): is used to flip to the previous card of the given container.
o public void first(Container parent): is used to flip to the first card of the given container.
o public void last(Container parent): is used to flip to the last card of the given container.
o public void show(Container parent, String name): is used to flip to the specified card with the given
name.

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

public class CardLayoutExample extends JFrame implements ActionListener{


CardLayout card;
JButton b1,b2,b3;
Container c;
CardLayoutExample(){

c=getContentPane();
card=new CardLayout(40,30);
//create CardLayout object with 40 hor space and 30 ver space
c.setLayout(card);

b1=new JButton("Apple");
b2=new JButton("Boy");
b3=new JButton("Cat");
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
Java Programming 35

c.add("a",b1);c.add("b",b2);c.add("c",b3);

}
public void actionPerformed(ActionEvent e) {
card.next(c);
}

public static void main(String[] args) {


CardLayoutExample cl=new CardLayoutExample();
cl.setSize(400,400);
cl.setVisible(true);
cl.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}

GridBagLayout
The Java GridBagLayout class is used to align components vertically, horizontally or along their baseline.The
components may not be of same size. Each GridBagLayout object maintains a dynamic, rectangular grid of
cells. Each component occupies one or more cells known as its display area. Each component associates an
instance of GridBagConstraints. With the help of constraints object we arrange component's display area on the
grid. The GridBagLayout manages each component's minimum and preferred sizes in order to determine
component's size.

Useful Methods
Modifier and Method Description
Type

void addLayoutComponent(Compone It adds specified component to the layout, using


nt comp, Object constraints) the specified constraints object.

void addLayoutComponent(String It has no effect, since this layout manager does not
name, Component comp) use a per-component string.

protected adjustForGravity(GridBagConstr It adjusts the x, y, width, and height fields to the


void aints constraints, Rectangle r) correct values depending on the constraint
geometry and pads.
Java Programming 36

protected AdjustForGravity(GridBagConst This method is for backwards compatibility only


void raints constraints, Rectangle r)

protected arrangeGrid(Container parent) Lays out the grid.


void

protected ArrangeGrid(Container parent) This method is obsolete and supplied for


void backwards compatibility

GridBagCon getConstraints(Component It is for getting the constraints for the specified


straints comp) component.

float getLayoutAlignmentX(Container It returns the alignment along the x axis.


parent)

Example program to demonstrate Java GridBagLayout

import java.awt.Button;

import java.awt.GridBagConstraints;

import java.awt.GridBagLayout;

import javax.swing.*;

public class GridBagLayoutExample extends JFrame{

public static void main(String[] args) {

GridBagLayoutExample a = new GridBagLayoutExample();

public GridBagLayoutExample() {

GridBagLayoutgrid = new GridBagLayout();

GridBagConstraints gbc = new GridBagConstraints();

setLayout(grid);

setTitle("GridBag Layout Example");

GridBagLayout layout = new GridBagLayout();


Java Programming 37

this.setLayout(layout);

gbc.fill = GridBagConstraints.HORIZONTAL;

gbc.gridx = 0;

gbc.gridy = 0;

this.add(new Button("Button One"), gbc);

gbc.gridx = 1;

gbc.gridy = 0;

this.add(new Button("Button two"), gbc);

gbc.fill = GridBagConstraints.HORIZONTAL;

gbc.ipady = 20;

gbc.gridx = 0;

gbc.gridy = 1;

this.add(new Button("Button Three"), gbc);

gbc.gridx = 1;

gbc.gridy = 1;

this.add(new Button("Button Four"), gbc);

gbc.gridx = 0;

gbc.gridy = 2;

gbc.fill = GridBagConstraints.HORIZONTAL;

gbc.gridwidth = 2;

this.add(new Button("Button Five"), gbc);

setSize(300, 300);
setPreferredSize(getSize());
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);

}
Java Programming 38

5.2 Event Handling

5.2.1 The Delegation event model

Java adopts the so-called "Event-Driven" (or "Event-Delegation") programming model for event-handling, similar to most of
the visual programming languages, such as Visual Basic.

In event-driven programming, a piece of event-handling codes is executed (or called back by the graphics subsystem) when an
event was fired in response to an user input (such as clicking a mouse button or hitting the ENTER key in a text field).
Call Back methods
In the above examples, the method actionPerformed() is known as a call back method. In other words, you never
invoke actionPerformed() in your codes explicitly. The actionPerformed() is called back by the graphics subsystem under certain
circumstances in response to certain user actions.
Source, Event and Listener Objects
The AWT's event-handling classes are kept in package java.awt.event.
Three kinds of objects are involved in the event-handling: a source, listener(s) and an event object.
The source object (such as Button and Textfield) interacts with the user. Upon triggered, the source object creates
an event object to capture the action (e.g., mouse-click x and y, texts entered, etc). This event object will be messaged to all
the registered listener object(s), and an appropriate event-handler method of the listener(s) is called-back to provide the
Java Programming 39

response. In other words, triggering a source fires an event to all its listener(s), and invoke an appropriate event handler of the
listener(s).
To express interest for a certain source's event, the listener(s) must be registered with the source. In other words, the listener(s)
"subscribes" to a source's event, and the source "publishes" the event to all its subscribers upon activation. This is known
as subscribe-publish or observable-observer design pattern.

The Delegation event model

The sequence of steps is illustrated above:

1. The source object registers its listener(s) for a certain type of event.

(A source fires an event when triggered. For example, clicking a Button fires an ActionEvent,
clicking a mouse button fires MouseEvent, typing a key fires KeyEvent, and etc.)

2. The source is triggered by a user.


Java Programming 40

3. The source create a XxxEvent object, which encapsulates the necessary information about the activation.
For example, the (x, y) position of the mouse pointer, the text entered, etc.

4. Finally, for each of the XxxEvent listeners in the listener list, the source invokes the appropriate handler
on the listener(s), which provides the programmed response

5.2.2 Events

Changing the state of an object is known as an Event. For example, click on button, dragging mouse etc.

The java.awt.event package provides many event classes and Listener interfaces for event handling.

It canbe generated as a consequence of a person interacting with the elements in a graphical user interface.
Some of the activities that cause events to be generated are pressing a button, entering a character via the
keyboard, selecting an item in a list, and clicking the mouse. Many other user operations could also be cited as
examples.Events may also occur that are not directly caused by interactions with a user interface.

For example, an event may be generated when a timer expires, a counter exceeds a value,a software or hardware
failure occurs, or an operation is completed. You are free to define events that are appropriate for your
application.

5.2.3 Event Sources

Asource is an object that generates an event. This occurs when the internal state of that object changes in some
way. Sources may generate more than one type of event. Asource must register listeners in order for the
listeners to receive notifications about a specific type of event. Each type of event has its own registration
method. Here is the general form:

public void addTypeListener(TypeListener el);

Here, Type is the name of the event, and el is a reference to the event listener. For example,the method that
registers a keyboard event listener is called addKeyListener( ). The methodthat registers a mouse motion
listener is called addMouseMotionListener( ). When an eventoccurs, all registered listeners are notified and
receive a copy of the event object. This is known as multicasting the event. In all cases, notifications are sent
only to listeners that register to receive them.

A source must also provide a method that allows a listener to unregister an interest in a specific type of event.
The general form of such a method is this:

public void removeTypeListener(TypeListener el);


Java Programming 41

Here, Type is the name of the event, and el is a reference to the event listener. For example,to remove a
keyboard listener, you would call removeKeyListener( ).The methods that add or remove listeners are provided
by the source that generates events. For example, the Component class provides methods to add and remove
keyboard and mouse event listeners.

5.2.4 Event Listerners

A listener is an object that is notified when an event occurs.

It has two major requirements.

 First, it must have been registered with one or more sources to receive notifications about
specific types of events.

 Second, it must implement methods to receive and process these notifications.

The methods that receive and process events are defined in a set of interfaces found in java.awt.event.

For example, the MouseMotionListener interface defines two methods to receive notifications when the mouse
is dragged or moved. Any object may receive and process one or both of these events if it provides an
implementation of this interface.

5.2.5 Event Classes

At the root of the Java event class hierarchy is EventObject, which is in java.util. It is the superclass for all
events. Its one constructor is shown here:

EventObject(Object src);

Here, src is the object that generates this event.

EventObject contains two methods: getSource( ) and toString( ).

General form is shown here:

Object getSource( ); ---- returns the source of the event

String toString( ); --- returns the string equivalent of the event.


Java Programming 42

List of Event Classes and Listener Interfaces

Event Classes Listener Interfaces


ActionEvent ActionListener
MouseEvent MouseListener and MouseMotionListener
MouseWheelEvent MouseWheelListener
KeyEvent KeyListener
ItemEvent ItemListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener
FocusEvent FocusListener

5.2.6 Handling Mouse and Keyboard Events

Steps to perform EventHandling

Following steps are required to perform event handling :

1. Implement the Listener interface and overrides its methods

2. Register the component with the Listener

For registering the component with the Listener, many classes provide the registration methods.

For example:

• Button

public void addActionListener(ActionListener a){}

• MenuItem

public void addActionListener(ActionListener a){}

• TextField

public void addActionListener(ActionListener a){}


Java Programming 43

public void addTextListener(TextListener a){}

• TextArea

public void addTextListener(TextListener a){}

• Checkbox

public void addItemListener(ItemListener a){}

• Choice

public void addItemListener(ItemListener a){}

• List

public void addActionListener(ActionListener a){}

public void addItemListener(ItemListener a){}

Mouse Event:

 A MouseEvent is fired when you press, release, or click (press followed by release) a mouse-button (left
or right button) at the source object; or position the mouse-pointer at (enter) and away (exit) from the
source object.

 A MouseEvent listener must implement either MouseListener interface or MouseMotionListener


interface or both dependending a action.

 The Java MouseListener is notified whenever you change the state of mouse

 The Java MouseMotionListener is notified whenever you move or drag mouse

Java MouseListener Interface

The Java MouseListener is notified whenever you change the state of mouse. It is notified against MouseEvent.
The MouseListener interface is found in java.awt.event package. It has five methods.

The signature of 5 methods found in MouseListener interface are given below:

1. public abstract void mouseClicked(MouseEvent e); // Called-back when the mouse-button has been
clicked on the source.

2. public abstract void mouseEntered(MouseEvent e); //Called-back when the mouse-pointer has
entered the source

3. public abstract void mouseExited(MouseEvent e); //Called-back when the mouse-pointer has exited
the source
Java Programming 44

4. public abstract void mousePressed(MouseEvent e); // Called-back when a mouse-button has been
pressed on the source

5. public abstract void mouseReleased(MouseEvent e); //Called-back when a mouse-button has been
released on the source

Note: A mouse-click invokes mousePressed(), mouseReleased() and mouseClicked().

Example on Java MouseListener:

import java.awt.*;

import java.awt.event.*;

public class MouseListenerExample extends Frame implements MouseListener{

Label l;

MouseListenerExample(){

addMouseListener(this);

l=new Label();

l.setBounds(20,50,100,20);

add(l);

setSize(300,300);

setLayout(null);

setVisible(true);

public void mouseClicked(MouseEvent e) {

l.setText("Mouse Clicked");

public void mouseEntered(MouseEvent e) {

l.setText("Mouse Entered");

public void mouseExited(MouseEvent e) {


Java Programming 45

l.setText("Mouse Exited");

public void mousePressed(MouseEvent e) {

l.setText("Mouse Pressed");

public void mouseReleased(MouseEvent e) {

l.setText("Mouse Released");

public static void main(String[] args) {

new MouseListenerExample();

Output:
Java Programming 46

Java MouseMotionListener Interface


The Java MouseMotionListener is notified whenever you move or drag mouse. It is notified against
MouseEvent. The MouseMotionListener interface is found in java.awt.event package. It has two methods.

Methods of MouseMotionListener interface


The signature of 2 methods found in MouseMotionListener interface are given below:

1. public abstract void mouseDragged(MouseEvent e);


2. public abstract void mouseMoved(MouseEvent e);

Example on Java MouseMotionListener ;

import java.awt.*;

import java.awt.event.*;

public class MouseMotionListenerExample extends Frame implements MouseMotionListener

MouseMotionListenerExample(){

addMouseMotionListener(this);

setSize(300,300);

setLayout(null);

setVisible(true);

public void mouseDragged(MouseEvent e) {

Graphics g=getGraphics();

g.setColor(Color.Green);

g.fillOval(e.getX(),e.getY(),20,20);

public void mouseMoved(MouseEvent e) {}

public static void main(String[] args) {


Java Programming 47

new MouseMotionListenerExample();

Output:

5.2.7 Adapter Classes


Java adapter classes provide the default implementation of listener interfaces. If you inherit the adapter class,
you will not be forced to provide the implementation of all the methods of listener interfaces. So it saves code.

The adapter classes are found in java.awt.event, java.awt.dnd and javax.swing.event packages. The Adapter
classes with their corresponding listener interfaces are given below

java.awt.event Adapter classes:

Adapter class Listener interface


WindowAdapter WindowListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
FocusAdapter FocusListener
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
HierarchyBoundsAdapter HierarchyBoundsListener
Java Programming 48

java.awt.dnd Adapter classes

Adapter class Listener interface


DragSourceAdapter DragSourceListener
DragTargetAdapter DragTargetListener

javax.swing.event Adapter classes:

Adapter class Listener interface


MouseInputAdapter MouseInputListener
InternalFrameAdapter InternalFrameListener

Example on Java KeyAdapter :

import java.awt.*;
import java.awt.event.*;
public class KeyAdapterExample extends KeyAdapter{
Label l;
TextArea area;
Frame f;
KeyAdapterExample(){
f=new Frame("Key Adapter");
l=new Label();
l.setBounds(20,50,200,20);
area=new TextArea();
area.setBounds(20,80,300, 300);
area.addKeyListener(this);
f.add(l);f.add(area);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public void keyReleased(KeyEvent e) {
String text=area.getText();
String words[]=text.split("\\s");
l.setText("Words: "+words.length+" Characters:"+text.length());
}

public static void main(String[] args) {


Java Programming 49

new KeyAdapterExample();
}
}
Output:

5.2.8 Inner Classes


A nested class (or commonly called inner class) is a class defined inside another class As an illustration, two
nested classes MyNestedClass1 and MyNestedClass2 are defined inside the definition of an outer class called
MyOuterClass.

public class MyOuterClass { // outer class defined here

......

private class MyNestedClass1 { ...... } // an nested class defined inside the outer class

public static class MyNestedClass2 { ...... } // an "static" nested class defined inside the outer class

......

Properties of nested class:

1. A nested class is a proper class. That is, it could contain constructors, member variables and member
methods. You can create an instance of a nested class via the new operator and constructor.

2. A nested class is a member of the outer class, just like any member variables and methods defined inside
a class.

3. Most importantly, a nested class can access the private members (variables/methods) of the enclosing
outer class, as it is at the same level as these private members. This is the property that makes inner class useful.
Java Programming 50

4. A nested class can have private, public, protected, or the default access, just like any member variables
and methods defined inside a class. A private inner class is only accessible by the enclosing outer class, and is
not accessible by any other classes. [An top-level outer class cannot be declared private, as no one can use a
private outer class.]

5. A nested class can also be declared static, final or abstract, just like any ordinary class.

6. A nested class is NOT a subclass of the outer class. That is, the nested class does not inherit the
variables and methods of the outer class. It is an ordinary self-contained class. [Nonetheless, you could declare
it as a subclass of the outer class, via keyword "extends OuterClassName", in the nested class's definition.]

The usages of nested class are:

1. To control visibilities (of the member variables and methods) between inner/outer class. The nested
class, being defined inside an outer class, can access private members of the outer class.

2. To place a piece of class definition codes closer to where it is going to be used, to make the program
clearer and easier to understand.

3. For namespace management.

Example program on inner classes

import java.awt.*;
import java.awt.event.*;
public class InnerClassDemo extends Frame {
private TextField tfCount;
private Button btnCount;
private int count = 0;

// Constructor to setup the GUI components and event handlers


public InnerClassDemo () {
setLayout(new FlowLayout()); // "super" Frame sets to FlowLayout
add(new Label("Counter")); // An anonymous instance of Label
tfCount = new TextField("0", 10);
tfCount.setEditable(false); // read-only
add(tfCount); // "super" Frame adds tfCount
btnCount = new Button("Count");
add(btnCount); // "super" Frame adds btnCount
// Construct an anonymous instance of BtnCountListener (a named inner class).
// btnCount adds this instance as a ActionListener.
btnCount.addActionListener(new BtnCountListener());
setTitle("AWT Counter");
setSize(250, 100);
Java Programming 51

setVisible(true);
}
// The entry main method
public static void main(String[] args) {
new InnerClassDem (); // Let the constructor do the job
}
/* BtnCountListener is a "named inner class" used as ActionListener. This inner class can access private
variables of the outer class. */
private class BtnCountListener implements ActionListener {

public void actionPerformed(ActionEvent evt) //Override actionperformed method of ActionListener


{
++count;
tfCount.setText(count + "");
}
}
}
Explaination of program:
• An inner class named BtnCountListener is used as the ActionListner.

• An anonymous instance of the BtnCountListener inner class is constructed. The btnCount source object
adds this instance as a listener, as follows:

btnCount.addActionListener(new BtnCountListener());

• The inner class can access the private variable tfCount and count of the outer class.

5.2.9 Anonymous Inner Classes


Instead of using a named inner class (called BtnCountListner in the previous example), we shall use an inner
class without a name, known as anonymous inner class as the ActionListener in this example

import java.awt.*;
import java.awt.event.*;

// An AWT GUI program inherits from the top-level container java.awt.Frame


public class AWTCounterAnonymousInnerClass extends Frame {
// This class is NOT a ActionListener, hence, it does not implement ActionListener interface

// The event-handler actionPerformed() needs to access these private variables


private TextField tfCount;
private Button btnCount;
private int count = 0;
Java Programming 52

// Constructor to setup the GUI components and event handlers


public AWTCounterAnonymousInnerClass () {
setLayout(new FlowLayout()); // "super" Frame sets to FlowLayout
add(new Label("Counter")); // An anonymous instance of Label
tfCount = new TextField("0", 10);
tfCount.setEditable(false); // read-only
add(tfCount); // "super" Frame adds tfCount

btnCount = new Button("Count");


add(btnCount); // "super" Frame adds btnCount

// Construct an anonymous instance of an anonymous class.


// btnCount adds this instance as a ActionListener.
btnCount.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent evt) {
++count;
tfCount.setText(count + "");
}
});

setTitle("AWT Counter");
setSize(250, 100);
setVisible(true);
}

// The entry main method


public static void main(String[] args) {
new AWTCounterAnonymousInnerClass(); // Let the constructor do the job
}
}
Applets
5.3 Swing Application and Applets

5.3.1 Applets and HTML

Java Applet

Applet is a special type of program that is embedded in the webpage to generate the dynamic content. It runs
inside the browser and works at client side.

Advantage of Applet

There are many advantages of applet. They are as follows:


Java Programming 53

 It works at client side so less response time.

 Secured

 It can be executed by browsers running under many plateforms, including Linux, Windows, Mac Os etc.

Drawback of Applet

 Plugin is required at client browser to execute applet.

Hierarchy of Applet

Lifecycle of Java Applet[ 2 marks]

1. Applet is initialized.

2. Applet is started.

3. Applet is painted.

4. Applet is stopped.

5. Applet is destroyed.
Java Programming 54

Lifecycle methods for Applet:

The java.applet.Applet class provides 4 life cycle methods and java.awt.Component class provides 1 life cycle
methods for an applet.

java.applet.Applet class

For creating any applet java.applet.Applet class must be inherited.

It provides 4 life cycle methods of applet.

 public void init(): is used to initialized the Applet. It is invoked only once.

 public void start(): is invoked after the init() method or browser is maximized. It is used to start the
Applet.

 public void stop(): is used to stop the Applet. It is invoked when Applet is stop or browser is minimized.

 public void destroy(): is used to destroy the Applet. It is invoked only once.

java.awt.Component class

The Component class provides 1 life cycle method of applet.

 public void paint(Graphics g): is used to paint the Applet. It provides Graphics class object that can be
used for drawing oval, rectangle, arc etc.

The HTML APPLET Tag


As mentioned earlier, Sun currently recommends that the APPLET tag be used to start an applet from both an
HTML document and from an applet viewer.

The syntax for a fuller form of the APPLET tag is shown here. Bracketed items are optional.

< APPLET

[CODEBASE = codebaseURL]

CODE = appletFile

[ALT = alternateText]

[NAME = appletInstanceName]

WIDTH = pixels HEIGHT = pixels


Java Programming 55

[ALIGN = alignment]

[VSPACE = pixels] [HSPACE = pixels]

>

[< PARAM NAME = AttributeName VALUE = AttributeValue>]

[< PARAM NAME = AttributeName2 VALUE = AttributeValue>]

...

[HTML Displayed in the absence of Java]

</APPLET>

Let’s take a look at each part now.

CODEBASE :

CODEBASE is an optional attribute that specifies the base URL of the applet code, which is the
directory that will be searched for the applet’s executable class file (specified by the CODE tag). The HTML
document’s URL directory is used as the CODEBASE if this attribute is not specified. The CODEBASE does
not have to be on the host from which the HTML document was read.

CODE :

It is a required attribute that gives the name of the file containing your applet’s compiled .class file. This file is
relative to the code base URL of the applet, which is the directory that the HTML file was in or the directory
indicated by CODEBASE if set.

ALT :

The ALT tag is an optional attribute used to specify a short text message that should be displayed if the browser
recognizes the APPLET tag but can’t currently run Java applets. This is distinct from the alternate HTML you
provide for browsers that don’t support applets.

NAME :NAME is an optional attribute used to specify a name for the applet instance.Applets must be named in
order for other applets on the same page to find them by name and communicate with them. To obtain an applet
by name, use getApplet( ), which is defined by the AppletContext interface.

WIDTH and HEIGHT :

WIDTH and HEIGHT are required attributes that give the size (in pixels) of the applet display area.

ALIGN:

ALIGN is an optional attribute that specifies the alignment of the applet. The possible values: LEFT, RIGHT,

TOP, BOTTOM, MIDDLE, BASELINE, TEXTTOP, ABSMIDDLE, and ABSBOTTOM.


Java Programming 56

VSPACE and HSPACE :

These attributes are optional. VSPACE specifies the space, in pixels,bove and below the applet. HSPACE
specifies the space, in pixels, on each side of the applet.

PARAM NAME and VALUE :

The PARAM tag allows you to specify applet-specific arguments in an HTML page. Applets access their
attributes with the getParameter( ) method.

Other valid APPLET attributes include ARCHIVE, which lets you specify one or more archive files, and
OBJECT, which specifies a saved version of the applet.

Note:

APPLET tag should include only a CODE or an OBJECT attribute, but not both.

Question: Why do applet classes need to be declared as public? [ 2 marks]

Applet classes need to be declared as a public becomes the applet classes are access from HTML document
that means from outside code. Otherwise, an applet will not be accessible from an outside code i.e an HTML

Running an Applet

There are two ways to run an applet

1. By html file.

2. By appletViewer tool (for testing purpose).

1.Running an applet by html file :

To execute the applet by html file, create an applet and compile it. After that create an html file and place the
applet code in html file. Now click the html file.

//First.java

import java.applet.Applet;

import java.awt.Graphics;

public class First extends Applet{

public void paint(Graphics g){

g.drawString("welcome",150,150);

}
Java Programming 57

Note: class must be public because its object is created by Java Plugin software that resides on the browser.

myapplet.html

<html>

<body>

<applet code="First.class" width="300" height="300">

</applet>

</body>

</html>

2:Running Applet by appletviewer tool:

To execute the applet by appletviewer tool, create an applet that contains applet tag in comment and compile it.
After that run it by: appletviewer Filename.java. Now Html file is not required but it is for testing purpose only.

Example:

//First.java

import java.applet.Applet;

import java.awt.Graphics;

public class First extends Applet

public void paint(Graphics g)

g.drawString("welcome to applet",150,150);

To execute the applet by appletviewer tool, write in command prompt:

c:\>javac First.java

c:\>appletviewer First.java
Java Programming 58

EventHandling in Applet

As we perform event handling in AWT or Swing, we can perform it in applet also. Let's see the simple example
of event handling in applet that prints a message by click on the button.

Example of EventHandling in applet:

import java.applet.*;

import java.awt.*;

import java.awt.event.*;

public class EventApplet extends Applet implements ActionListener

Button b; TextField tf;

public void init()

tf=new TextField();

tf.setBounds(30,40,150,20);

b=new Button("Click");

b.setBounds(80,150,60,50);

add(b);

add(tf);

b.addActionListener(this);

setLayout(null);

public void actionPerformed(ActionEvent e)

tf.setText("Welcome");

}
Java Programming 59

In the above example, we have created all the controls in init() method because it is invoked only once.

myapplet.html

<html>

<body>

<applet code="EventApplet.class" width="300" height="300">

</applet>

</body>

</html>

5.3.2 Security Issues


As you are likely aware, every time you download a “normal” program, you are taking a risk, because
the code you are downloading might contain a virus, Trojan horse, or other harmful code. At the core of the
problem is the fact that malicious code can cause its damage because it has gained unauthorized access to
system resources. For example, a virus program might gather private information, such as credit card numbers,
bank account balances, and passwords, by searching the contents of your computer’s local file system.

In order for Java to enable applets to be downloaded and executed on the client computer safely, it was

necessary to prevent an applet from launching such an attack.Java achieved this protection by confining an
applet to the Java execution environmentand not allowing it access to other parts of the computer. The ability to
download applets with confidence that no harm will be done and that no security will be breached is considered
by many to be the single most innovative aspect of Java

5.3.3 Applets and Applications

Advantages of Applets:

1. Execution of applets is easy in a Web browser and does not require any installation or deployment
procedure in realtime programming (where as servlets require).

2. Writing and displaying (just opening in a browser) graphics and animations is easier than applications.

3. In GUI development, constructor, size of frame, window closing code etc. are not required (but are
required in applications).

Restrictions of Applets:

1. Applets are required separate compilation before opening in a browser.


Java Programming 60

2. In realtime environment, the bytecode of applet is to be downloaded from the server to the client
machine.

3. Applets are treated as untrusted (as they were developed by unknown people and placed on unknown
servers whose trustworthiness is not guaranteed) and for this reason they are not allowed, as a security measure,
to access any system resources like file system etc. available on the client system.

4. Extra Code is required to communicate between applets using AppletContext

Differences between applications and applets-[3 marks]

FEATURE APPLET APPLICATION

main() method Not Present present

Called as stand-alone application as


Nature Requires some third party tool help like a application can be executed from
browser to execute command prompt

cannot access any thing on the system except Can access any data or software
Restrictions browser’s services available on the system

Requires highest security for the system as


Security they are untrusted Does not require any security

Applet is portable and can be executed by any Need JDK, JRE, JVM installed on client
Execution JAVA supported browser machine

Applications are created by writing


Applets are created by extending the public static void main(String[] s)
Creation java.applet.Applet method

Applet application has 5 methods which will


be automatically invoked on occurance of Application has a single start point
Methods specific event which is main method

Example: Example:
Example
Java Programming 61

import java.awt.*; public class MyClass

import java.applet.*; {

public static void main(String args[]) {}

public class Myclass extends Applet }

public void init() { }

public void start() { }

public void stop() {}

public void destroy() {}

public void paint(Graphics g) {}

5.3.4 Passing Parameters to Applets

We can get any information from the HTML file as a parameter. For this purpose, Applet class provides a
method named getParameter().

Syntax:

public String getParameter(String parameterName);

Example on Passing Parameters to Applets

import java.applet.Applet;

import java.awt.Graphics;

public class UseParam extends Applet

public void paint(Graphics g)


Java Programming 62

String str=getParameter("msg");

g.drawString(str,50, 50);

myapplet.html

<html>

<body>

<applet code="UseParam.class" width="300" height="300">

<param name="msg" value="Welcome to applet">

</applet>

</body>

</html>

5.3.5 Creating a Swing Applet

We can even create applets based on the Swing package. In order to create such applets, we must extend
JApplet class of the swing package. JApplet extends Applet class, hence all the features of Applet class are
available in JApplet as well, including JApplet's own Swing based features. Swing applets provides an easier to
use user interface than AWT applets.

Some important points :

 When we creat an AWT applet, we implement the paint(Graphics g) method to draw in it but when we
create a Swing applet, we implement paintComponent(Graphics g) method to draw in it.

 For an applet class that extends Swing's JApplet class, the way elements like textfield, buttons,
checksboxes etc are added to this applet is performed by using a default layout manager, i.e.
BorderLayout.

Swing applets use the same four lifecycle methods: init( ),start( ), stop( ), and destroy( ). Of course, you need
override only those methods that are needed by your applet. Painting is accomplished differently in Swing than
it is in the AWT,and a Swing applet will not normally override the paint( ) method.
Java Programming 63

Example on Creating a swing applet

In this example , first, we have created a swing applet by extending JApplet class and we have added a JPanel to
it.Next, we have created a class B, which has extended JPanel class of Swing package and have also
implemented ActionListener interace to listen to the button click event generated when buttons added to JPanel
are clicked.

import java.awt.*;
import java.applet.*;
import java.awt.event.*;
import javax.swing.*;
/*
<applet code="SwingAppletDemo" width="500" height="200">
</applet>
*/
public class SwingAppletDemo extends JApplet
{
public void init()
{
add(new B()); //Adding a JPanel to this Swing applet
}
}

class B extends JPanel implements ActionListener


{
JLabel jb;
JButton box1;
String str;

B( )
{
jb= new JLabel("Welcome, please click on button to unbox some interesting knowledge -");
box1 = new JButton("Box1");
str ="";
setLayout(new FlowLayout());
add(jb);
add(box1);
box1.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
Java Programming 64

if(ae.getActionCommand().equals("box1"))
{
str=" welcome to SwingApplet programming";
repaint();
}
}

public void paintComponent(Graphics g)


{
super.paintComponent(g);
g.drawString(str, 2, 170);
}
}

5.3.6 Painting in Swing


Painting is accomplished differently in Swing than it is in the AWT,and a Swing applet will not normally
override the paint( ) method.when we create a Swing applet, we implement paintComponent(Graphics g)
method to draw in it.

Syntax:

protected void paintComponent(Graphics g)

The parameter g is the graphics context to which output is written.

To cause a component to be painted under program control, call repaint( ). It works in Swing just as it does for
the AWT. The repaint( ) method is defined by Component. Calling it causes the system to call paint( ) as soon
Java Programming 65

as it is possible to do so. In Swing the call to paint( ) results in a call to paintComponent( ). Inside the
overridden paintComponent( ), you will draw the stored output

Note: For example refer to the program on Creating a Swing Applet

5.3.7 Exploring Swing Controls- JLabel , Image Icon and JText Field

Hierarchy for swing components. [3marks]

the hierarchy of java swing API is given below.

Hierarchy of swing components


Java Programming 66

Exploring Swing Controls

 JLable , Image Icon and JTextField

JLabels

A JLabel is a very simple component which contains a string.

The constructors are

 public JLabel() // creates label with no text

 public JLabel(String text) //create label with text

The methods available are

 public String getText() // return label text

 public void setText(String s) // sets the label text

Image Icon

The class ImageIcon is an implementation of the Icon interface that paints Icons from Images.

The constructors are

 ImageIcon() // Creates an uninitialized image icon.

 ImageIcon(Image image)// Creates an ImageIcon from an image object.

 ImageIcon(Image image, String description)// Creates an ImageIcon from the image.

 ImageIcon(String filename, String description)// Creates an ImageIcon from the specified


file.

 ImageIcon(URL location)// Creates an ImageIcon from the specified URL.

The methods available are

 String getDescription() // Gets the description of the image

 Image getImage()//Returns this icon's Image.

 void paintIcon(Component c, Graphics g, int x, int y)// Paints the icon.

 void setDescription(String description)// Sets the description of the image.

 void setImage(Image image)// Sets the image displayed by this icon.

 String toString()//Returns a string representation of this image .


Java Programming 67

JTextField

A JTextField is an area that the user can type one line of text into. It is a good way of getting text

input from the user.

The constructors are :

 public JTextField () // creates text field with no text

 public JTextField (int columns) // create text field with appropriate # of columns

 public JTextField (String s) // create text field with s displayed

 public JTextField (String s, int columns) // create text field with s displayed & approp.
width

Methods include:

 public void setEditable(boolean s) // if false the TextField is not user editable

 public String getText() // return label text

 public void setText(String s) // sets the label text

.5.3.8 Swing Buttons


Java Swing is a part of Java Foundation Classes (JFC) that is used to create window-based applications. It is
built on the top of AWT (Abstract Windowing Toolkit) API and entirely written in java.
Unlike AWT, Java Swing provides platform-independent and lightweight components.
The javax.swing package provides classes for java swing API such
JButton
JToggle Button
JCheckBox
JRadio Button
JTabbed Pane
JScroll Pane
JList
JComboBox
Swing Menus
Dialogs
Java Programming 68

JButton
The JButton class is used to create a labeled button that has platform independent implementation. The
application result in some action when the button is pushed. It inherits AbstractButton class.

JButton class declaration

Let's see the declaration for javax.swing.JButton class.

1. public class JButton extends AbstractButton implements Accessible

Commonly used Constructors

Constructor Description

JButton() It creates a button with no text and icon.

JButton(String s) It creates a button with the specified text.

It creates a button with the specified icon


JButton(Icon i)
object.

Commonly used Methods of AbstractButton class:

Methods Description

void setText(String s) It is used to set specified text on button

String getText() It is used to return the text of the button.

void setEnabled(boolean b) It is used to enable or disable the button.

void setIcon(Icon b) It is used to set the specified Icon on the button.

Icon getIcon() It is used to get the Icon of the button.

void setMnemonic(int a) It is used to set the mnemonic on the button.

void addActionListener(ActionListener a) It is used to add the action listener to this object.


Java Programming 69

Java JButton Example

import javax.swing.*;
public class ButtonExample {
public static void main(String[] args) {
JFrame f=new JFrame("Button Example");
JButton b=new JButton("Click Here");
b.setBounds(50,100,95,30);
f.add(b);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}

Output:

Question:
subclasses of JButton class.[2 marks]
Subclasses:
1.BasicArrowButton,
2.MetalComboBoxButton

1.BasicArrowButton:

public class BasicArrowButton extends JButton implements SwingConstants MetalComboBoxButton

Constructors:
BasicArrowButton(int direction); --Creates a BasicArrowButton whose arrow is drawn in the specified
direction.
Java Programming 70

BasicArrowButton(int direction, Color background, Color shadow, Color darkShadow, Color highlight)--
Creates a BasicArrowButton whose arrow is drawn in the specified direction and with the specified
colors.

2.MetalComboBoxButton
Constructors :
MetalComboBoxButton(JComboBox cb, Icon i, boolean onlyIcon, CellRendererPane pane, JList list)

MetalComboBoxButton(JComboBox cb, Icon i, CellRendererPane pane, JList list)

JToggle Button

Auseful variation on the push button is called a toggle button. A toggle button looks just like a push

button, but it acts differently because it has two states: pushed and released. That is, when you press

a toggle button, it stays pressed rather than popping back up as a regular push button does. When you

press the toggle button a second time, it releases (pops up). Therefore, each time a toggle button is

pushed, it toggles between its two states

JToggleButton constructors:

JToggleButton(String str)

This creates a toggle button that contains the text passed in str. By default, the button is in the off position.
Other constructors enable you to create toggle buttons that contain images,or images and text.

To handle item events, you must implement the ItemListener interface.Each time an item event is generated, it
is passed to the itemStateChanged( )method defined by ItemListener. Inside itemStateChanged( ), the getItem(
) method canbe called on the ItemEvent object to obtain a reference to the JToggleButton instance
thatgenerated the event. It is shown here:

Object getItem( )

A reference to the button is returned. You will need to cast this reference to JToggleButton.The easiest way to
determine a toggle button’s state is by calling the isSelected( ) method(inherited from AbstractButton) on the
button that generated the event. It is shown here:

boolean isSelected( )

It returns true if the button is selected and false otherwise


Java Programming 71

Example program to demonstrate JToggleButton

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
<applet code="JToggleButtonDemo" width=200 height=80>
</applet>
*/
public class JToggleButtonDemo extends JApplet {
JLabel jlab;
JToggleButton jtbn;
public void init() {
try {
SwingUtilities.invokeAndWait(
new Runnable() {
public void run() {
makeGUI();
}
}
);
} catch (Exception exc) {
System.out.println("Can't create because of " + exc);
}
}
private void makeGUI() {
// Change to flow layout.
setLayout(new FlowLayout());
// Create a label.
jlab = new JLabel("Button is off.");
// Make a toggle button.
jtbn = new JToggleButton("On/Off");
// Add an item listener for the toggle button.
jtbn.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent ie) {
if(jtbn.isSelected())
jlab.setText("Button is on.");
else
jlab.setText("Button is off.");
}
});
// Add the toggle button and label to the content pane.
add(jtbn);
Java Programming 72

add(jlab);
}
}
The output from the toggle button example is shown here:

JCheck Box
The JCheckBox class is used to create a checkbox. It is used to turn an option on (true) or off (false). Clicking
on a CheckBox changes its state from "on" to "off" or from "off" to "on ".It inherits JToggleButton class.

JCheckBox class declaration

Let's see the declaration for javax.swing.JCheckBox class.

public class JCheckBox extends JToggleButton implements Accessible

Commonly used Constructors:

Constructor Description

JJCheckBox() Creates an initially unselected check box button with no text, no icon.

JChechBox(String s) Creates an initially unselected check box with text.

JCheckBox(String text, boolean Creates a check box with text and specifies whether or not it is initially
selected) selected.

JCheckBox(Action a) Creates a check box where properties are taken from the Action supplied.

Commonly used Methods:

Methods Description

AccessibleContext getAccessibleContext() It is used to get the AccessibleContext associated with this JCheckBox.

protected String paramString() It returns a string representation of this JCheckBox.


Java Programming 73

Example program to demonstrate JCheckBox

import javax.swing.*;
public class CheckBoxExample
{
CheckBoxExample(){
JFrame f= new JFrame("CheckBox Example");
JCheckBox checkBox1 = new JCheckBox("C++");
checkBox1.setBounds(100,100, 50,50);
JCheckBox checkBox2 = new JCheckBox("Java", true);
checkBox2.setBounds(100,150, 50,50);
f.add(checkBox1);
f.add(checkBox2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new CheckBoxExample();
}
}
Output:
Java Programming 74

JRadio Button

The JRadioButton class is used to create a radio button. It is used to choose one option from multiple options.
It is widely used in exam systems or quiz.

It should be added in ButtonGroup to select one radio button only.

JRadioButton class declaration

public class JRadioButton extends JToggleButton implements Accessible

Commonly used Constructors:

Constructor Description

JRadioButton() Creates an unselected radio button with no text.

JRadioButton(String s) Creates an unselected radio button with specified text.

JRadioButton(String s, boolean selected) Creates a radio button with the specified text and selected status.

Commonly used Methods:

Methods Description

void setText(String s) It is used to set specified text on button.

String getText() It is used to return the text of the button.

void setEnabled(boolean b) It is used to enable or disable the button.

void setIcon(Icon b) It is used to set the specified Icon on the button.

Icon getIcon() It is used to get the Icon of the button.

void setMnemonic(int a) It is used to set the mnemonic on the button.

void addActionListener(ActionListener a) It is used to add the action listener to this object.


Java Programming 75

Example program to demonstrate JRadioButton

import javax.swing.*;
public class RadioButtonExample
{
JFrame f;
RadioButtonExample(){
f=new JFrame();
JRadioButton r1=new JRadioButton("A) Male");
JRadioButton r2=new JRadioButton("B) Female");
r1.setBounds(75,50,100,30);
r2.setBounds(75,100,100,30);
ButtonGroup bg=new ButtonGroup();
bg.add(r1);bg.add(r2);
f.add(r1);f.add(r2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String[] args) {
new RadioButtonExample();
}
}
Output:
Java Programming 76

JTabbed Pane
JTabbedPane encapsulates a tabbed pane. It manages a set of components by linking them with tabs. Selecting a
tab causes the component associated with that tab to come to the forefront.

JTabbedPane defines three constructors. We will use its default constructor, whichcreates an empty control with
the tabs positioned across the top of the pane. The other two constructors let you specify the location of the tabs,
which can be along any of the foursides. JTabbedPane uses the SingleSelectionModel model.Tabs are added by
calling addTab( ). Here is one of its forms:

void addTab(String name, Component comp)

Here, name is the name for the tab, and comp is the component that should be added to the tab. Often, the
component added to a tab is a JPanel that contains a group of related components. This technique allows a tab to
hold a set of components

The general procedure to use a tabbed pane is outlined here:

1. Create an instance of JTabbedPane.

2. Add each tab by calling addTab( ).

3. Add the tabbed pane to the content pane.

Example to illustrates a Tabbed Pane.

In this exampleThe first tab is titled “Cities” andcontains four buttons. Each button displays the name of a city.
The second tab is titled“Colors” and contains three check boxes. Each check box displays the name of a color.
The third tab is titled “Flavors” and contains one combo box. This enables the user to select oneof three flavors.
// Demonstrate JTabbedPane.
import javax.swing.*;
/*
<applet code="JTabbedPaneDemo" width=400 height=100>
</applet>
*/
public class JTabbedPaneDemo extends JApplet {
public void init() {
try {
SwingUtilities.invokeAndWait(
new Runnable() {
public void run() {
Java Programming 77

makeGUI();
}
}
);
} catch (Exception exc) {
System.out.println("Can't create because of " + exc);
}
}
private void makeGUI() {
JTabbedPane jtp = new JTabbedPane();
jtp.addTab("Cities", new CitiesPanel());
jtp.addTab("Colors", new ColorsPanel());
jtp.addTab("Flavors", new FlavorsPanel());
add(jtp);
}
}
// Make the panels that will be added to the tabbed pane.
class CitiesPanel extends JPanel {
public CitiesPanel() {
JButton b1 = new JButton("New York");
add(b1);
JButton b2 = new JButton("London");
add(b2);
JButton b3 = new JButton("Hong Kong");
add(b3);
JButton b4 = new JButton("Tokyo");
add(b4);
}
}
class ColorsPanel extends JPanel {
public ColorsPanel() {
JCheckBox cb1 = new JCheckBox("Red");
add(cb1);
JCheckBox cb2 = new JCheckBox("Green");
add(cb2);
JCheckBox cb3 = new JCheckBox("Blue");
add(cb3);
}
}
class FlavorsPanel extends JPanel {
public FlavorsPanel() {
JComboBox jcb = new JComboBox();
jcb.addItem("Vanilla");
Java Programming 78

jcb.addItem("Chocolate");
jcb.addItem("Strawberry");
add(jcb);
}
}
Output:
Java Programming 79

JScroll Pane

JScrollPane is a lightweight container that automatically handles the scrolling of another component. The
component being scrolled can either be an individual component, such as a table, or a group of components
contained within another lightweight container, such as a JPanel

JScrollPane defines several constructors. The one used in this chapter is shown here:

JScrollPane(Component comp)

The component to be scrolled is specified by comp. Scroll bars are automatically displayed when the content of
the pane exceeds the dimensions of the viewport.

Here are the steps to follow to use a scroll pane:


1. Create the component to be scrolled.
2. Create an instance of JScrollPane, passing to it the object to scroll.
3. Add the scroll pane to the content pane.

Example program to illustrates JScroll Pane

First, a JPanel object is created, and 400 buttons are added to it, arranged into 20 columns. This panel is then
added to a scroll pane,and the scroll pane is added to the content pane. Because the panel is larger than the
viewport, vertical and horizontal scroll bars appear automatically. You can use the scroll bars to scroll the
buttons into view.
// Demonstrate JScrollPane.
import java.awt.*;
import javax.swing.*;
/*
<applet code="JScrollPaneDemo" width=300 height=250>
</applet>
*/
public class JScrollPaneDemo extends JApplet {
public void init() {
try {
SwingUtilities.invokeAndWait(
new Runnable() {
public void run() {
makeGUI();
Java Programming 80

}
}
);
} catch (Exception exc) {
System.out.println("Can't create because of " + exc);
}
}
private void makeGUI() {
// Add 400 buttons to a panel.
JPanel jp = new JPanel();
jp.setLayout(new GridLayout(20, 20));
int b = 0;
for(int i = 0; i < 20; i++) {
for(int j = 0; j < 20; j++) {
jp.add(new JButton("Button " + b));
++b;
}
}
// Create the scroll pane.
JScrollPane jsp = new JScrollPane(jp);
// Add the scroll pane to the content pane.
// Because the default border layout is used,
// the scroll pane will be added to the center.
add(jsp, BorderLayout.CENTER);
}
}
Output:
Java Programming 81

JList
The object of JList class represents a list of text items. The list of text items can be set up so that the user can
choose either one item or multiple items. It inherits JComponent class.

JList class declaration

Let's see the declaration for javax.swing.JList class.

public class JList extends JComponent implements Scrollable, Accessible

Commonly used Constructors:

Constructor Description

JList() Creates a JList with an empty, read-only, model.

JList(ary[] listData) Creates a JList that displays the elements in the specified array.

JList(ListModel<ary> dataModel) Creates a JList that displays elements from the specified, non-null, model.

Commonly used Methods:

Methods Description

Void addListSelectionListener(ListSelectionListener It is used to add a listener to the list, to be notified each time a
listener) change to the selection occurs.

int getSelectedIndex() It is used to return the smallest selected cell index.

It is used to return the data model that holds a list of items


ListModel getModel()
displayed by the JList component.

It is used to create a read-only ListModel from an array of


void setListData(Object[] listData)
objects.

Example program to illustrates JList

import javax.swing.*;
public class ListExample
{
ListExample(){
JFrame f= new JFrame();
DefaultListModel<String> l1 = new DefaultListModel<>();
l1.addElement("Item1");
Java Programming 82

l1.addElement("Item2");
l1.addElement("Item3");
l1.addElement("Item4");
JList<String> list = new JList<>(l1);
list.setBounds(100,100, 75,75);
f.add(list);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new ListExample();
}}

Output:
Java Programming 83

JCombo Box

Swing provides a combo box (a combination of a text field and a drop-down list) through the JComboBox
class. A combo box normally displays one entry, but it will also display a drop-down list that allows a user to
select a different entry.

The JComboBox constructor used by the example is shown here:

JComboBox(Object[ ] items)

Here, items is an array that initializes the combo box. Other constructors are available.JComboBox uses the
ComboBoxModel. Mutable combo boxes (those whose entries canbe changed) use the
MutableComboBoxModel.

In addition to passing an array of items to be displayed in the drop-down list, items canbe dynamically added
to the list of choices via the addItem( ) method, shown here:

void addItem(Object obj)

Here, obj is the object to be added to the combo box. This method must be used only withmutable combo
boxes.

One way to obtain the item selected in the list is to call getSelectedItem( ) on the combobox. It is shown here:

Object getSelectedItem( )

You will need to cast the returned value into the type of object stored in the list.

Example program to demonstrates the ComboBox

The following example demonstrates the combo box. The combo box contains entries for “France,”
“Germany,” “Italy,” and “Japan.” When a country is selected, an icon-based label is updated to display the flag
for that country. You can see how little code is required to use this powerful component.

// Demonstrate JComboBox.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
<applet code="JComboBoxDemo" width=300 height=100>
Java Programming 84

</applet>
*/
public class JComboBoxDemo extends JApplet {
JLabel jlab;
ImageIcon france, germany, italy, japan;
JComboBox jcb;
String flags[] = { "France", "Germany", "Italy", "Japan" };
public void init() {
try {
SwingUtilities.invokeAndWait(
new Runnable() {
public void run() {
makeGUI();
}
}
);
} catch (Exception exc) {
System.out.println("Can't create because of " + exc);
}
}
private void makeGUI() {
// Change to flow layout.
setLayout(new FlowLayout());
// Instantiate a combo box and add it to the content pane.
jcb = new JComboBox(flags);
add(jcb);
// Handle selections.
jcb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
String s = (String) jcb.getSelectedItem();
jlab.setIcon(new ImageIcon(s + ".gif"));
}
});
// Create a label and add it to the content pane.
jlab = new JLabel(new ImageIcon("france.gif"));
add(jlab);
}
}
Java Programming 85

Output:

Swing Menus [2 marks]


JMenuBar, JMenu and JMenuItem

The JMenuBar class is used to display menubar on the window or frame. It may have several menus.
The object of JMenu class is a pull down menu component which is displayed from the menu bar. It inherits the
JMenuItem class.
The object of JMenuItem class adds a simple labeled menu item. The items used in a menu must belong to the
JMenuItem or any of its subclass.

JMenuBar class declaration


public class JMenuBar extends JComponent implements MenuElement, Accessible
JMenu class declaration
public class JMenu extends JMenuItem implements MenuElement, Accessible
JMenuItem class declaration
public class JMenuItem extends AbstractButton implements Accessible, MenuElement
Java Programming 86

Example program to demonstrate SWING Menu


import javax.swing.*;
class MenuExample
{
JMenu menu, submenu;
JMenuItem i1, i2, i3, i4, i5;
MenuExample(){
JFrame f= new JFrame("Menu and MenuItem Example");
JMenuBar mb=new JMenuBar();
menu=new JMenu("Menu");
submenu=new JMenu("Sub Menu");
i1=new JMenuItem("Item 1");
i2=new JMenuItem("Item 2");
i3=new JMenuItem("Item 3");
i4=new JMenuItem("Item 4");
i5=new JMenuItem("Item 5");
menu.add(i1); menu.add(i2); menu.add(i3);
submenu.add(i4); submenu.add(i5);
menu.add(submenu);
mb.add(menu);
f.setJMenuBar(mb);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new MenuExample();
}}
Output:
Java Programming 87

Dialogs

The JOptionPane class is used to provide standard dialog boxes such as message dialog box, confirm dialog box and input
dialog box. These dialog boxes are used to display information or get input from the user. The JOptionPane class inherits
JComponent class.

JOptionPane class declaration

public class JOptionPane extends JComponent implements Accessible

Common Constructors of JOptionPane class

Constructor Description

JOptionPane() It is used to create a JOptionPane with a test message.

JOptionPane(Object message) It is used to create an instance of JOptionPane to display a message.

JOptionPane(Object message, int It is used to create an instance of JOptionPane to display a message with specified
messageType message type and default options.

Common Methods of JOptionPane class

Methods Description

It is used to create and return a new parentless JDialog


JDialog createDialog(String title)
with the specified title.

static void showMessageDialog(Component parentComponent, It is used to create an information-message dialog titled


Object message) "Message".

static void showMessageDialog(Component parentComponent, It is used to create a message dialog with given title
Object message, String title, int messageType) and messageType.

static int showConfirmDialog(Component parentComponent, It is used to create a dialog with the options Yes, No
Object message) and Cancel; with the title, Select an Option.

static String showInputDialog(Component parentComponent, It is used to show a question-message dialog requesting


Object message) input from the user parented to parentComponent.

It is used to set the input value that was selected or


void setInputValue(Object newValue)
input by the user.
Java Programming 88

Example program to demonstrate showMessageDialog()

import javax.swing.*;

public class OptionPaneExample {

JFrame f;

OptionPaneExample(){

f=new JFrame();

JOptionPane.showMessageDialog(f,"Hello, Welcome to Java.");

public static void main(String[] args) {

new OptionPaneExample();

Output:

Example program to demonstrate showMessageDialog()

import javax.swing.*;
public class OptionPaneExample {
JFrame f;
OptionPaneExample(){
f=new JFrame();
JOptionPane.showMessageDialog(f,"Successfully Updated.","Alert",JOptionPane.WARNING_MESSAGE);
}
public static void main(String[] args) {
new OptionPaneExample();
}
}
Java Programming 89

Example program to demonstrate showInputDialog()


import javax.swing.*;
public class OptionPaneExample {
JFrame f;
OptionPaneExample(){
f=new JFrame();
String name=JOptionPane.showInputDialog(f,"Enter Name");
}
public static void main(String[] args) {
new OptionPaneExample();
}
}

Output:

5.3.9 Difference between AWT and Swing [2 maks]

No. Java AWT Java Swing

Java swing components are platform-


1) AWT components are platform-dependent.
independent.

2) AWT components are heavyweight. Swing components are lightweight.

3) AWT doesn't support pluggable look and feel. Swing supports pluggable look and feel.

Swing provides more powerful components


4) AWT provides less components than Swing. such as tables, lists, scrollpanes, colorchooser,
tabbedpane etc.

AWT doesn't follows MVC(Model View Controller) where model


5) represents data, view represents presentation and controller acts as an Swing follows MVC.
interface between model and view.
Java Programming 90

Difference between Swing and Applet[3 marks]

Swing Applet

Swing is light weight Component. Applet is heavy weight Component.

Swing have look and feel according to user view you Applet Does not provide this facility.
can change look and feel using UIManager.

Swing uses for stand lone Applications, Swing have Applet need HTML code for Run the Applet.
main method to execute the program.

Swing uses MVC Model view Controller. Applet not.

Swing have its own Layout like most popular Box Applet uses AWT Layouts like flowlayout.
Layout.

Swing have some Thread rules. Applet doesn't have any rule.

To execute Swing no need any browser By which we To execute Applet programe we should need any one
can create stand alone application But Here we have to browser like Appletviewer, web browser. Because
add container and maintain all action control with in Applet using browser container to run and all action
frame container. control with in browser container.
Java Programming 91

UNIT_V JNTUH PREVIOUSLY ASKEDSHORT ANSWER QUESTIONS

1. What are the containers available in swing? [2M]


2. Compare Applets with application programs. [3M]
3. what is the use of LayOut manager
4. explain about life cycle of Applet
5. What are the merits of swing components over AWT? [2]
6. What is an adapter class? What is its significance? List the adapter classes. [3]
7. What are the sources for item event? [2]
8. Give the hierarchy for swing components. [3]
9. Give the subclasses of JButton class.
10. Differentiate between grid layout and border layout managers.
11. What are the limitations of AWT? [2]
12. Why do applet classes need to be declared as public? [3]
13. Give the AWT hierarchy. [2]
14. What are the various classes used in creating a swing menu? [3]
15. What are the differences between JToggle buttion and Radio buttion? [2]
16. What is an adapter class? Explain with an example. [3]
17. What is Swing in Java? How it differs from Applet. [2]
18. How do applets differ from application program? [3]

UNIT-V JNTUH-PREVIOUSLY ASKD ESSAY QUESTIONS

1a) What is the significance of layout managers? Discuss briefly various layout managers.
b) Give an overview of JButton class. [5+5]

2a) Explain delegation event model.


b) Write an Applet to draw a smiley picture accept user name as a parameter and display welcome
message. [5+5]

3a) Describe about various components in AWT.


b) Write an applet program to handle all mouse events. [5+5]

4a) Write a Java program to create AWT radio buttons using check box group.
b) Explain the various event listener interfaces. [5+5]

5 a)Write a java program that design scientific calculator using AWT


b)What are the different types of Event listeners supported by java

6 a) Is Applet more secure than application program? Justify your answer.


b) Design a user interface to collect data from the student for admission application using swing components.
[5+5]

7. Write a program to demonstrate various keyboard events with suitable functionality. [10]

8.a) Why swing components are preferred over AWT components?


b) What is an adapter class? What is their role in event handling? [5+5]
Java Programming 92

9a) Explain the life cycle of an applet.


b) What are the various layout managers used in Java? [5+5]

10.a) What is the role of event listeners in event handling? List the Java event listeners
b) Write an applet to display the mouse cursor position in that applet window.[5+5]

11.a) Discuss various AWT containers with examples.


b) Explain about the adapter class with an example. [5+5]

12.a) What is an applet? Explain the life cycle of Applet with a neat sketch.
b) Write the applets to draw the Cube and Cylinder shapes. [5+5]

13.a) What is an Layout manager? Explain different types of Layout managers.


b) Write a program to create a frame window that responds to key strokes. [5+5]

14.a) Illustrate the use of Grid Bag layout.


b) What are the subclasses of JButton class of swing package? [5+5]

15.a) Create a simple applet to display a smiley picture using Graphics class methods.
b) Write a short note on delegation event model. [5+5]

16 a) List and explain different types of Layout managers with suitable examples.
b) How to move/drag a component placed in Swing Container? Explain. [5+5]

17.a) Discuss about different applet display methods in brief.


b) What are the various components of Swing? Explain. [5+5]

18 a) What is the difference between init( ) and start ( ) methods in an Applet? When will each be
executed?
b) Write the applets to draw the Cube and Circle shapes. [5+5]

19. a) Explain various layout managers in JAVA.


b) Write a program to create a frame window that responds to mouse clicks. [5+5]

You might also like