Java Programming All Units Notes
Java Programming All Units Notes
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.
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:
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.
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 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”.
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.
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.
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.”
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.
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.
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.
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
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.
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:
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).
14
Secured:
Java is secured because
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:
Portable :
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.
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).
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:
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 is an acronym for Java Development Kit.It physically exists.It contains JRE +
development tools.
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)
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:
NOTE:JVM, JRE and JDK are platform dependent because configuration of each OS differs.
But, Java is platform independent
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
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.
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.
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
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.
26
7. loading the file may take a couple of minutes based on your connection speed.
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.
29
13. You will then be asked to install the Java Runtime Engine (JRE.) Click the “Next >”
button.
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…
32
2. The System Information Window should load.
33
4. System Properties window should open with the “Advanced” tab already selected.
Click on “Environment Variables” button.
34
6. In the “System variables” region, scroll down until you see the “Path” variable.
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:
36
10. Click the “OK” button to confirm your change.
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:
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.
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
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.
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.
Step 1: Click on the Windows button and choose Control Panel. Select System.
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;.;
43
Java Programming 44
PATH CLASSPATH
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.
44
Java Programming 45
1.Open a simple text editor program such as Notepad and type the following content:
2.Save the file as HelloWorld.java (note that the extension is .java) under a directory, let’s say, C:\Java
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:
It’s now ready to run our first Java program. To run java program use following Syntax
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 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.
{ {
{ }
} {
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.
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:
Literals:
Using a literal representation of it creates a constant value in java. For example, here are some literals:
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.
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:
48
Java Programming 49
byte
short
int
long
float
double
49
Java Programming 50
Values of class type are references. Strings are references to an instance of class String.
-9223372036854775808 to
long 8 0
9223372036854775807
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
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
50
Java Programming 51
1.1.11 Variables
Introduction of variables:
Name
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;
Initialization of Variable:
ii.Runtime initialization
Syntax:
Datatype variable_name=value;
52
Java Programming 53
Datatype variable_name=Expression;
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).
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.
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().
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
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:
import java.io.*;
class ConsoleDemo
{
public static void main(String args[])
{
String str;
55
Java Programming 56
56
Java Programming 57
Local Variable
Instance Variable
A variable that is declared inside the class but outside the method is called instance variable .
class A
{
int data=50;//instance variable
static int m=100;//static variable
void method()
{
int n=90; //local variable
}
} //end of class
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.
The process of converting one data type to another data type is called as Casting
Types of castings:
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
double m=50.00;
int n=(int)m;
58
Java Programming 59
When one type of data is assigned to another type of variable, an automatic type conversion
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
double f=3.141,x;
int i,j=30;
i=(int)f;//explicit conversion
x=j;//implicit conversion
59
Java Programming 60
Output: i value is 3
x value is 30.00
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.
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
Every array in java is an object hence we can create by using new operator.
arrayname=new datatype[size];
Example :
a= new int[3];
Example:
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 :
Rule 2:
Example :
Rule 3 :
If we are taking array size with -ve int value then we will get runtime exception saying
NegativeArraySizeException.
Example :
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 :
byte b=10;
Rule 5 :
The maximum allowed array size in java is maximum value of int size [2147483647].
Example :
Array initialization:
arrayname[subscript]=value;
Example:
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
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:
Array Length:
length Vs length():
length:
length() method:
Example:
66
Java Programming 67
System.out.println(x.length);//3
Example:
String s="bhaskar";
System.out.println(s.length);//C.E:cannot find symbol
System.out.println(s.length());//7
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
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
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.
Datatype arrayname[ ][ ];
Or
Datatype[ ][ ] arrayname;
int [ ][ ]a;
int [ ][ ]a;
int [ ] [ ]a;
int [ ] a[ ];
int [ ]a[ ];
Example :
69
Java Programming 70
syntax:
Example:
int a[ ] [ ];
a=new int[3][2];
Syntax
Example1:
70
Java Programming 71
a[0]=new int[2];
a[1]=new int[4];
a[2]=new int[3];
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.
Length variable applicable only for arrays where as length()method is applicable for String objects.
Example :
71
Java Programming 72
Diagram:
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
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
int[ ][ ][ ] a;
int [ ][ ][ ]a;
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.
At the time of anonymous array creation we can’t specify the size otherwise we will get compile time
error.
Example :
74
Java Programming 75
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
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
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
Show Examples
- (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
Assume variable A holds 10 and variable B holds 20, then −Show Examples
76
Java Programming 77
>= (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.
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
Show Examples
77
Java Programming 78
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.
78
Java Programming 79
Show Examples
Show Examples
79
Java Programming 80
Miscellaneous Operators
80
Java Programming 81
Conditional Operator ( ? : )
instanceof Operator
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 −
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 );
}
}
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 −
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 );
}
}
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
Output
true
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.
83
Java Programming 84
84
Java Programming 85
One of the most common operators that you'll encounter is the simple assignment operator " =".
int cadence = 0;
int speed = 0;
int gear = 1;
classArithmeticDemo {
int result = 1 + 2;
// result is now 3
intoriginal_result = result;
result = result - 1;
// result is now 2
original_result = result;
result = result * 2;
// result is now 4
85
Java Programming 86
original_result = result;
result = result / 2;
// result is now 2
original_result = result;
result = result + 8;
// result is now 10
original_result = result;
result = result % 7;
// result is now 3
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
System.out.println(thirdString);
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)
87
Java Programming 88
ClassUnaryDemo {
// 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);
// 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 {
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
90
Java Programming 91
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 {
int value1 = 1;
int value2 = 2;
91
Java Programming 92
class ConditionalDemo2 {
int value1 = 1;
int value2 = 2;
int result;
booleansomeCondition = true;
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).
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 following program, BitDemo, uses the bitwise AND operator to print the number "2" to standard
output.
classBitDemo {
intval = 0x2222;
// prints "2"
System.out.println(val& bitmask);
93
Java Programming 94
1.1.14 Expressions
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:
...
...
if (Character.isUpperCase(aChar)) {
... }
Each expression performs an operation and returns a value, as shown in the following table.
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:
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
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
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 .
Simple if Statement
if…else Statement
Nested if statement
if...else if…else statement
Switch statement
While
Do…while
For
For-Each Loop
Break
Continue
Return
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
}
Example:
class ifTest {
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) {
Example:
class ifelseTest {
int x = 9;
if (x > 10)
else
Output:
98
Java Programming 99
i is less than 10
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 {
int x = 25;
if (x > 10) {
if (x%2==0)
99
Java Programming 100
else
else {
Output:
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 {
int x = 2;
if (x > 10) {
else if (x <10)
else {
System.out.println("i is 10");
Output:
i is less than 10
101
Java Programming 102
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
class switchDemo{
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:
break;
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 {
int j = 1;
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 {
int j = 10;
do {
System.out.println(j);
j = j+1;
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 {
for (int i : a) {
106
Java Programming 107
System.out.println(i);
Output:
10
15
20
25
30
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 {
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 {
108
Java Programming 109
// If the number is odd then bypass and continue with next value
if (j%2 != 0)
continue;
Output:
02468
ASIS FOR
BREAK CONTINUE
COMPARISON
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
enclosing 'continue'.
109
Java Programming 110
Continuation 'break' stops the continuation of loop. 'continue' do not stops the
Other uses 'break' can be used with 'switch', 'continue' can not be
'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.
Class fundamentals
» 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.
class classname {
type var1;
type var2;
// 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.
To create an object of the class we use new keyword as shown below syntaxt
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
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.
/* A program that uses the Box class. Call this file BoxDemo.java */
class Box {
double width;
double height;
double depth;
class BoxDemo {
double vol;
mybox.width = 10;
mybox.height = 20;
mybox.depth = 15;
113
Java Programming 114
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.
2. parameterized constructor
1) Default Constructor
class_name( )
Statements;
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
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
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
Constructor Method
Constructor must not have return type. Method must have return type.
Constructor name must be same as the class Method name may or may not be same as class
name. name.
118
Java Programming 119
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.
119
Java Programming 120
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.
//body of method
Example of a Method:
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.
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:
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.
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:
122
Java Programming 123
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;
Output:
123
Java Programming 124
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
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:
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:
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
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 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.
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
class Student{
String name;
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(){
System.out.println(count);
//creating objects
Output:
128
Java Programming 129
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);
}
}
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.
Example:
class Demo{
System.out.println("Hello main");
129
Java Programming 130
Output:
Hello main
int a=10;
a=a+10;
System.out.println(a);
System.out.println(b);
130
Java Programming 131
Class Demo
System.out.println(“hello”);
System.out.println(“hello”);
fd. display( );
131
Java Programming 132
final class A
{
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:
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
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
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);
133
Java Programming 134
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
class Outer_class_Name
...
class Nested_class_Name
...
...
• 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
There are two types of nested classes non-static and static nested classes.
135
Java Programming 136
A class that is declared inside a class but outside a method is known as 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
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.
Example:
137
Java Programming 138
{
abstract void display();
}
class Annomynous
{
public static void main(String args[])
{
A static class that is created inside a class is known as static nested class. It cannot access the non-static
members outer class.
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.
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'};
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.
i. By String Literal
ii. By new keyword
i) String Literal
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
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).
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
1 char charAt(int index) returns char value for the particular index
4 String substring(int beginIndex, int returns substring for given begin index and end
endIndex) index
141
Java Programming 142
10 String replace(char old, char new) replaces all occurrences of specified char value
14 String[] split(String regex, int limit) returns splitted string matching regex and limit
16 int indexOf(int ch, int fromIndex) returns specified char value index starting with
given index
18 int indexOf(String substring, int returns specified substring index starting with
fromIndex) given index
142
Java Programming 143
Program on StringHandling :
String s1="hello";
String s2="hello";
String joinstring,stringlower,stringupper;
System.out.println(ch);
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
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
Constructor Description
144
Java Programming 145
145
Java Programming 146
Command-Line Arguments
Sometimes you will want to pass information into a program when you run it. This is
the information that directly follows the program’s name on the command line when it is
executed.
they are stored as strings in a String array passed to the args parameter of main( ). The first
146
Java Programming 147
Example 1:
The following program displays all of the command-line arguments that it is called with:
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:
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.
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
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.
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.
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
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
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
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:
Class PrivateAccess
155
Java Programming 156
int c;
void display()
c=a+b;
System.out.println(c);
Void sub()
156
Java Programming 157
157
Java Programming 158
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
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
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.
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
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
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
final class A
{
163
Java Programming 164
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.
If you overload a static method in Java, it is the example of compile time polyymorphism.
164
Java Programming 165
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.
class Operatoroverloading {
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
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.
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
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.
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
A a=new B();//upcasting .
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.
168
Java Programming 169
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.
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.
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
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.
Upcasting
If the reference variable of Parent class refers to the object of Child class, it is known as upcasting
class 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
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.
abstract class A
Abstract method
A method that is declared as abstract and does not have implementation is known as abstract method.
171
Java Programming 172
Output:hello
172
Java Programming 173
Object Class
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
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 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.
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.
Construction inheritance
The superclass just specifies which methods should be available but doesn't give code.
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
• 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 .
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
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
UNIT-I
178
Java Programming 179
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
180
Packages ,Interfaces
And Stream Based
Input /Output
Java Programming 2
2.1 Packages
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
Syntax:
package packagename[.subpackage1][.subpackage2]…[.subpackageN];
//save as Simple.java
package mypack;
System.out.println("Welcome to package");
If you are not using any IDE, you need to follow the syntax given below:
Syntax:
3
Java Programming 4
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).
You need to use fully qualified name e.g. mypack.Simple etc to run the class.
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.
CLASS PATH environment variable setting is used by java run time system to know
where to look for package that is created.
package MyPack
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();
………
}
}
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
There are three ways to access the package from outside the package.
1. import package.*;
2. import package.classname;
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.
package pack;
public class A
{
public void msg()
{
System.out.println("Hello");
}
}
6
Java Programming 7
import pack.*;
class B
{
public static void main(String args[])
{
A obj = new A();
obj.msg();
}
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
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
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.
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
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 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.
10
Java Programming 11
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.
1. private
2. default
3. protected
4. public
There are many non-access modifiers such as static, abstract, synchronized, native, volatile, transient etc.
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
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
}
}
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.
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.
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
//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
(or)
(or)
An interface in java is a blueprint of a class. It has static final constants and abstract methods.
They are mainly three reasons to use interface. They are given below.
Syntax:
public interface NameOfInterface
In other words, Interface fields are public, static and final by default, and methods are public and abstract.
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
interface MyInterface
{
public void method();
}
class Demo implements MyInterface
{
public void method()
{
System.out.println("Implementation of method");
}
public static void main(String arg[])
{
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();
}
Output:
Hello
19
Java Programming 20
Welcome
Abstract class and interface both are used to achieve abstraction where we can declare the abstract
methods.
But there are many differences between abstract class and interface that are given below.
20
Java Programming 21
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.
• Nested interface must be public if it is declared inside the interface but it can have any access modifier if
declared within the class.
interface interface_name
{
...
public interface nested_interface_name
{
...
}
}
21
Java Programming 22
void show();
void show()
obj.show();
obj.message();
}
22
}
Java Programming 23
Output:
23
Java Programming 24
Output:
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
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
{
…..
}
}
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();
}
}
25
Java Programming 26
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.
interface interface_name
{
….
26
Java Programming 27
Interface inheritance
Output:
Hello
Welcome
27
Java Programming 28
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
Byte stream classes have been designed to provide functional features for creating and manipulating streams
and files for reading and writing Bytes.
1. InputStream class
2. OutputStream class
1.InputStream Class:
Reading Bytes
Closing streams
Marking positions in streams
Skipping ahead in stream
Finding the number of Bytes in a streams
29
Java Programming 30
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
2.OutputStream class:
Writing bytes
Closing streams
Flushing streams
30
Java Programming 31
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
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
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
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
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();
}
}
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[])
{
}
35
}
Java Programming 36
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
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.
Reading/Writing Characters:
The subclasses of Reader and Writer implements streams that handle characters.
The two subclasses used are
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
Reading/Writing Bytes
The subclasses of Reader and Writer implements streams that handle bytes.
The two subclasses used are
}
catch(IOException e)
{
System.out.println(e);
finally
{
39
Java Programming 40
try
ins.close();
outs.close();
catch(IOException e)
System.out.println(e);
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:
40
Java Programming 41
Here,newPos specifies the new position,in bytes,of the file pointer from the beginning of the file.
Output:
x
333
3.1412
333
False
41
Java Programming 42
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
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:
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
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
eo.setEmpno (100);
eo.setEname ("KVR");
eo.setSal (10000.00f);
oos.writeObject (eo);
oos.close ();
fos.close ();
Output:
EMPLOYEE OBJECT SAVED SUCCESSFULLY...
47
Java Programming 48
2.3.10 Enumeration
enum enumerationtype{identifier,identifier2,…….}
Example:
note:
enumerationtype variablename1,variablename2,…..;
Example:
Season s;
Day d;
Note:
s= Season. WINTER;
d= Day. SUNDAY
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.
All enumerations automatically contain predefined methods: values( ) valueOf( )and 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.
49
Java Programming 50
The following program demonstrates the values( ), valueOf( ) and ordinal() methods:
class EnumDemo2 {
Season s;
for(Season x : allseasons)
System.out.println(x);
System.out.println();
System.out.println("WINTER ordinal="+Season.WINTER.ordinal());
System.out.println("SPRING ordinal="+Season.SPRING.ordinal());
System.out.println("SUMMER ordinal="+Season.SUMMER.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
class BoxingDemo
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.
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.
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);
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
55
Java Programming 56
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
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.
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.
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
Unchecked Exception
Unchecked exceptions are the class that extends RuntimeException. Unchecked exception are ignored at
compile time.
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
There are given some scenarios where unchecked exceptions can occur. They are as follows:
1. int a=50/0;//ArithmeticException
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
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
If you are inserting any value in the wrong index, it would result ArrayIndexOutOfBoundsException as shown
below:
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
class terminationtest
}
}
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”
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.
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.
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
class Excp {
int a,b,c;
try {
a=0;
b=10;
c=b/a;
catch(ArithmeticException e) {
System.out.println("Divided by zero");
Output :
Divided by zero
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
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.
class Excep {
try {
int arr[]={1,2};
arr[2]=3/0;
catch(ArithmeticExceptionae)
System.out.println("divide by zero");
catch(ArrayIndexOutOfBoundsException e)
}
Java Programming 10
Output :
divide by zero
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 {
try
int arr[]={1,2};
arr[2]=3/0;
System.out.println("Generic exception");
}
Java Programming 11
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 {
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
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.
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
Ex:newNullPointerException("test");
class Test {
try {
catch(ArithmeticException e) {
System.out.println("Exception caught");
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.
import java.io.*;
if(num==1)
else
class Demo
try{
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.
class ExceptionTest {
System.out.println("out of try");
try {
Java Programming 16
catch(ArrayIndexOutOfBoundException ae)
System.out.println(“array exception”);
finally {
Output :
Out of try
Array exception
Exception in thread main java. Lang. exception array Index out of bound exception.
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
Protectedvoid finalize()
Exception
class FinalizeExample{
System.out.println("finalize called");
f1=null;
f2=null;
System.gc();
Output:
finalize called
Java Programming 18
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.
Exception Description
StringIndexOutOfBounds UnsupportedOperationException
An unsupported operation was encountered.
Exception Description
CloneNotSupportedException Attempt to clone an object that does not implement the Cloneable
interface.
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.
MyException(int a) //constructor
ex=a;
class UserException {
if(a<0) {
}
Java Programming 21
else {
System.out.println(a+b);
try {
sum(-10, 10);
catch(MyException me) {
System.out.println(me);
Points to Remember
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
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.
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
Substitute Process are also called heavyweight task. Thread are also called lightweight task.
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:
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.
Process-based Multitasking(Multiprocessing)
Thread-based Multitasking(Multithreading)
Java Programming 24
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.
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
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
We can a thread by instantiating an object of type Thread. This can be accomplish by in two ways
Functionality;
t.start( )
package threads;
for(int i=1;i<=3;i++)
System.out.println("user thread:"+i);
t.start();
Output:
user thread:1
user thread:2
user thread:3
Functionality;
Java Programming 29
t.start( )
package threads;
for(int i=1;i<=10;i++)
System.out.println("user thread:"+i);
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
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.
classMainThread
Thread t=Thread.currentThread();
Java Programming 31
t.setName("MainThread");
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.
m1.setPriority(Thread.MIN_PRIORITY);
Java Programming 32
m2.setPriority(Thread.MAX_PRIORITY);
m1.start();
m2.start();
Output:
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
Types of Synchronization
1. Process Synchronization
2. Thread Synchronization
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.
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
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.
class First
System.out.print("["+msg);
try
Thread.sleep(2000);
Java Programming 34
catch(InterruptedException e)
System.out.println("error is"+e);
System.out.print("]");
String msg;
First fobj;
fobj=fp;
msg=str;
start();
fobj.display(msg);
}
Java Programming 35
Output:
[welcome[program[new]]]
When a thread invokes a synchronized method, it automatically acquires the lock for that object and releases it
when the method returns
class First
System.out.print("["+msg);
try {
Thread.sleep(2000);
Java Programming 36
catch(InterruptedException e)
System.out.println("error is"+e);
System.out.print("]");
String msg;
First fobj;
fobj=fp;
msg=str;
start();
fobj.display(msg);
}
Java Programming 37
Output:
[welcome][new][program]
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.
//code block
}
Java Programming 38
class First
System.out.print("["+msg);
try
Thread.sleep(2000);
catch(InterruptedException e)
System.out.println("error is"+e);
System.out.print("]");
String msg;
First fobj;
{
Java Programming 39
fobj=fp;
msg=str;
start();
synchronized(fobj)
fobj.display(msg);
Output:
Java Programming 40
[welcome][new][program]
If you make any static method as synchronized, the lock will be on the class not on object.
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.
In this example we are applying synchronized keyword on the static method to perform static synchronization.
class Table{
for(int i=1;i<=10;i++){
System.out.println(n*i);
try{
Java Programming 41
Thread.sleep(400);
}catch(Exception e){}
Table.printTable(1);
Table.printTable(10);
Table.printTable(100);
Table.printTable(1000);
class Use{
t1.start();
t2.start();
t3.start();
t4.start();
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:
3) notifyAll() method
Wakes up all threads that are waiting on this object's monitor. Syntax:
Why wait(), notify() and notifyAll() methods are defined in Object class not Thread class?
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.
should be notified by notify() or notifyAll() after the specified amount of time, sleep is
methods completed.
Java Programming 44
class Customer {
int amount=10000;
System.out.println("going to withdraw");
if(this.amount<amount) {
try {
wait();
catch(Exception e)
System.out.println("error"+e);
this.amount=this.amount-amount;
System.out.println("withdraw is completed");
this.amount=this.amount+amount;
System.out.println("deposite completed");
Java Programming 45
notify();
new Thread() {
c.withdraw(15000);
}.start();
new Thread() {
c.deposit(10000);
}.start();
Output :
going to withdraw
deposite completed
withdraw is completed
Aim: Write a Java program that correctly implements the producer – consumer problem using the
concept of inter thread communication.
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.*;
for(;;)
int roll;
roll = d.nextInt(200) + 1;
System.out.println(roll);
try
Thread.sleep(1000);
if(roll%2==0)
t2.start();
else
t3.start();
catch(InterruptedException e){}
}
Java Programming 50
int r1;
Second2(int r)
r1=r;
System.out.println("The square of
number"+r1+"is:"+r1*r1);
int r1;
Third3(int r)
r1=r;
class Mthread
{
Java Programming 51
t1.start();
}
Java Programming 52
2.Does Java support thread priorities? Justify your answer with suitable discussion.
b)**Describe producer-consumer pattern using inter-thread communication. [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”
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]
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]
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 :
Framework :
Collection Framework :
Collection framework represents a unified architecture for storing and manipulating group of objects. It has:
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
There are many methods declared in the Collection interface. They are as follows:
3 public boolean remove(Object element) is used to delete an element from this 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.
Iterator interface
Iterator interface provides the facility of iterating the elements in forward direction only.
There are only three methods in the Iterator interface. They are:
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.
Java ArrayList class uses a dynamic array for storing the elements. It inherits AbstractList class and
implements List interface.
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.
Constructor Description
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
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.
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.
1. By Iterator interface.
2. By for-each loop.
Java Programming 8
import java.util.*;
class TestCollection1{
list1.add("Vijay");
list1.add("Giri");
list1.add("Ajay");
Iterator itr=list1.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
for(String obj:list1)
System.out.println(obj);
list2.add("Vijay");
System.out.println(“elements in list2”);
Java Programming 9
for(String obj:list2)
System.out.println(obj);
Iterator itr=list1.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
list1.removeAll(list2);
Iterator itr=list1.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
Output :
Ravi
Vijay
Giri
Java Programming 10
Ajay
Ravi
Vijay
Giri
Ajay
elements in list2
Sonoo
Vijay
Ravi
Vijay
Giri
Ajay
Sonoo
Vijay
Ravi
Vijay
Giri
Ajay
Java Programming 11
class Student{
int rollno;
String name;
int age;
this.rollno=rollno;
this.name=name;
this.age=age;
import java.util.*;
//creating arraylist
al.add(s2);
Java Programming 12
al.add(s3);
//Getting Iterator
Iterator itr=al.iterator();
while(itr.hasNext()){
Student st=(Student)itr.next();
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.
As shown in above diagram, Java LinkedList class extends AbstractSequentialList class and implements List
and Deque interfaces.
Java Programming 14
In case of doubly linked list, we can add or remove elements from both side.
Constructor Description
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.
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.
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.
import java.util.*;
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
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.
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
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);
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
Constructors in HashSet
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.
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);
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();
Using iterator
Without using iterator
import java.io.*;
import java.util.*;
animals.add("Elephant");
animals.add("Tiger");
animals.add("Lion");
// Creating an iterator
while (iterator.hasNext()) {
System.out.println(iterator.next());
System.out.println(animal);
clonedSet = (HashSet)animals.clone();
animals.remove("Elephant");
animals.remove("Lion");
animals.clear();
Output:
Elephant
Tiger
Lion
Elephant
Tiger
Lion
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:
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;
tset.add("ABC");
tset.add("String");
tset.add("Test");
tset.add("Pen");
tset.add("Ink");
tset.add("Jack");
//Displaying TreeSet
System.out.println(tset);
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.
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
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.
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.
import java.util.*;
class Example {
pQueue.add("C");
pQueue.add("C++");
pQueue.add("Java");
pQueue.add("Python");
while (itr.hasNext())
System.out.println(itr.next());
pQueue.poll();
while (itr2.hasNext())
System.out.println(itr2.next());
pQueue.remove("Java");
while (itr3.hasNext())
System.out.println(itr3.next());
boolean b = pQueue.contains("C");
Output:
C++
Java
Python
C++
Python
Java
C++
Python
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.
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 −
Class constructors
Constructor Description
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
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.
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
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. 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.
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.
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
ar.add("ab");
ar.add("bc");
ar.add("cd");
ar.add("de");
while(it.hasNext())
System.out.print(it.next()+" ");
Output:
ab bc cd de
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.
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.
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.
int nextIndex() Returns the index of the next element. If there is not a next element, returns the
size of the list.
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 {
ar.add("ab");
ar.add("bc");
ar.add("cd");
ar.add("de");
System.out.print(litr.next()+" ");
System.out.print(litr.previous()+" ");
Output:
ab bc cd de
de cd bc ab
Java Programming 34
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.
...
import java.util.*;
class ForEachDemo {
ls.add("a");
ls.add("b");
ls.add("c");
ls.add("d");
System.out.print(str+" ");
}
Java Programming 35
Output:
abcd
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.
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.
Method Description
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.
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.
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
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.
//Non-generic
import java.util.*;
map.put(1,"Amit");
map.put(5,"Rahul");
map.put(2,"Jai");
map.put(6,"Amit");
//Traversing Map
Java Programming 39
Iterator itr=set.iterator();
while(itr.hasNext()){
Map.Entry entry=(Map.Entry)itr.next();
System.out.println(entry.getKey()+" "+entry.getValue());
Output:
1 Amit
2 Jai
5 Rahul
6 Amit
import java.util.*;
class MapExample2{
map.put(100,"Amit");
Java Programming 40
map.put(101,"Vijay");
map.put(102,"Rahul");
for(Map.Entry m : map.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
Output:
102 Rahul
100 Amit
101 Vijay
import java.util.*;
class MapExample3{
map.put(100,"Amit");
map.put(101,"Vijay");
map.put(102,"Rahul");
Java Programming 41
map.entrySet()
stream()
sorted(Map.Entry.comparingByKey())
forEach(System.out::println);
sorted(Map.Entry.comparingByKey(Comparator.reverseOrder()))
forEach(System.out::println);
sorted(Map.Entry.comparingByValue())
forEach(System.out::println);
Java Programming 42
sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
forEach(System.out::println);
Output:
100=Amit
101=Vijay
102=Rahul
comparingByKey in descending order
102=Rahul
101=Vijay
100=Amit
100=Amit
102=Rahul
101=Vijay
Java Programming 43
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.
1. compare( )
2. equals( )
1.The compare( ) method, shown here, compares two elements for order:
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:
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.
import java.util.*;
aStr = a;
bStr = b;
return bStr.compareTo(aStr);
class CompDemo {
Java Programming 45
ts.add("C");
ts.add("A");
ts.add("B");
ts.add("E");
ts.add("F");
ts.add("D");
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
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 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 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
import java.util.*;
ll.add(new Integer(-8));
ll.add(new Integer(20));
ll.add(new Integer(-20));
ll.add(new Integer(8));
while(li.hasNext()) {
System.out.println();
Collections.shuffle(ll);
Java Programming 48
li = ll.iterator();
while(li.hasNext()) {
System.out.println();
Output
Minimum: -20
Maximum: 20
Java Programming 49
4.1.10 Arrays
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
int[] grades;
Student[] students;
The students array has been declared and instantiated, but not yet initialized: no
}
Java Programming 50
"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.
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
Dictionary
Properties
HashTable
Vector
Stack
Legacy Interface
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:
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);
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:
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
System.out.println();
// elements method
System.out.println();
// keys method :
// isEmpty method
// remove method :
dictionary.remove("surname");
// size method
Output:
surname:abc
middlename:def
abc
def
sur name
middlename
surname:null
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.
Here, K specifies the type of keys, and V specifies the type of values.
Syntax:
Hashtable( );
Hashtable(int size);
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
// Demonstrate a Hashtable.
import java.util.*;
class HTDemo
Enumeration<String> names;
String str;
double bal;
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.
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.
class PropDemo {
capitals.put("Indiana", "Indianapolis");
System.out.println();
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:
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.
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
st.push(a);
System.out.println("push(" + a + ")");
}
Java Programming 62
Integer a = st.pop();
System.out.println(a);
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
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.
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(Collection c)
This constructor creates a vector that contains the elements of collection c.
Method Description
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);
Last element: 12
Vector contains 3.
Elements in vector:
1 2 3 4 5 6 7 9 10 11 12
-String Tokenizer
-Bit Set
-Date
-Caleneder
-Random
-Formatter
-Scanner
The set of delimiters (the characters that separate tokens) may be specified either at creation time or on a per -
token basis.
Constructor Description
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.
Method Description
int countTokens() Calculates the number of times that this okenizer's nextToken method
can be called before it generates an exception.
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.
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.
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
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
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
d Day in a month 10
m Minute in hour 30
s Second in minute 56
S Millisecond 234
w Week in year 40
W Week in month 1
a A.M./P.M. marker PM
G Era designator AD
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
OUTPUT
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
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
}
}
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
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();
}
}
OUTPUT
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
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.
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.
%a %A Floating-point hexadecimal
%b %B Boolean
%c Character
%d Decimal Integer
%e %E Scientfic notation
%f Decimal floating-point
%o Octal Integer
%s %S String
%x %X Integer hexadecimal
%% Inserts a % sign
Java Programming 84
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.
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
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]
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]
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.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.
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;
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.
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
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 :
Controller:
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.
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
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
File Dialog A FileDialog control represents a dialog window from which the user can select a file.
Method Description
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.
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.
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( ).
String getText( )
For setText( ), str specifies the new label. For getText( ), the current label is returned.
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.
After a button has been created, you can set its label by calling setLabel( ). You can retrieve its label by calling
getLabel( ).
String getLabel( )
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.
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( ).
boolean getState( )
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.
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( ).
Checkbox getSelectedCheckbox( )
Here, which is the check box that you want to be selected. The previously selected check box will be turned off.
Java Programming 14
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.
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.
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:
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( ),
int getItemCount( );
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:
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:
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
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
int getItemCount( );
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:
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
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.
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.
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
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
.5.1.5 Container
Abstract Windowing Toolkit (AWT): Abstract Windowing Toolkit (AWT) is used for GUI programming in
java.
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.
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
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
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.
Flow Layout
Border Layout
Grid Layout
Card Layout
// java.awt.Container
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 new Layout object. The Panel container sets to this layout.
pnl.setLayout(new FlowLayout());
pnl.add(new JLabel("One"));
Java Programming 26
pnl.add(new JLabel("Two"));
pnl.add(new JLabel("Three"));
......
You can get the current layout via Container's getLayout() method.
System.out.println(pnl.getLayout());
// java.awt.FlowLayout[hgap=5,vgap=5,align=center]
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.
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();
Note: alignment :
Default value:
Example
import java.awt.*;
import java.awt.event.*;
public AWTFlowLayoutDemo ()
setLayout(new FlowLayout());
add(btn1);
add(btn2);
add(btn3);
add(btn4);
add(btn5);
add(btn6);
}
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
Example
import java.awt.*;
import java.awt.event.*;
public AWTGridLayoutDemo () {
// "super" Frame sets layout to 3x2 GridLayout, horizontal and vertical gaps of 3 pixels
add(btn1);
add(btn2);
add(btn3);
add(btn4);
add(btn5);
add(btn6);
}
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();
Example
import java.awt.*;
import java.awt.event.*;
public AWTBorderLayoutDemo ( )
// "super" Frame sets layout to BorderLayout, horizontal and vertical gaps of 3 pixels
add(btnNorth, BorderLayout.NORTH);
Java Programming 32
add(btnSouth, BorderLayout.SOUTH);
add(btnCenter, BorderLayout.CENTER);
add(btnEast, BorderLayout.EAST);
add(btnWest, BorderLayout.WEST);
}
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
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
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.
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.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
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);
}
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(String It has no effect, since this layout manager does not
name, Component comp) use a per-component string.
import java.awt.Button;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.*;
public GridBagLayoutExample() {
setLayout(grid);
this.setLayout(layout);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridx = 1;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.ipady = 20;
gbc.gridx = 0;
gbc.gridy = 1;
gbc.gridx = 1;
gbc.gridy = 1;
gbc.gridx = 0;
gbc.gridy = 2;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = 2;
setSize(300, 300);
setPreferredSize(getSize());
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
Java Programming 38
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.
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.)
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.
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:
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:
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.
First, it must have been registered with one or more sources to receive notifications about
specific types of events.
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.
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);
For registering the component with the Listener, many classes provide the registration methods.
For example:
• Button
• MenuItem
• TextField
• TextArea
• Checkbox
• Choice
• List
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.
The Java MouseListener is notified whenever you change the state of mouse
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.
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
import java.awt.*;
import java.awt.event.*;
Label l;
MouseListenerExample(){
addMouseListener(this);
l=new Label();
l.setBounds(20,50,100,20);
add(l);
setSize(300,300);
setLayout(null);
setVisible(true);
l.setText("Mouse Clicked");
l.setText("Mouse Entered");
l.setText("Mouse Exited");
l.setText("Mouse Pressed");
l.setText("Mouse Released");
new MouseListenerExample();
Output:
Java Programming 46
import java.awt.*;
import java.awt.event.*;
MouseMotionListenerExample(){
addMouseMotionListener(this);
setSize(300,300);
setLayout(null);
setVisible(true);
Graphics g=getGraphics();
g.setColor(Color.Green);
g.fillOval(e.getX(),e.getY(),20,20);
new MouseMotionListenerExample();
Output:
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
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());
}
new KeyAdapterExample();
}
}
Output:
......
private class MyNestedClass1 { ...... } // an nested class defined inside the outer class
public static class MyNestedClass2 { ...... } // an "static" nested class defined inside the outer 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.]
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.
import java.awt.*;
import java.awt.event.*;
public class InnerClassDemo extends Frame {
private TextField tfCount;
private Button btnCount;
private int count = 0;
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 {
• 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.
import java.awt.*;
import java.awt.event.*;
setTitle("AWT Counter");
setSize(250, 100);
setVisible(true);
}
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
Secured
It can be executed by browsers running under many plateforms, including Linux, Windows, Mac Os etc.
Drawback of Applet
Hierarchy of Applet
1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.
Java Programming 54
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
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
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 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]
[ALIGN = alignment]
>
...
</APPLET>
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 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,
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.
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.
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
1. 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;
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>
</body>
</html>
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;
g.drawString("welcome to applet",150,150);
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.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
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);
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>
</body>
</html>
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
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:
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.
cannot access any thing on the system except Can access any data or software
Restrictions browser’s services available on the system
Applet is portable and can be executed by any Need JDK, JRE, JVM installed on client
Execution JAVA supported browser machine
Example: Example:
Example
Java Programming 61
import java.applet.*; {
We can get any information from the HTML file as a parameter. For this purpose, Applet class provides a
method named getParameter().
Syntax:
import java.applet.Applet;
import java.awt.Graphics;
String str=getParameter("msg");
g.drawString(str,50, 50);
myapplet.html
<html>
<body>
</applet>
</body>
</html>
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.
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
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
}
}
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();
}
}
Syntax:
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
5.3.7 Exploring Swing Controls- JLabel , Image Icon and JText Field
JLabels
Image Icon
The class ImageIcon is an implementation of the Icon interface that paints Icons from Images.
JTextField
A JTextField is an area that the user can type one line of text into. It is a good way of getting text
public JTextField (int columns) // create text field with appropriate # of columns
public JTextField (String s, int columns) // create text field with s displayed & approp.
width
Methods include:
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.
Constructor Description
Methods Description
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:
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)
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
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( )
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.
Constructor Description
JJCheckBox() Creates an initially unselected check box button with no text, no icon.
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.
Methods Description
AccessibleContext getAccessibleContext() It is used to get the AccessibleContext associated with this 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.
Constructor Description
JRadioButton(String s, boolean selected) Creates a radio button with the specified text and selected status.
Methods Description
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:
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
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.
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.
Constructor Description
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.
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.
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.
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:
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.
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:
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.
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.
Constructor Description
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.
Methods Description
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.
import javax.swing.*;
JFrame f;
OptionPaneExample(){
f=new JFrame();
new OptionPaneExample();
Output:
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
Output:
3) AWT doesn't support pluggable look and feel. Swing supports pluggable look and feel.
Swing Applet
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 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
1a) What is the significance of layout managers? Discuss briefly various layout managers.
b) Give an overview of JButton class. [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]
7. Write a program to demonstrate various keyboard events with suitable functionality. [10]
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]
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]
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]
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]