Java Notes (1)
Java Notes (1)
Object-Oriented Thinking
1
Responsibilities:
A fundamental concept in OOP is to describe behavior in terms of responsibilities. A
Request to perform an action denotes the desired result. An object can use any technique
that helps in obtaining the desired result and this process will not have any interference
from other object. The abstraction level will be increased when a problem is evaluated in
terms of responsibilities. The objects will thus become independent from each other which
will help in solving complex problems. An Object has a collection of responsibilities related
with it which is termed as ‘protocol’
The Operation of a traditional program depends on how it acts on data structures. Where
as an OOP operates by requesting data structure to perform a service.
Messages & Methods:
When a message is passed to an agent (or object) that is capable of performing an action,
then that action will be initiated in OOP. An object which receives the message sent is called
‘receiver’. When a receiver accepts a message, it means that the receiver has accepted the
responsibility of processing the requested action. It then performs a method as a response
to the message in order to fulfill the request.
A Receiver’s class determines which method is to be invoked by the object in response to a
message. When similar messages are requested then all the objects of a class will invoke
the same method.
All objects are said to be the instances of a class.
For e.g., If ‘flower’ is a class then Rose is its instance
Class Hierarchies (Inheritance):
It is possible to organize classes in the form of a structure that corresponds to hierarchical
inheritance. All the child classes can inherit the properties of their parent classes. A parent
class that does not have any direct instances is called an abstract class. It is used in the
creation of subclasses.
2
Object Oriented Thinking
Let ‘Hari’ be a florist, but florist more specific form of shot keeper. Additionally, a shop
keeper is a human and a human is definitely a mammal. But a mammal is an animal &
animal is material object.
All these categories along with their relationships can be represented using a graphical
technique shown in figure. Each category is regarded as a class. The classes at the top of the
tree are said to be more abstract classes and the classes at the bottom of the tree are said to
be more specific classes.
Inheritance is a principle, according to which knowledge of a category (or class) which is
more general can also be applied to a category which is more specific.
Method Binding:
When the method is super class have same name that of the method in sub class, then the
subclass method overridden the super-class method. The program will find out a class to
which the reference is actually pointing and that class method will be binded.
E.g.
class parent
{ void print()
{ System.out.println(“From Parent”);
}
}
class child extends parent
{
void print()
{ System.out.println(“From Child”);
}
}
class Bind
{
Public static void main(String arg[])
{ child ob=new child();
ob.print();
3
}
}
o/p: From Child
The child’s object ‘ob’ will point to child class print() method thus that method will be
binded.
Overriding:
When the name and type of the method in a subclass is same as that of a method in its
super class. Then it is said that the method present in subclass overrides the method
present in super class. Calling an overridden method from a subclass will always point to
the type of that method as defined by the subclass, where as the type of method defined by
super class is hidden.
E.g. (above ’method binding’ example)
Exceptions:
Exception is a error condition that occurs in the program execution. There is an object
called ‘Exception’ object that holds error information. This information includes the type
and state of the program when the error occurred.
E.g. Stack overflow, Memory error etc
Summary of OOP concepts (proposed by Alan kay):
• Everything is an
• Computation is performed by objects communicating with each other, requesting
that other objects perform actions. Objects communicate by sending &
receiving messages. A message is a request for an 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 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 same class can perform the same actions.
• Classes are organized into a singly rooted tree structure, called inheritance
hierarchy.
Copyng with complexity:
When programs are larger then complex is more programmers found it difficult to
remember all the information they needed to know in order to develop or debug their
software.
Non-Linear behavior of complexity:
When projects become larger, a task that can be solved by a programmer in 2 months
can’t be accomplished by 2 programmers working for one month. The reason for this non-
linear behavior is complexity. The inter connections between the software components is
complicated. The OOP designers illustrated this with a memorable phrase “The bearing of a
child takes nine months, no matter how many women are assigned to the task”
Abstraction Mechanisms:
4
In general to reduce the complexities in OOP we use abstraction mechanism. Abstraction is
the ability to encapsulate, isolate design and execution the information. Object oriented
techniques can be seen as a natural outcome of a long historical progression from
procedures, to modules, to abstract datatypes and finally to objects.
Procedures are the functions that allowed tasks to be executed repeatedly. The procedure
gave the first possibility for information hiding.
Modules are the independent parts of program. A module provides the ability to divide the
program into two parts. The public part is accessible outside the module. The private part
is accessible only with in the module.
An abstract data type is a programmer defined datatype that can be manipulated like the
system defined datatypes. Objects are instances of a class. Object oriented programming
adds several important new ideas. Among them, message passing, inheritance and
polymorphism are important. Message passing is the idea that the interpretation of a
message can vary with different objects. Inheritance allows different datatypes to share
same code, and increase the functionality. Polymorphism allows this shared code to be
tailored to fit t he specific circumstances of individual datatypes.
History of Java
• History of Java
• Java Version History
The history of Java is very interesting. Java was originally designed for interactive
television, but it was too advanced technology for the digital cable television industry at the
time. The history of Java starts with the Green Team. Java team members (also known
as Green Team), initiated this project to develop a language for digital devices such as set-
top boxes, televisions, etc. However, it was suited for internet programming. Later, Java
technology was incorporated by Netscape.
The principles for creating Java programming were "Simple, Robust, Portable, Platform-
independent, Secured, High Performance, Multithreaded, Architecture Neutral, Object-
Oriented, Interpreted, and Dynamic". Java was developed by James Gosling, who is known
as the father of Java, in 1995. James Gosling and his team members started the project in
the early '90s.
5
6) In 1995, Oak was renamed as "Java" because it was already a trademark by Oak
Technologies.
Why Java Programming named "Java"?
7) Why had they chosen java name for Java language? The team gathered to choose a
new name. The suggested words were "dynamic", "revolutionary", "Silk", "jolt", "DNA", etc.
They wanted something that reflected the essence of the technology: revolutionary,
dynamic, lively, cool, unique, and easy to spell and fun to say.
According to James Gosling, "Java was one of the top choices along with Silk". Since Java
was so unique, most of the team members preferred Java than other names.
8) Java is an island of Indonesia where the first coffee was produced (called java coffee). It
is a kind of espresso bean. Java name was chosen by James Gosling while having coffee near
his office.
9) Notice that Java is just a name, not an acronym.
10) Initially developed by James Gosling at Sun Microsystems (which is now a subsidiary of
Oracle Corporation) and released in 1995.
11) In 1995, Time magazine called Java one of the Ten Best Products of 1995.
12) JDK 1.0 released in(January 23, 1996). After the first release of Java, there have been
many additional features added to the language. Now Java is being used in Windows
applications, Web applications, enterprise applications, mobile applications, cards, etc.
Each new version adds the new features in Java.
Java Version History
Many java versions have been released till now. The current stable release of Java is Java SE
10.
• JDK Alpha and Beta (1995)
• JDK 1.0 (23rd Jan 1996)
• JDK 1.1 (19th Feb 1997)
• J2SE 1.2 (8th Dec 1998)
• J2SE 1.3 (8th May 2000)
• J2SE 1.4 (6th Feb 2002)
• J2SE 5.0 (30th Sep 2004)
• Java SE 6 (11th Dec 2006)
• Java SE 7 (28th July 2011)
• Java SE 8 (18th Mar 2014)
• Java SE 9 (21st Sep 2017)
• Java SE 10 (20th Mar 2018)
First Java Program | Hello World Example
• Software Requirements
• Creating Hello Java Example
In this page, we will learn how to write the simple program of java. We can write a simple
hello java program easily after installing the JDK.
To create a simple java program, you need to create a class that contains the main method.
Let's understand the requirement first.
The requirement for Java Hello World Example
For executing any java program, you need to
• Install the JDK if you don't have installed it, download the JDK and install it.
• Set path of the jdk/bin directory. http://www.javatpoint.com/how-to-set-path-
6
in-java
• Create the java program
• Compile and run the java program
• Simple
• Object-Oriented
• Portable
7
• Platform independent
• Secured
• Robust
• Architecture neutral
• Interpreted
• High Performance
• Multithreaded
• Distributed
• Dynamic
Simple
Java is very easy to learn, and its syntax is simple, clean and easy to understand. According
to Sun, Java language is a simple programming language because:
• Java syntax is based on C++ (so easier for programmers to learn it after C++).
• Java has removed many complicated and rarely-used features, for example, explicit
pointers, operator overloading, etc.
• There is no need to remove unreferenced objects because there is an Automatic
Garbage Collection in Java.
Robust
Robust simply means strong. Java is robust because:
• It uses strong memory management.
• There is a lack of pointers that avoids security problems.
• There is automatic garbage collection in java which runs on the Java Virtual Machine
to get rid of objects which are not being used by a Java application anymore.
• There are exception handling and the type checking mechanism in Java. All these
points make Java robust.
Distributed
• Java is designed for distributed environment of the Internet. Its used for creating
applications on networks.
• Java applications can access remote objects on Internet as easily as they can do in local
system.
• Java enables multiple programmers at multiple remote locations to collaborate and
work together on a single project.
Compiled and Interpreted
• Usually a computer language is either compiled or Interpreted. Java combines both this
approach and makes it a two-stage system.
• Compiled : Java enables creation of a cross platform programs by compiling into an
intermediate representation called Java Bytecode.
• Interpreted : Bytecode is then interpreted, which generates machine code that can be
directly executed by the machine that provides a Java Virtual machine.
Robust
• It provides many features that make the program execute reliably in variety of
environments.
• Java is a strictly typed language. It checks code both at compile time and runtime.
• Java takes care of all memory management problems with garbage-collection.
8
• Java, with the help of exception handling captures all types of serious errors and
eliminates any risk of crashing the system.
Secure
• Java provides a “firewall” between a networked application and your computer.
• When a Java Compatible Web browser is used, downloading can be done safely
without fear of viral infection or malicious intent.
• Java achieves this protection by confining a Java program to the java execution
environment and not allowing it to access other parts of the computer.
Architecture Neutral
• Java language and Java Virtual Machine helped in achieving the goal of “write once; run
anywhere, any time, forever.”
• Changes and upgrades in operating systems, processors and system resources will not
force any changes in Java Programs.
Portable
• Java Provides a way to download programs dynamically to all the various types of
platforms connected to the Internet.
• It helps in generating Portable executable code.
High Performance
• Java performance is high because of the use of bytecode.
• The bytecode was used, so that it was easily translated into native machine code.
Multithreaded
• Multithreaded Programs handled multiple tasks simultaneously, which was helpful in
creating interactive, networked programs.
• Java run-time system comes with tools that support multiprocess synchronization
used to construct smoothly interactive systems.
Dynamic
• Java is capable of linking in new class libraries, methods, and objects.
• It can also link native methods (the functions written in other languages such as C and
C++).
Object-oriented
Java is an object-oriented programming language. Everything in Java is an object. Object-
oriented means we organize our software as a combination of different types of objects
that incorporates both data and behavior.
Object-oriented programming (OOPs) is a methodology that simplifies software
development and maintenance by providing some rules.
Basic concepts of OOPs are:
• Object
• Class
• Inheritance
• Polymorphism
• Abstraction
• Encapsulation
Object
9
Any entity that has state and behavior is known as an object. For example, a chair, pen,
table, keyboard, bike, etc. It can be physical or logical.
An Object can be defined as an instance of a class. An object contains an address and takes
up some space in memory. Objects can communicate without knowing the details of each
other's data or code. The only necessary thing is the type of message accepted and the type
of response returned by the objects.
Example: A dog is an object because it has states like color, name, breed, etc. as well as
behaviors like wagging the tail, barking, eating, etc.
Class
Collection of objects is called class. It is a logical entity.
A class can also be defined as a blueprint from which you can create an individual object.
Class doesn't consume any space.
Inheritance in Java
Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object. It is an important part of OOPs (Object Oriented programming
system).
The idea behind inheritance in Java is that you can create new classes that are built upon
existing classes. When you inherit from an existing class, you can reuse methods and fields
of the parent class. Moreover, you can add new methods and fields in your current class
also.
Inheritance represents the IS-A relationship which is also known as a parent-
child relationship.
Why use inheritance in java
• For Method Overriding (so runtime polymorphism can be achieved).
• For Code Reusability.
Terms used in Inheritance
• Class: A class is a group of objects which have common properties. It is a template
or blueprint from which objects are created.
• Sub Class/Child Class: Subclass is a class which inherits the other class. It is also
called a derived class, extended class, or child class.
• Super Class/Parent Class: Superclass is the class from where a subclass inherits
the features. It is also called a base class or a parent class.
• Reusability: As the name specifies, reusability is a mechanism which facilitates you
to reuse the fields and methods of the existing class when you create a new class.
You can use the same fields and methods already defined in the previous class.
The syntax of Java Inheritance
class Subclass-name extends Superclass-name
{
//methods and fields
}
The extends keyword indicates that you are making a new class that derives from an
existing class. The meaning of "extends" is to increase the functionality.
In the terminology of Java, a class which is inherited is called a parent or superclass, and
the new class is called child or subclass.
10
Types of inheritance in java
On the basis of class, there can be three types of inheritance in java:
• Single Inheritance
• Multilevel Inheritance
• Hierarchical. Inheritance
• Multiple Inheritance
• Hybrid Inheritance
File: TestInheritance.java
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}
Output:
barking...
eating...
Multilevel Inheritance Example
When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in
the example given below, BabyDog class inherits the Dog class which again inherits the
Animal class, so there is a multilevel inheritance.
Or
In Multilevel Inheritance, one class can inherit from a derived class. Hence, the derived
class becomes the base class for the new class.
11
Multilevel Inheritance
As per shown in diagram Class C is subclass of B and B is a of subclass Class A.
File: TestInheritance2.java
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}
Output:
weeping...
barking...
eating...
Hierarchical Inheritance Example
When two or more classes inherits a single class, it is known as hierarchical inheritance. In
the example given below, Dog and Cat classes inherits the Animal class, so there is
hierarchical inheritance.
Or
In Hierarchical Inheritance, one class is inherited by many sub classes.
12
Hierarchical Inheritance
As per above example, Class B, C, and D inherit the same class A.
File: TestInheritance3.java
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}
Output:
meowing...
eating...
13
Multiple Inheritance
As per above diagram, Class C extends Class A and Class B both.
• class A{
• void msg(){System.out.println("Hello");}
• }
• class B{
• void msg(){System.out.println("Welcome");}
• }
• class C extends A,B{//suppose if it were
•
• public static void main(String args[]){
• C obj=new C();
• obj.msg();//Now which msg() method would be invoked?
• }
• }
Output
Hybrid Inheritance:
Hybrid inheritance is a combination of Single and Multiple inheritance.
14
Hybrid Inheritance
As per above example, all the public and protected members of Class A are inherited into
Class D, first via Class B and secondly via Class C.
Note: Java doesn't support hybrid/Multiple inheritence
15
class Adder{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}
Output:
22
33
Q) Why Method Overloading is not possible by changing the return type of method only?
In java, method overloading is not possible by changing the return type of the method only
because of ambiguity. Let's see how ambiguity may occur:
class Adder{
static int add(int a,int b){return a+b;}
static double add(int a,int b){return a+b;}
}
class TestOverloading3{
public static void main(String[] args){
System.out.println(Adder.add(11,11));//ambiguity
}}
Output:
Compile Time Error: method add(int,int) is already defined in class Adder
System.out.println(Adder.add(11,11)); //Here, how can java determine which sum()
method should be called?
16
Note: Compile Time Error is better than Run Time Error. So, java compiler renders compiler
time error if you declare the same method having same parameters.
Polymorphism
If one task is performed in different ways, it is known as polymorphism. For example: to
convince the customer differently, to draw something, for example, shape, triangle,
rectangle, etc.
In Java, we use method overloading and method overriding to achieve polymorphism.
Another example can be to speak something; for example, a cat speaks meow, dog barks
woof, etc.
Abstraction
Hiding internal details and showing functionality is known as abstraction. For example
phone call, we don't know the internal processing.
In Java, we use abstract class and interface to achieve abstraction.
Encapsulation
Binding (or wrapping) code and data together into a single unit are known as encapsulation.
For example, a capsule, it is wrapped with different medicines.
A java class is the example of encapsulation. Java bean is the fully encapsulated class
because all the data members are private here.
Java Data Types
As explained in the previous chapter, a variable in Java must be a specified data type:
Example
int myNum = 5; // Integer (whole number)
float myFloatNum = 5.99f; // Floating point number
char myLetter = 'D'; // Character
boolean myBool = true; // Boolean
String myText = "Hello"; // String
Data types are divided into two groups:
• Primitive data types - includes byte, short, int, long, float, double, boolean and char
• Non-primitive data types - such as String, Arrays and Classes (you will learn more
about these in a later chapter)
Primitive Data Types
A primitive data type specifies the size and type of variable values, and it has no additional
methods.
There are eight primitive data types in Java:
Data Type Size Description
byte 1 byte Stores whole numbers from -128 to 127
short 2 bytes Stores whole numbers from -32,768 to 32,767
int 4 bytes Stores whole numbers from -2,147,483,648 to
2,147,483,647
long 8 bytes Stores whole numbers from -9,223,372,036,854,775,808
to 9,223,372,036,854,775,807
float 4 bytes Stores fractional numbers. Sufficient for storing 6 to 7
decimal digits
double 8 bytes Stores fractional numbers. Sufficient for storing 15
17
decimal digits
boolean 1 bit Stores true or false values
char 2 bytes Stores a single character/letter or ASCII values
Numbers
Primitive number types are divided into two groups:
Integer types stores whole numbers, positive or negative (such as 123 or -456), without
decimals. Valid types are byte, short, int and long. Which type you should use, depends on
the numeric value.
Floating point types represents numbers with a fractional part, containing one or more
decimals. There are two types: float and double.
Even though there are many numeric types in Java, the most used for numbers are int (for
whole numbers) and double (for floating point numbers). However, we will describe them
all as you continue to read.
Integer Types
Byte
The byte data type can store whole numbers from -128 to 127. This can be used instead
of int or other integer types to save memory when you are certain that the value will be
within -128 and 127:
Example
byte myNum = 100;
System.out.println(myNum);
Short
The short data type can store whole numbers from -32768 to 32767:
Example
short myNum = 5000;
System.out.println(myNum);
Int
The int data type can store whole numbers from -2147483648 to 2147483647. In general,
and in our tutorial, the int data type is the preferred data type when we create variables
with a numeric value.
Example
int myNum = 100000;
System.out.println(myNum);
Long
The long data type can store whole numbers from -9223372036854775808 to
9223372036854775807. This is used when int is not large enough to store the value. Note
that you should end the value with an "L":
Example
long myNum = 15000000000L;
System.out.println(myNum);
Floating Point Types
You should use a floating point type whenever you need a number with a decimal, such as
9.99 or 3.14515.
18
Float
The float data type can store fractional numbers from 3.4e−038 to 3.4e+038. Note that you
should end the value with an "f":
Example
float myNum = 5.75f;
System.out.println(myNum);
Double
The double data type can store fractional numbers from 1.7e−308 to 1.7e+308. Note that
you should end the value with a "d":
Example
double myNum = 19.99d;
System.out.println(myNum);
Use float or double?
The precision of a floating point value indicates how many digits the value can have after
the decimal point. The precision of float is only six or seven decimal digits,
while double variables have a precision of about 15 digits. Therefore it is safer to
use double for most calculations.
Scientific Numbers
A floating point number can also be a scientific number with an "e" to indicate the power of
10:
Example
float f1 = 35e3f;
double d1 = 12E4d;
System.out.println(f1);
System.out.println(d1);
Booleans
A boolean data type is declared with the boolean keyword and can only take the
values true or false:
Example
boolean isJavaFun = true;
boolean isFishTasty = false;
System.out.println(isJavaFun); // Outputs true
System.out.println(isFishTasty); // Outputs false
Boolean values are mostly used for conditional testing, which you will learn more about in
a later chapter.
Characters
The char data type is used to store a single character. The character must be surrounded
by single quotes, like 'A' or 'c':
Example
char myGrade = 'B';
System.out.println(myGrade);
Alternatively, you can use ASCII values to display certain characters:
Example
char a = 65, b = 66, c = 67;
19
System.out.println(a);
System.out.println(b);
System.out.println(c);
Tip: A list of all ASCII values can be found in our ASCII Table Reference.
Strings
The String data type is used to store a sequence of characters (text). String values must be
surrounded by double quotes:
Example
String greeting = "Hello World";
System.out.println(greeting);
The String type is so much used and integrated in Java, that some call it "the
special ninth type".
A String in Java is actually a non-primitive data type, because it refers to an object. The
String object has methods that is used to perform certain operations on strings. Don't
worry if you don't understand the term "object" just yet. We will learn more about
strings and objects in a later chapter.
20
3. Local Variables
A method stores its temporary state in local variables. The syntax for declaring a local
variable is similar to declaring a field (for example, int count = 0;). There is no special
keyword designating a variable as local; that determination comes entirely from the
location in which the variable is declared—between the opening and closing braces of a
method. As such, local variables are only visible to the methods in which they are declared;
they are not accessible from the rest of the class.
4. Parameters
They are the variables that are passed to the methods of a class.
Variable Declaration
Identifiers are the names of variables. They must be composed of only letters, numbers, the
underscore, and the dollar sign ($). They cannot contain white spaces. Identifiers may only
begin with a letter, the underscore, or the dollar sign. A variable cannot begin with a
number. All variable names are case sensitive.
Syntax for variable declaration
datatype1 variable1, datatype2 variable2, … datatypen variablen;
For example:
int a, char ch;
Initialisation
Variables can be assigned values in the following way: Variablename = value;
For example;
ch='a';
a=0;
Arrays
Arrays: An array represents a group of elements of same data type.
Arrays are generally categorized into two types.
• Single Dimensional arrays (or 1 Dimensional arrays or 1D) ·
• Multi-Dimensional arrays (or 2 Dimensional arrays or 2D, 3 Dimensional arrays or
3D, …)
Single Dimensional Arrays: A one dimensional array or single dimensional array
represents a row or a column of elements. For example, the marks obtained by a student in
5 different subjects can be represented by a 1D array.
· We can declare a one dimensional array and directly store elements at the time of its
declaration, as:
int marks[] = {15, 20, 25, 30, 50};
· We can create a 1D array by declaring the array first and then allocate memory for it by
using new operator, as:
int marks[]; //declare marks array
marks = new int[5]; //allot memory for storing 5 elements
These two statements also can be written as: int marks [] = new int [5];
The following program, Printarr, creates an array of integers, puts some values in it, and
prints each value to standard output.
class Printarr {
public static void main(String[] args) {
// declares an array of integers
21
int[ ] A;
// initialize elements
A[0] = 15;//first element
22
We can create a two dimensional array by declaring the array first and then we can allot
memory for it by using new operator as:
int marks[ ] [ ]; //declare marks
array marks = new int[3][5]; //allot memory for storing 15 elements.
These two statements also can be written as:
int marks [ ][ ] = new int[3][5];
Program 2: Write a program to take a 2D array and display its elements in the form
of a matrix. //Displaying a 2D array as a matrix
class Matrix
{
public static void main(String args[])
{ //take a 2D array
int x[ ][ ] = {{1, 2, 3}, {4, 5, 6} }; // display the array elements
for (int i = 0 ; i < 2 ; i++)
{
System.out.println ("");
for (int j = 0 ; j < 3 ; j++)
System.out.print(x[i][j] + “\t”);
}}}
Output:
123
456
Operators in java
Operators are used to perform operations on variables and values.
In the example below, we use the + operator to add together two values:
Example
int x = 100 + 50;
Although the + operator is often used to add together two values, like in the example above,
it can also be used to add together a variable and a value, or a variable and another
variable:
Example
int sum1 = 100 + 50; // 150 (100 + 50)
int sum2 = sum1 + 250; // 400 (150 + 250)
int sum3 = sum2 + sum2; // 800 (400 + 400)
23
• Unary Operator
Arithmetic Operators
Arithmetic operators are used to perform common mathematical operations.
24
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x = x / 3
%= x %= 3x = x % 3
&= x &= 3 x = x & 3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3
Example program
class OperatorExample{
int a=10;
int b=20;
a+=4;//a=a+4 (a=10+4)
b-=4;//b=b-4 (b=20-4)
System.out.println(a);
System.out.println(b);
}}
Output:
14
16
25
statements is true
! Logical Reverse the result, returns false if !(x < 5 && x < 10)
not the result is true
~ 0101
________
1010 = 10 (In decimal)
Note – Compiler will give 2’s complement of that number, i.e., 2’s compliment of 10 will be -
6.
// bitwise and
// 0101 & 0111=0101 = 5
System.out.println("a&b = " + (a & b));
// bitwise or
// 0101 | 0111=0111 = 7
System.out.println("a|b = " + (a | b));
// bitwise xor
// 0101 ^ 0111=0010 = 2
System.out.println("a^b = " + (a ^ b));
// bitwise and
// ~0101=1010
// will give 2's complement of 1010 = -6
System.out.println("~a = " + ~a);
27
// can also be combined with
// assignment operator to provide shorthand
// assignment
// a=a&b
a &= b;
System.out.println("a= " + a);
}
}
Output :
a&b = 5
a|b = 7
a^b = 2
~a = -6
a= 5
Java expressions
Expressions are constructed from operands and operators. The operators of an
expression indicate which operations to apply to the operands. The order of evaluation of
operators in an expression is determined by the precedence and associativity of the
operators.
An operator is a special symbol which indicates a certain process is carried out. Operators
in programming languages are taken from mathematics. Programmers work with data. The
operators are used to process data. An operand is one of the inputs (arguments) of an
operator.
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
• Decision Making in Java
• Simple if Statement
• if…else Statement
• Nested if statement
• if...else if…else statement
• Switch statement
• While
• Do…while
• For
• For-Each Loop
1. Branching Statements in Java
• Break
28
• Continue
• Return
Decision Making in Java
Decision making statements are statements which decides what to execute and when. They
are similar to decision making in real time. Control flow statements control the flow of a
program’s execution. Here flow of execution will be based on state of a program. We have 4
decision making statements available in Java.
Simple if Statement
Simple if statement is the basic of decision-making statements in Java. It decides if certain
amount of code should be executed based on the condition.
Syntax:
if (condition) {
Statemen 1; //if condition becomes true then this will be executed
}
Statement 2; //this will be executed irrespective of condition becomes true or false
Example:
class ifTest
{
public static void main(String args[])
{
int x = 5;
if (x > 10)
System.out.println("Inside If");
System.out.println("After if statement");
}
}
Output:
After if statement
if…else Statement
In if…else statement, if condition is true then statements in if block will be executed but if it
comes out as false then else block will be executed.
Syntax:
if (condition) {
Statemen 1; //if condition becomes true then this will be executed
}
Example:
class ifelseTest
{
public static void main(String args[])
{
int x = 9;
if (x > 10)
System.out.println("x is greater than 10");
else
System.out.println("x is less than 10");
System.out.println("After if else statement");
29
}
}
Output:
x is less than 10
After if else statement
Nested if statement
Nested if statement is if inside an if block. It is same as normal if…else statement but they
are written inside another if…else statement.
Syntax:
if (condition1) {
Statemen 1; //executed when condition1 is true
if (condition2) {
Statement 2; //executed when condition2 is true
}
else {
Statement 3; //executed when condition2 is false
}
}
Example:
class nestedifTest
{
public static void main(String args[])
{
int x = 25;
if (x > 10)
{
if (x%2==0)
System.out.println("x is greater than 10 and even number");
else
System.out.println("i is greater than 10 and odd number");
}
else
{
System.out.println("i is less than 10");
}
System.out.println("After nested if statement");
}
}
Output:
i is greater than 10 and odd number
After nested if statement
if...else 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
30
matching condition, that block will be executed. But if no condition is matching then the
last else statement will be executed.
Syntax:
if (condition2) {
Statemen 1; //if condition1 becomes true then this will be executed
}
else if (condition2) {
<span style="white-space:pre"> </span>Statement 2; // if condition2 becomes true then
this will be executed
}
.
.
else {
Statement 3; //executed when no matching condition found
}
Example:
class ifelseifTest
{
public static void main(String args[])
{
int x = 2;
if (x > 10)
{
System.out.println("i is greater than 10");
}
else if (x <10)
System.out.println("i is less than 10");
}
else
{
System.out.println("i is 10");
}
System.out.println("After if else if ladder statement");
}
}
Output:
i is less than 10
After if else if ladder statement
Switch statement
Java switch statement compares the value and executes one of the case blocks based on the
condition. It is same as if…else if ladder. Below are some points to consider while working
with switch statements:
• case value must be of the same type as expression used in switch statement
• case value must be a constant or literal. It doesn’t allow variables
31
• case values should be unique. If it is duplicate, then program will give compile time
error
Let us understand it through one example.
class switchDemo{
public static void main(String args[]){
int i=2;
switch(i){
case 0:
System.out.println("i is 0");
break;
case 1:
System.out.println("i is 1");
break;
case 2:
System.out.println("i is 2");
break;
case 3:
System.out.println("i is 3");
break;
case 4:
System.out.println("i is 4");
break;
default:
System.out.println("i is not in the list");
break;
}
}
}
Looping Statements in Java
Looping statements are the statements which executes a block of code repeatedly until
some condition meet to the criteria. Loops can be considered as repeating if statements.
There are 3 types of loops available in Java.
While
While loops are simplest kind of loop. It checks and evaluates the condition and if it is true
then executes the body of loop. This is repeated until the condition becomes false.
Condition in while loop must be given as a Boolean expression. If int or string is used
instead, compile will give the error.
Syntax:
while (condition)
{
statement1;
}
Example:
class whileLoopTest
{
public static void main(String args[])
32
{
int j = 1;
while (j <= 10)
{
System.out.println(j);
j = j+2;
}
}
}
Output:
1
3
5
7
9
Do…while
Do…while works same as while loop. It has only one difference that in do…while, condition
is checked after the execution of the loop body. That is why this loop is considered as exit
control loop. In do…while loop, body of loop will be executed at least once before checking
the condition
Syntax:
do{
statement1;
}while(condition);
Example: here
class dowhileLoopTest
{
public static void main(String args[])
{
int j = 10;
do
{
System.out.println(j);
j = j+1;
} while (j <= 10)
}
}
Output:
10
For
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)
33
{
statement;
}
Example:
class forLoopTest
{
public static void main(String args[])
{
for (int j = 1; j <= 5; j++)
System.out.println(j);
}
}
Output:
1
2
3
4
5
For-Each Loop
For-Each loop is used to traverse through elements in an array. It is easier to use because
we don’t have to increment the value. It returns the elements from the array or collection
one by one.
Example:
class foreachDemo{
public static void main(String args[]){
int a[] = {10,15,20,25,30};
for (int i : a) {
System.out.println(i);
}
}
Output:
10
15
20
25
30
34
{
public static void main(String args[])
{
for (int j = 0; j < 5; j++)
{
// come out of loop when i is 4.
if (j == 4)
break;
System.out.println(j);
}
System.out.println("After loop");
}
}
Output:
0
1
2
3
4
After loop
Continue
Continue statement works same as break but the difference is it only comes out of loop for
that iteration and continue to execute the code for next iterations. So it only bypasses the
current iteration.
Example:
class continueTest
{
public static void main(String args[])
{
for (int j = 0; j < 10; j++)
{
// If the number is odd then bypass and continue with next value
if (j%2 != 0)
continue;
// only even numbers will be printed
System.out.print(j + " ");
}
}
}
Output:
02468
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.
Example: Here method getwebURL() returns the current URL to the caller method.
35
public String getwebURL()
{
String vURL= null;
try {
vURL= driver.getCurrentUrl();
}
catch(Exception e) {
System.out.println("Exception occured while getting the current url :
"+e.getStackTrace());
}
return vURL;
}
Java Classes/Objects
Everything in Java is associated with classes and objects, along with its attributes and
methods. For example: in real life, a car is an object. The car has attributes, such as weight
and color, and methods, such as drive and brake.
Create a Class
MyClass.java
int x = 5;
Create an Object
In Java, an object is created from a class. We have already created the class named MyClass,
so now we can use this to create objects.
To create an object of MyClass, specify the class name, followed by the object name, and use
the keyword new:
36
Example
int x = 5;
System.out.println(myObj.x);
Out put:5
Java Class Methods
You learned from the Java Methods chapter that methods are declared within a class, and
that they are used to perform certain actions:
Example
System.out.println("Hello World!");
myMethod() prints a text (the action), when it is called. To call a method, write the
method's name followed by two parentheses () and a semicolon;
Example
37
static void myMethod() {
System.out.println("Hello World!");
myMethod();
Java Strings
String Length
A String in Java is actually an object, which contain methods that can perform certain
operations on strings. For example, the length of a string can be found with
the length() method:
Example
MyClass.java
Result:
The length of the txt string is: 26
38
public class MyClass {
public static void main(String[] args) {
String txt = "Hello World";
System.out.println(txt.toUpperCase());
System.out.println(txt.toLowerCase());
}
}
Result:
HELLO WORLD
hello world
String Concatenation
Example
MyClass.java
Result:
John Doe
note that we have added an empty text (" ") to create a space between firstName and
lastName on print.
You can also use the concat() method to concatenate two strings:
Example
MyClass.java
39
String firstName = "John ";
String lastName = "Doe";
System.out.println(firstName.concat(lastName));
}
}
Result:
John Doe
Java Inheritance
Java Inheritance (Subclass and Superclass)
In Java, it is possible to inherit attributes and methods from one class to another. We group
the "inheritance concept" into two categories:
In the example below, the Car class (subclass) inherits the attributes and methods from
the Vehicle class (superclass):
Example
Car.java
class Vehicle {
protected String brand = "Ford";
public void honk() {
System.out.println("Tuut, tuut!");
}
}
40
Result:
Tuut, tuut!
Ford Mustang
As the name suggests access modifiers in Java helps to restrict the scope of a class,
constructor , variable , method or data member. There are four types of access modifiers
available in java:
• Default – No keyword required
• Private
• Protected
• Public
• Default: When no access modifier is specified for a class , method or data member –
It is said to be having the default access modifier by default.
• The data members, class or methods which are not declared using any access
modifiers i.e. having default access modifier are accessible only within the
same package.
In this example, we will create two packages and the classes in the packages will be
having the default access modifiers and we will try to access a class from one package
from a class of second package.
•
//Java program to illustrate default modifier
package p1;
41
//This class is having default access modifier
class GeekNew
{
public static void main(String args[])
{
//accessing class Geek from package p1
Geeks obj = new Geek();
obj.display();
}
}
Output:
Compile time error
• Private: The private access modifier is specified using the keyword private.
• The methods or data members declared as private are accessible only within
the class in which they are declared.
• Any other class of same package will not be able to access these members.
• Top level Classes or interface can not be declared as private because
• private means “only visible within the enclosing class”.
• protected means “only visible within the enclosing class and any
subclasses”
Hence these modifiers in terms of application to classes, they apply only to
nested classes and not on top level classes
In this example, we will create two classes A and B within same package p1. We will
declare a method in class A as private and try to access this method from class B and
see
//Java program to illustrate error while
//using class from different package with
//private modifier
package p1;
class A
{
private void display()
{
System.out.println("GeeksforGeeks");
}
}
class B
{
public static void main(String args[])
42
{
A obj = new A();
//trying to access private method of another class
obj.display();
}
}
Output:
error: display() has private access in A
obj.display();
• protected: The protected access modifier is specified using the keyword protected.
• The methods or data members declared as protected are accessible within
same package or sub classes in different package.
In this example, we will create two packages p1 and p2. Class A in p1 is made public,
to access it in p2. The method display in class A is protected and class B is inherited
from class A and this protected method is then accessed by creating an object of class
B.
filter_none
edit
play_arrow
brightness_4
//Java program to illustrate
//protected modifier
package p1;
//Class A
public class A
{
protected void display()
{
System.out.println("GeeksforGeeks");
}
}
filter_none
edit
play_arrow
brightness_4
//Java program to illustrate
//protected modifier
package p2;
43
import p1.*; //importing all classes in package p1
//Class B is subclass of A
class B extends A
{
public static void main(String args[])
{
B obj = new B();
obj.display();
}
}
Output:
GeeksforGeeks
• public: The public access modifier is specified using the keyword public.
• The public access modifier has the widest scope among all other access
modifiers.
• Classes, methods or data members which are declared as public are accessible
from every where in the program. There is no restriction on the scope of a
public data members.
44
GeeksforGeeks
Constructors in Java
Constructors are used to initialize the object’s state. Like methods, a constructor also
contains collection of statements(i.e. instructions) that are executed at time of Object
creation.
Need of Constructor
Think of a Box. If we talk about a box class then it will have some class variables (say
length, breadth, and height). But when it comes to creating its object(i.e Box will now exist
in computer’s memory), then can a box be there with no value defined for its dimensions.
The answer is no.
So constructors are used to assign values to the class variables at the time of object
creation, either explicitly done by the programmer or by Java itself (default constructor).
When is a Constructor called ?
Each time an object is created using new() keyword at least one constructor (it could be
default constructor) is invoked to assign initial values to the data members of the same
class.
A constructor is invoked at the time of object or instance creation. For Example:
class Geek
{
.......
// A Constructor
new Geek() {}
.......
}
45
• Access modifiers can be used in constructor declaration to control its access i.e which
other class can call the constructor.
Types of constructor
There are two type of constructor in Java:
• No-argument constructor: A constructor that has no parameter is known as default
constructor. If we don’t define a constructor in a class, then compiler creates default
constructor(with no arguments) for the class. And if we write a constructor with
arguments or no-arguments then the compiler does not create a default constructor.
Default constructor provides the default values to the object like 0, null, etc.
depending on the type.
filter_none
edit
play_arrow
brightness_4
// Java Program to illustrate calling a
// no-argument constructor
import java.io.*;
class Geek
{
int num;
String name;
class GFG
{
public static void main (String[] args)
{
// this would invoke default constructor.
Geek geek1 = new Geek();
46
Output :
Constructor called
null
0
• Parameterized Constructor: A constructor that has parameters is known as
parameterized constructor. If we want to initialize fields of the class with your own
values, then use a parameterized constructor.
filter_none
edit
play_arrow
brightness_4
// Java Program to illustrate calling of
// parameterized constructor.
import java.io.*;
class Geek
{
// data members of the class.
String name;
int id;
class GFG
{
public static void main (String[] args)
{
// this would invoke the parameterized constructor.
Geek geek1 = new Geek("adam", 1);
System.out.println("GeekName :" + geek1.name +
" and GeekId :" + geek1.id);
}
}
Output:
47
GeekName :adam and GeekId :1
Does constructor return any value?
There are no “return value” statements in constructor, but constructor returns current
class instance. We can write ‘return’ inside a constructor.
Constructor Overloading
Like methods, we can overload constructors for creating objects in different ways.
Compiler differentiates constructors on the basis of numbers of parameters, types of the
parameters and order of the parameters.
filter_none
edit
play_arrow
brightness_4
// Java Program to illustrate constructor overloading
// using same task (addition operation ) for different
// types of arguments.
import java.io.*;
class Geek
{
// constructor with one argument
Geek(String name)
{
System.out.println("Constructor with one " +
"argument - String : " + name);
}
48
}
class GFG
{
public static void main(String[] args)
{
// Creating the objects of the class named 'Geek'
// by passing different arguments
49
void funcB() {
System.out.println("This is class B");
}
}
class C extends B {
void funcC() {
System.out.println("This is class C");
}
}
public class Demo {
public static void main(String args[]) {
C obj = new C();
obj.funcA();
obj.funcB();
obj.funcC();
}
}
Output
This is class A
This is class B
This is class C
Java Polymorphism
Polymorphism means "many forms", and it occurs when we have many classes that are
related to each other by inheritance.
Like we specified in the previous chapter; Inheritance lets us inherit attributes and
methods from another class. Polymorphism uses those methods to perform different
tasks. This allows us to perform a single action in different ways.
For example, think of a superclass called Animal that has a method called animalSound().
Subclasses of Animals could be Pigs, Cats, Dogs, Birds - And they also have their own
implementation of an animal sound (the pig oinks, and the cat meows, etc.):
MyMainClass.java
class Animal {
public void animalSound() {
System.out.println("The animal makes a sound");
}
}
50
class Pig extends Animal {
public void animalSound() {
System.out.println("The pig says: wee wee");
}
}
class MyMainClass {
public static void main(String[] args) {
Animal myAnimal = new Animal();
Animal myPig = new Pig();
Animal myDog = new Dog();
myAnimal.animalSound();
myPig.animalSound();
myDog.animalSound();
}
}
Result:
The animal makes a sound
The pig says: wee wee
The dog says: bow wow
Java Pylymorphism
The polymorphism is the process of defining same method with different implementation.
That means creating multiple methods with different behaviors.
In java, polymorphism implemented using method overloading and method overriding.
Ad hoc polymorphism
The ad hoc polymorphism is a technique used to define the same method with different
implementations and different arguments. In a java programming language, ad hoc
polymorphism carried out with a method overloading concept.
In ad hoc polymorphism the method binding happens at the time of compilation. Ad hoc
polymorphism is also known as compile-time polymorphism. Every function call binded
with the respective overloaded method based on the arguments.
The ad hoc polymorphism implemented within the class only.
Let's look at the following example java code.
51
Example
import java.util.Arrays;
52
Pure polymorphism
The pure polymorphism is a technique used to define the same method with the same
arguments but different implementations. In a java programming language, pure
polymorphism carried out with a method overriding concept.
In pure polymorphism, the method binding happens at run time. Pure polymorphism is
also known as run-time polymorphism. Every function call binding with the respective
overridden method based on the object reference.
When a child class has a definition for a member function of the parent class, the parent
class function is said to be overridden.
The pure polymorphism implemented in the inheritance concept only.
Let's look at the following example java code.
Example
class ParentClass{
void showData() {
System.out.println("Inside ParentClass showData() method");
System.out.println("num = " + num);
}
void showData() {
System.out.println("Inside ChildClass showData() method");
System.out.println("num = " + num);
}
}
}
}
53
When we run this code, it produce the following output.
54
• //Java Program to demonstrate why we need method overriding
• //Here, we are calling the method of parent class with child
• //class object.
• //Creating a parent class
• class Vehicle{
• void run(){System.out.println("Vehicle is running");}
• }
• //Creating a child class
• class Bike extends Vehicle{
• public static void main(String args[]){
• //creating an instance of child class
• Bike obj = new Bike();
• //calling the method with child class instance
• obj.run();
• }
• }
Output:
Vehicle is running
Problem is that I have to provide a specific implementation of run() method in subclass
that is why we use method overriding.
55
Bike is running safely
Java method overriding is mostly used in Runtime Polymorphism which we will learn in next
pages.
//Java Program to demonstrate the real scenario of Java Method Overriding
//where three classes are overriding the method of a parent class.
//Creating a parent class.
class Bank{
int getRateOfInterest(){return 0;}
}
//Creating child classes.
class SBI extends Bank{
int getRateOfInterest(){return 8;}
}
56
}
}
Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9
forms of inheritance-
The inheritance concept used for the number of purposes in the java programming
language. One of the main purposes is substitutability. The substitutability means that
when a child class acquires properties from its parent class, the object of the parent class
may be substituted with the child class object. For example, if B is a child class of A,
anywhere we expect an instance of A we can use an instance of B.
The substitutability can achieve using inheritance, whether using extends or implements
keywords.
The following are the differnt forms of inheritance in java.
• Specialization
• Specification
• Construction
• Eextension
• Limitation
• Combination
Specialization
It is the most ideal form of inheritance. The subclass is a special case of the parent class. It
holds the principle of substitutability.
Specification
This is another commonly used form of inheritance. In this form of inheritance, the parent
class just specifies which methods should be available to the child class but doesn't
implement them. The java provides concepts like abstract and interfaces to support this
form of inheritance. It holds the principle of substitutability.
Construction
This is another form of inheritance where the child class may change the behavior defined
by the parent class (overriding). It does not hold the principle of substitutability.
Eextension
This is another form of inheritance where the child class may add its new properties. It
holds the principle of substitutability.
57
Limitation
This is another form of inheritance where the subclass restricts the inherited behavior. It
does not hold the principle of substitutability.
Combination
This is another form of inheritance where the subclass inherits properties from multiple
parent classes. Java does not support multiple inheritance type.
benefits of inheritance
• Inheritance helps in code reuse. The child class may use the code defined in the
parent class without re-writing it.
• Inheritance can save time and effort as the main code need not be written again.
• Inheritance provides a clear model structure which is easy to understand.
• An inheritance leads to less development and maintenance costs.
• With inheritance, we will be able to override the methods of the base class so that
the meaningful implementation of the base class method can be designed in the
derived class. An inheritance leads to less development and maintenance costs.
• In inheritance base class can decide to keep some data private so that it cannot be
altered by the derived class.
Costs of Inheritance
• Inheritance decreases the execution speed due to the increased time and effort it
takes, the program to jump through all the levels of overloaded classes.
• Inheritance makes the two classes (base and inherited class) get tightly coupled.
This means one cannot be used independently of each other.
• The changes made in the parent class will affect the behavior of child class too.
• The overuse of inheritance makes the program more complex.
UNIT – 2
Packages
Defining a Package
Packages are used in Java in order to prevent naming conflicts, to control access, to make
searching/locating and usage of classes, interfaces, enumerations and annotations easier,
etc.
A Package can be defined as a grouping of related types (classes, interfaces, enumerations
and annotations ) providing access protection and namespace management.
Some of the existing packages in Java are −
58
• java.lang − bundles the fundamental classes
• java.io − classes for input , output functions are bundled in this package
Programmers can define their own packages to bundle group of classes/interfaces, etc. It
is a good practice to group related classes implemented by you so that a programmer can
easily determine that the classes, interfaces, enumerations, and annotations are related.
Since the package creates a new namespace there won't be any name conflicts with names
in other packages. Using packages, it is easier to provide access control and it is also easier
to locate the related classes.
Creating a Package
While creating a package, you should choose a name for the package and include
a package statement along with that name at the top of every source file that contains the
classes, interfaces, enumerations, and annotation types that you want to include in the
package.
The package statement should be the first line in the source file. There can be only one
package statement in each source file, and it applies to all types in the file.
If a package statement is not used then the class, interfaces, enumerations, and annotation
types will be placed in the current default package.
To compile the Java programs with package statements, you have to use -d option as
shown below.
javac -d Destination_folder file_name.java
Then a folder with the given package name is created in the specified destination, and the
compiled class files will be placed in that folder.
Example
Let us look at an example that creates a package called animals. It is a good practice to use
names of packages with lower case letters to avoid any conflicts with the names of classes
and interfaces.
Following package example contains interface named animals −
/* File name : Animal.java */
package animals;
interface Animal {
public void eat();
public void travel();
}
Now, let us implement the above interface in the same package animals −
package animals;
/* File name : MammalInt.java */
59
public class MammalInt implements Animal {
You can execute the class file within the package and get the result as shown below.
Mammal eats
Mammal travels
Example
Here, a class named Boss is added to the payroll package that already contains Employee.
The Boss can then refer to the Employee class without using the payroll prefix, as
demonstrated by the following Boss class.
package payroll;
public class Boss {
public void payEmployee(Employee e) {
60
e.mailCheck();
}
}
What happens if the Employee class is not in the payroll package? The Boss class must
then use one of the following techniques for referring to a class in a different package.
• The fully qualified name of the class can be used. For example −
payroll.Employee
• The package can be imported using the import keyword and the wild card (*). For
example −
import payroll.*;
• The class itself can be imported using the import keyword. For example −
import payroll.Employee;
Note − A class file can contain any number of import statements. The import statements
must appear after the package statement and before the class declaration.
61
In general, a company uses its reversed Internet domain name for its package names.
Example − A company's Internet domain name is apple.com, then all its package names
would start with com.apple. Each component of the package name corresponds to a
subdirectory.
Example − The company had a com.apple.computers package that contained a Dell.java
source file, it would be contained in a series of subdirectories like this −
....\com\apple\computers\Dell.java
At the time of compilation, the compiler creates a different output file for each class,
interface and enumeration defined in it. The base name of the output file is the name of the
type, and its extension is .class.
For example −
// File Name: Dell.java
package com.apple.computers;
class Ups {
}
Now, compile this file as follows using -d option −
$javac -d . Dell.java
The files will be compiled as follows −
.\com\apple\computers\Dell.class
.\com\apple\computers\Ups.class
You can import all the classes or interfaces defined in \com\apple\computers\ as follows −
import com.apple.computers.*;
Like the .java source files, the compiled .class files should be in a series of directories that
reflect the package name. However, the path to the .class files does not have to be the same
as the path to the .java source files. You can arrange your source and class directories
separately, as −
<path-one>\sources\com\apple\computers\Dell.java
<path-two>\classes\com\apple\computers\Dell.class
By doing this, it is possible to give access to the classes directory to other programmers
without revealing your sources. You also need to manage source and class files in this
manner so that the compiler and the Java Virtual Machine (JVM) can find all the types your
program uses.
62
The full path to the classes directory, <path-two>\classes, is called the class path, and is
set with the CLASSPATH system variable. Both the compiler and the JVM construct the
path to your .class files by adding the package name to the class path.
Say <path-two>\classes is the class path, and the package name is com.apple.computers,
then the compiler and JVM will look for .class files in <path-two>\classes\com\apple\
computers.
A class path may include several paths. Multiple paths should be separated by a semicolon
(Windows) or colon (Unix). By default, the compiler and the JVM search the current
directory and the JAR file containing the Java platform classes so that these directories are
automatically in the class path.
In java, the package is a container of classes, sub-classes, interfaces, and sub-packages. The
class acts as a container of data and methods. So, the access modifier decides the
accessibility of class members across the different packages.
In java, the accessibility of the members of a class or interface depends on its access
specifiers. The following table provides information about the visibility of both data
members and methods.
63
• The protected members are accessible to every child class (same package or other
packages).
• The default members are accessible within the same package but not outside the
package.
Example
class ParentClass{
int a = 10;
public int b = 20;
protected int c = 30;
private int d = 40;
void showData() {
System.out.println("Inside ParentClass");
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
}
}
void accessData() {
System.out.println("Inside ChildClass");
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
//System.out.println("d = " + d); // private member can't be accessed
}
}
public class AccessModifiersExample {
64
When we run this code, it produce the following output.
Inside ParentClass
a = 10
b = 20
c = 30
d=40
Inside ChildClass
a=10
b=20
c=30
Import Package
Package is a collection of related classes. Java uses package to group related classes,
interfaces and sub-packages in any Java project.
We can assume package as a folder or a directory that is used to store similar files.
In Java, packages are used to avoid name conflicts and to control access of class, interface
and enumeration etc. Using package it becomes easier to locate the related classes and it
also provides a good structure for projects with hundreds of classes and other files.
Lets understand it by a simple example, Suppose, we have some math related classes and
interfaces then to collect them into a simple place, we have to create a package.
Built-in Package: math, util, lang, i/o etc are the example of built-in packages.
User-defined-package: Java package created by user to categorize their project's classes
and interface are known as user-defined packages.
Packages in java
package mypack;
public class employee
{
String empId;
String name;
}
The above statement will create a package woth name mypack in the project directory.
65
Java uses file system directories to store packages. For example the .java file for any class
you define to be part of mypack package must be stored in a directory called mypack.
//save as FirstProgram.java
package learnjava;
public class FirstProgram{
public static void main(String args[]) {
System.out.println("Welcome to package example");
}
}
How to compile Java programs inside packages?
This is just like compiling a normal java program. If you are not using any IDE, you need to
follow the steps given below to successfully compile your packages:
javac -d . FirstProgram.java
The -d switch specifies the destination where to put the generated class file. You can use
any directory name like d:/abc (in case of windows) etc. If you want to keep the package
within the same directory, you can use . (dot).
java learnjava.FirstProgram
After running the program, we will get “Welcome to package example” message to the
console. You can tally that with print statement used in the program.
66
How to import Java Package
To import java package into a class, we need to use java import keyword which is used to
access package and its classes into the java program.
Use import to access built-in and user-defined packages into your java source file so that
your class can refer to a class that is in another package by directly using its name.
There are 3 different ways to refer to any class that is present in a different package:
Example
In this example, we are creating a class A in package pack and in another class B, we are
accessing it while creating object of class A.
//save by A.java
package pack;
public class A {
public void msg() {
System.out.println("Hello");
}
}
//save by B.java
package mypack;
class B {
public static void main(String args[]) {
pack.A obj = new pack.A(); //using fully qualified name
obj.msg();
}
}
Hello
67
Import the Specific Class
Package can have many classes but sometimes we want to access only specific class in our
program in that case, Java allows us to specify class name along with package name. If we
use import packagename.classname statement then only the class with name classname in
the package will be available for use.
Example:
In this example, we created a class Demo stored into pack package and in another class
Test, we are accessing Demo class by importing package name with class name.
//save by Demo.java
package pack;
public class Demo {
public void msg() {
System.out.println("Hello");
}
}
//save by Test.java
package mypack;
import pack.Demo;
class Test {
public static void main(String args[]) {
Demo obj = new Demo();
obj.msg();
}
}
Hello
The import keyword is used to make the classes of another package accessible to the
current package.
Example :
In this example, we created a class First in learnjava package that access it in another class
Second by using import keyword.
//save by First.java
package learnjava;
public class First{
public void msg() {
68
System.out.println("Hello");
}
}
//save by Second.java
package Java;
import learnjava.*;
class Second {
public static void main(String args[]) {
First obj = new First();
obj.msg();
}
}
Hello
Interface in Java
An interface in Java is a blueprint of a class. It has static constants and abstract methods.
The interface in Java is a mechanism to achieve abstraction. There can be only abstract
methods in the Java interface, not method body. It is used to achieve abstraction and
multiple inheritance in Java.
In other words, you can say that interfaces can have abstract methods and variables. It
cannot have a method body.
Declaring Interfaces
The interface keyword is used to declare an interface. Here is a simple example to declare
an interface −
Example
Following is an example of an interface −
An interface is implicitly abstract. You do not need to use the abstract keyword while
declaring an interface.
69
Each method in an interface is also implicitly abstract, so the abstract keyword is not
needed.
Example
/* File name : Animal.java */
interface Animal {
public void eat();
public void travel();
}
Implementing an Interface
Like abstract classes, we cannot create objects of interfaces.
To use an interface, other classes must implement it. We use the implements keyword to
implement an interface.
class Main {
public static void main(String[] args) {
Rectangle r1 = new Rectangle();
r1.getArea(5, 6);
}
}
Output
70
Here, the Rectangle class implements Polygon. And, provides the implementation of the
getArea() method.
class Main {
public static void main(String[] args) {
ProgrammingLanguage language = new ProgrammingLanguage();
language.getName("Java");
}
}
Output
Here, the ProgrammingLanguage class implements the interface and provides the
implementation for the method.
interface A {
// members of A
}
interface B {
// members of B
}
class C implements A, B {
// abstract members of A
71
// abstract members of B
}
Extending an Interface
Similar to classes, interfaces can extend other interfaces. The extends keyword is used for
extending interfaces. For example,
interface Line {
// members of Line interface
}
// extending interface
interface Polygon extends Line {
// members of Polygon interface
// members of Line interface
}
Here, the Polygon interface extends the Line interface. Now, if any class implements
Polygon, it should provide implementations for all the abstract methods of both Line and
Polygon.
interface A {
...
}
interface B {
...
}
interface C extends A, B {
...
}
An interface which is declared inside another interface or class is called nested interface.
They are also known as inner interface. Since nested interface cannot be accessed directly,
the main purpose of using them is to resolve the namespace by grouping related interfaces
(or related interface and class) together. This way, we can only call the nested interface by
using outer class or outer interface name followed by dot( . ), followed by the interface
name.
Example: Entry interface inside Map interface is nested. Thus we access it by calling
Map.Entry.
Note:
72
Nested interfaces are static by default. You don’t have to mark them static explicitly as it
would be redundant.
Nested interfaces declared inside class can take any access modifier, however nested
interface declared inside interface is public implicitly.
Example 1: Nested interface declared inside another interface
interface MyInterfaceA{
void display();
interface MyInterfaceB{
void myMethod();
}
}
class NestedInterfaceDemo1
implements MyInterfaceA.MyInterfaceB{
public void myMethod(){
System.out.println("Nested interface method");
}
73
Nested interface method
Java IO Stream
Java performs I/O through Streams. A Stream is linked to a physical layer by java I/O
system to make input and output operation in java. In general, a stream means continuous
flow of data. Streams are clean way to deal with input/output without having every part of
your code understand the physical.
Java encapsulates Stream under java.io package. Java defines two types of streams. They
are,
1. Byte Stream : It provides a convenient means for handling input and output of byte.
2. Character Stream : It provides a convenient means for handling input and output of
characters. Character stream uses Unicode and therefore can be internationalized
These two abstract classes have several concrete classes that handle various devices such
as disk files, network connection etc.
74
BufferedOutputStream Used for Buffered Output Stream.
DataOutputStream An output stream that contain method for writing java standard data type
These classes define several key methods. Two most important are
75
These two abstract classes have several concrete classes that handle unicode character.
76
Writer Abstract class that define character stream output
Reading Characters
read() method is used with BufferedReader object to read characters. As this function
returns integer type value has we need to use typecasting to convert it into char type.
class CharRead
77
}
import java.io.*;
class MyInput
String text;
System.out.println(text);
78
String str;
while ((str=br.readLine())!=null)
{
System.out.println(str);
}
br.close();
fl.close();
}
catch(IOException e) {
e.printStackTrace();
}
}
}
The File class is an abstract representation of file and directory pathname. A pathname can
be either absolute or relative.
The File class have several methods for working with directories and files such as creating
new directories or files, deleting and renaming directories or files, listing the contents of a
directory etc.
79
Fields
constructors
Constructor Description
File(File parent, String child) It creates a new File instance from a parent
File(String parent, String child) It creates a new File instance from a parent
80
Useful Methods
Modifier Method Description
and Type
static File createTempFile It creates an empty file in the default temporary-file directory, u
(String prefix, and suffix to generate its name.
String suffix)
boolean canWrite() It tests whether the application can modify the file
boolean canExecute() It tests whether the application can execute the file
boolean canRead() It tests whether the application can read the file denoted by
boolean isDirectory() It tests whether the file denoted by this abstract pathname
is a directory.
boolean isFile() It tests whether the file denoted by this abstract pathname
is a normal file.
String getName() It returns the name of the file or directory denoted by this
abstract pathname.
81
parent, or null if this pathname does not name a parent
directory.
pathname.
String[] list(FilenameFil It returns an array of strings naming the files and directories
ter filter)
in the directory denoted by this abstract pathname that
try {
File file = new File("javaFile123.txt");
if (file.createNewFile()) {
System.out.println("New File is created!");
} else {
System.out.println("File already exists.");
}
82
} catch (IOException e) {
e.printStackTrace();
}
}
}
Output:
Output:
83
testFile1.txt
/home/Work/Project/File/testFile1.txt
true
/home/Work/Project/File/testFile1.txt Exists? true
Output:
"info.properties"
"info.properties".rtf
.DS_Store
.localized
Alok news
apache-tomcat-9.0.0.M19
apache-tomcat-9.0.0.M19.tar
bestreturn_org.rtf
BIODATA.pages
BIODATA.pdf
BIODATA.png
struts2jars.zip
workspace
84
Output:
FileWriter
85
public void write(String str,int off,int len)throws IOException – Writes a portion
of a string. Here off is offset from which to start writing characters and len is number
of character to write.
public void flush() throws IOException flushes the stream
public void close() throws IOException flushes the stream first and then closes the
writer.
Reading and writing take place character by character, which increases the
number of I/O operations and effects performance of the
system.BufferedWriter can be used along with FileWriter to improve speed of
execution.
Following program depicts how to create a text file using FileWriter
System.out.println("Writing successful");
//close the file
fw.close();
}
}
FileReader
FileReader is useful to read data in the form of characters from a ‘text’ file.
This class inherit from the InputStreamReader Class.
The constructors of this class assume that the default character encoding and the
default byte-buffer size are appropriate. To specify these values yourself, construct an
InputStreamReader on a FileInputStream.
FileReader is meant for reading streams of characters. For reading streams of raw
bytes, consider using a FileInputStream.
86
Constructors:
FileReader(File file) – Creates a FileReader , given the File to read from
FileReader(FileDescripter fd) – Creates a new FileReader , given the FileDescripter
to read from
FileReader(String fileName) – Creates a new FileReader , given the name of the file
to read from
Methods:
public int read () throws IOException – Reads a single character. This method will
block until a character is available, an I/O error occurs, or the end of the stream is
reached.
public int read(char[] cbuff) throws IOException – Reads characters into an array.
This method will block until some input is available, an I/O error occurs, or the end of
the stream is reached.
public abstract int read(char[] buff, int off, int len) throws IOException –Reads
characters into a portion of an array. This method will block until some input is
available, an I/O error occurs, or the end of the stream is reached.
Parameters:
cbuf – Destination buffer
off – Offset at which to start storing characters
len – Maximum number of characters to read
public void close() throws IOException closes the reader.
public long skip(long n) throws IOException –Skips characters. This method will
block until some characters are available, an I/O error occurs, or the end of the stream
is reached.
Parameters:
n – The number of characters to skip
Following program depicts how to read from the ‘text’ file using FileReader
87
catch (FileNotFoundException fe)
{
System.out.println("File not found");
}
Java - RandomAccessFile
This class is used for reading and writing to random access file. A random access file
behaves like a large array of bytes. There is a cursor implied to the array called file pointer,
by moving the cursor we do the read write operations. If end-of-file is reached before the
desired number of byte has been read than EOFException is thrown. It is a type of
IOException.
Constructor
Constructor Description
argument.
Method
Modifier and Method Method
Type
88
void close() It closes this random access file stream and releases
this file.
void seek(long It sets the file-pointer offset, measured from the beginning of this
pos)
file, at which the next read or write occurs.
void writeFloat(fl It converts the float argument to an int using the floatToIntBits
oat v)
method in class Float, and then writes that int value to the file as
void seek(long It sets the file-pointer offset, measured from the beginning of this
pos)
file, at which the next read or write occurs.
Example
1. import java.io.IOException;
89
2. import java.io.RandomAccessFile;
3.
4. public class RandomAccessFileExample {
5. static final String FILEPATH ="myFile.TXT";
6. public static void main(String[] args) {
7. try {
8. System.out.println(new String(readFromFile(FILEPATH, 0, 18)));
9. writeToFile(FILEPATH, "I love my country and my people", 31);
10. } catch (IOException e) {
11. e.printStackTrace();
12. }
13. }
14. private static byte[] readFromFile(String filePath, int position, int size)
15. throws IOException {
16. RandomAccessFile file = new RandomAccessFile(filePath, "r");
17. file.seek(position);
18. byte[] bytes = new byte[size];
19. file.read(bytes);
20. file.close();
21. return bytes;
22. }
23. private static void writeToFile(String filePath, String data, int position)
24. throws IOException {
25. RandomAccessFile file = new RandomAccessFile(filePath, "rw");
26. file.seek(position);
27. file.write(data.getBytes());
28. file.close();
29. }
30. }
The myFile.TXT contains text "This class is used for reading and writing to random access
file."
Next →← Prev
Java Console Class
The Java Console class is be used to get input from console. It provides methods to read
texts and passwords.
If you read password using Console class, it will not be displayed to the user.
The java.io.Console class is attached with system console internally. The Console class is
introduced since 1.5.
90
Let's see a simple example to read text from console.
1. String text=System.console().readLine();
2. System.out.println("Text is: "+text);
console.
String readLine(String fmt, Object... args) It provides a formatted prompt then reads the single
char[] readPassword(String fmt, Object... It provides a formatted prompt then reads the
args)
password that is not being displayed on the console.
Console format(String fmt, Object... args) It is used to write a formatted string to the console
output stream.
91
Console printf(String format, Object... It is used to write a string to the console output
args)
stream.
System class provides a static method console() that returns the singleton instance of
Console class.
1. Console c=System.console();
Output
92
5. System.out.println("Enter password: ");
6. char[] ch=c.readPassword();
7. String pass=String.valueOf(ch);//converting char array into string
8. System.out.println("Password is: "+pass);
9. }
10. }
Output
Enter password:
Password is: 123
Serialization in java
Java provides a mechanism, called object serialization where an object can be represented
as a sequence of bytes that includes the object's data as well as information about the
object's type and the types of data stored in the object.
After a serialized object has been written into a file, it can be read from the file and
deserialized that is, the type information and bytes that represent the object and its data
can be used to recreate the object in memory.
Most impressive is that the entire process is JVM independent, meaning an object can be
serialized on one platform and deserialized on an entirely different platform.
Classes ObjectInputStream and ObjectOutputStream are high-level streams that
contain the methods for serializing and deserializing an object.
The ObjectOutputStream class contains many write methods for writing various data
types, but one method in particular stands out −
public final void writeObject(Object x) throws IOException
The above method serializes an Object and sends it to the output stream. Similarly, the
ObjectInputStream class contains the following method for deserializing an object −
public final Object readObject() throws IOException, ClassNotFoundException
This method retrieves the next Object out of the stream and deserializes it. The return
value is Object, so you will need to cast it to its appropriate data type.
To demonstrate how serialization works in Java, I am going to use the Employee class that
we discussed early on in the book. Suppose that we have the following Employee class,
which implements the Serializable interface −
Example
public class Employee implements java.io.Serializable {
public String name;
public String address;
public transient int SSN;
93
public int number;
Serializing an Object
The ObjectOutputStream class is used to serialize an Object. The following SerializeDemo
program instantiates an Employee object and serializes it to a file.
When the program is done executing, a file named employee.ser is created. The program
does not generate any output, but study the code and try to determine what the program
is doing.
Note − When serializing an object to a file, the standard convention in Java is to give the
file a .ser extension.
Example
import java.io.*;
public class SerializeDemo {
try {
FileOutputStream fileOut =
new FileOutputStream("/tmp/employee.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(e);
out.close();
fileOut.close();
System.out.printf("Serialized data is saved in /tmp/employee.ser");
} catch (IOException i) {
i.printStackTrace();
94
}
}
}
Deserializing an Object
The following DeserializeDemo program deserializes the Employee object created in the
SerializeDemo program. Study the program and try to determine its output −
Example
import java.io.*;
public class DeserializeDemo {
System.out.println("Deserialized Employee...");
System.out.println("Name: " + e.name);
System.out.println("Address: " + e.address);
System.out.println("SSN: " + e.SSN);
System.out.println("Number: " + e.number);
}
}
This will produce the following result −
Output
Deserialized Employee...
Name: Reyan Ali
Address:Phokka Kuan, Ambehta Peer
SSN: 0
Number:101
95
What is Enumeration in Java?
Enumeration is basically a list of named constant. In Java, it defines a class type. It can
have constructors, methods and instance variables. It is created using the enum keyword.
By default, each enumeration constant is public, static and final. Even though enumeration
defines a class type and has constructors, you do not need to instantiate
an enum using the new variable. Enumeration variables are used and declared in the same
way as that of a primitive variable.
Or
The Enum in Java is a data type which contains a fixed set of constants.
It can be used for days of the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, and SATURDAY) , directions (NORTH, SOUTH, EAST, and WEST),
season (SPRING, SUMMER, WINTER, and AUTUMN or FALL), colors (RED, YELLOW, BLUE,
GREEN, WHITE, and BLACK) etc. According to the Java naming conventions, we should
have all constants in capital letters. So, we have enum constants in capital letters.
Java Enums can be thought of as classes which have a fixed set of constants (a variable that
does not change). The Java enum constants are static and final implicitly. It is available
since JDK 1.5.
Enums are used to create our own data type like classes. The enum data type (also known
as Enumerated Data Type) is used to define an enum in Java. Unlike C/C++, enum in Java is
more powerful. Here, we can define an enum either inside the class or outside the class.
Java Enum internally inherits the Enum class, so it cannot inherit any other class, but it can
implement many interfaces. We can have fields, constructors, methods, and main methods
in Java enum.
96
2. //defining the enum inside the class
3. public enum Season { WINTER, SPRING, SUMMER, FALL }
4. //main method
5. public static void main(String[] args) {
6. //traversing the enum
7. for (Season s : Season.values())
8. System.out.println(s);
9. }}
Output:
WINTER
SPRING
SUMMER
FALL
Let us see another example of Java enum where we are using value(), valueOf(), and
ordinal() methods of Java enum.
1. class EnumExample1{
2. //defining enum within class
3. public enum Season { WINTER, SPRING, SUMMER, FALL }
4. //creating the main method
5. public static void main(String[] args) {
6. //printing all enum
7. for (Season s : Season.values()){
8. System.out.println(s);
9. }
10. System.out.println("Value of WINTER is: "+Season.valueOf("WINTER"));
11. System.out.println("Index of WINTER is: "+Season.valueOf("WINTER").ordinal());
12. System.out.println("Index of SUMMER is: "+Season.valueOf("SUMMER").ordinal());
13.
14. }}
Output:
WINTER
SPRING
SUMMER
FALL
Value of WINTER is: WINTER
Index of WINTER is: 0
Index of SUMMER is: 2
Note: Java compiler internally adds values(), valueOf() and ordinal() methods within the
enum at compile time. It internally creates a static and final class for the enum.
97
What is the purpose of the values() method in the enum?
The Java compiler internally adds the values() method when it creates an enum. The
values() method returns an array containing all the values of the enum.
The Java compiler internally adds the valueOf() method when it creates an enum. The
valueOf() method returns the value of given constant enum.
The Java compiler internally adds the ordinal() method when it creates an enum. The
ordinal() method returns the index of the enum value.
Autoboxing
class AutoboxingExample1
{
public static void myMethod(Integer num){
98
System.out.println(num);
}
public static void main(String[] args) {
/* passed int (primitive type), it would be
* converted to Integer object at Runtime
*/
myMethod(2);
}
}
Output:
Java Generic
Java Generic methods and generic classes enable programmers to specify, with a single
method declaration, a set of related methods, or with a single class declaration, a set of
related types, respectively.
Generics also provide compile-time type safety that allows programmers to catch invalid
types at compile time.
Using Java Generic concept, we might write a generic method for sorting an array of
objects, then invoke the generic method with Integer arrays, Double arrays, String arrays
and so on, to sort the array elements.
Generic Methods
You can write a single generic method declaration that can be called with arguments of
different types. Based on the types of the arguments passed to the generic method, the
compiler handles each method call appropriately. Following are the rules to define
Generic Methods −
All generic method declarations have a type parameter section delimited by angle
brackets (< and >) that precedes the method's return type ( < E > in the next
example).
Each type parameter section contains one or more type parameters separated by
commas. A type parameter, also known as a type variable, is an identifier that
specifies a generic type name.
The type parameters can be used to declare the return type and act as placeholders
for the types of the arguments passed to the generic method, which are known as
actual type arguments.
A generic method's body is declared like that of any other method. Note that type
parameters can represent only reference types, not primitive types (like int, double
and char).
Example
Following example illustrates how we can print an array of different type using a single
Generic method −
public class GenericMethodTest {
// generic method printArray
99
public static < E > void printArray( E[] inputArray ) {
// Display array elements
for(E element : inputArray) {
System.out.printf("%s ", element);
}
System.out.println();
}
UNIT - III
EXCEPTION HANDLING
1. Exception Handling
2. Advantage of Exception Handling
3. Hierarchy of Exception classes
100
4. Types of Exception
5. Exception Example
6. Scenarios where an exception may occur
The Exception Handling in Java is one of the powerful mechanism to handle the runtime
errors so that normal flow of the application can be maintained.
In this page, we will learn about Java exceptions, its type and the difference between
checked and unchecked exceptions.
In Java, an exception is an event that disrupts the normal flow of the program. It is an object
which is thrown at runtime.
The core advantage of exception handling is to maintain the normal flow of the
application. An exception normally disrupts the normal flow of the application that is why
we use exception handling. Let's take a scenario:
statement 1;
statement 2;
statement 3;
statement 4;
statement 5;//exception occurs
statement 6;
statement 7;
statement 8;
statement 9;
statement 10;
Suppose there are 10 statements in your program and there occurs an exception at
statement 5, the rest of the code will not be executed i.e. statement 6 to 10 will not be
executed. If we perform exception handling, the rest of the statement will be executed. That
is why we use exception handling in Java.
101
The java.lang.Throwable class is the root class of Java Exception hierarchy which is
inherited by two subclasses: Exception and Error. A hierarchy of Java Exception classes are
given below:
There are mainly two types of exceptions: checked and unchecked. Here, an error is
considered as the unchecked exception. According to Oracle, there are three types of
exceptions:
1. Checked Exception
2. Unchecked Exception
3. Error
1) Checked Exception
The classes which directly inherit Throwable class except RuntimeException and Error are
known as checked exceptions e.g. IOException, SQLException etc. Checked exceptions are
checked at compile-time.
2) Unchecked Exception
The classes which inherit RuntimeException are known as unchecked exceptions e.g.
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.
Unchecked exceptions are not checked at compile-time, but they are checked at runtime.
102
3) Error
Keyword Description
The "try" keyword is used to specify a block where we should place exception
try code. The try block must be followed by either catch or finally. It means, we can't
use try block alone.
The "catch" block is used to handle the exception. It must be preceded by try
catch block which means we can't use catch block alone. It can be followed by finally
block later.
The "finally" block is used to execute the important code of the program. It is
finally
executed whether an exception is handled or not.
Let's see an example of Java Exception Handling where we using a try-catch statement to
handle the exception.
103
In the above example, 100/0 raises an ArithmeticException which is handled by a try-catch
block.
Catching Exceptions
A method catches an exception using a combination of the try and catch keywords. A
try/catch block is placed around the code that might generate an exception. Code within a
try/catch block is referred to as protected code, and the syntax for using try/catch looks
like the following −
Syntax
try {
// Protected code
} catch (ExceptionName e1) {
// Catch block
}
The code which is prone to exceptions is placed in the try block. When an exception
occurs, that exception occurred is handled by catch block associated with it. Every try
block should be immediately followed either by a catch block or finally block.
A catch statement involves declaring the type of exception you are trying to catch. If an
exception occurs in protected code, the catch block (or blocks) that follows the try is
checked. If the type of exception that occurred is listed in a catch block, the exception is
passed to the catch block much as an argument is passed into a method parameter.
Example
The following is an array declared with 2 elements. Then the code tries to access the
3rd element of the array which throws an exception.
// File Name : ExcepTest.java
import java.io.*;
104
Output
Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3
Out of the block
Syntax
try {
// Protected code
} catch (ExceptionType1 e1) {
// Catch block
} catch (ExceptionType2 e2) {
// Catch block
} catch (ExceptionType3 e3) {
// Catch block
}
The previous statements demonstrate three catch blocks, but you can have any number of
them after a single try. If an exception occurs in the protected code, the exception is
thrown to the first catch block in the list. If the data type of the exception thrown matches
ExceptionType1, it gets caught there. If not, the exception passes down to the second catch
statement. This continues until the exception either is caught or falls through all catches,
in which case the current method stops execution and the exception is thrown down to the
previous method on the call stack.
Example
Here is code segment showing how to use multiple try/catch statements.
try {
file = new FileInputStream(fileName);
x = (byte) file.read();
} catch (IOException i) {
i.printStackTrace();
return -1;
} catch (FileNotFoundException f) // Not valid! {
f.printStackTrace();
return -1;
}
105
throw ex;
Example
import java.io.*;
public class className {
Example
import java.io.*;
public class className {
106
Syntax
try {
// Protected code
} catch (ExceptionType1 e1) {
// Catch block
} catch (ExceptionType2 e2) {
// Catch block
} catch (ExceptionType3 e3) {
// Catch block
}finally {
// The finally block always executes.
}
Example
public class ExcepTest {
Output
Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3
First element value: 6
The finally statement is executed
Note the following −
A catch clause cannot exist without a try statement.
It is not compulsory to have finally clauses whenever a try/catch block is present.
The try block cannot be present without either catch clause or finally clause.
Any code cannot be present in between the try, catch, finally blocks.
The try-with-resources
107
Generally, when we use any resources like streams, connections, etc. we have to close
them explicitly using finally block. In the following program, we are reading data from a
file using FileReader and we are closing it using finally block.
Example
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
Syntax
try(FileReader fr = new FileReader("file path")) {
// use the resource
} catch () {
// body of catch
}
}
Following is the program that reads the data in a file using try-with-resources statement.
108
Example
import java.io.FileReader;
import java.io.IOException;
User-defined Exceptions
You can create your own exceptions in Java. Keep the following points in mind when
writing your own exception classes −
All exceptions must be a child of Throwable.
If you want to write a checked exception that is automatically enforced by the
Handle or Declare Rule, you need to extend the Exception class.
If you want to write a runtime exception, you need to extend the RuntimeException
class.
We can define our own Exception class as below −
class MyException extends Exception {
}
You just need to extend the predefined Exception class to create your own Exception.
These are considered to be checked exceptions. The
following InsufficientFundsException class is a user-defined exception that extends the
109
Exception class, making it a checked exception. An exception class is like any other class,
containing useful fields and methods.
Example
// File Name InsufficientFundsException.java
import java.io.*;
110
}
try {
System.out.println("\nWithdrawing $100...");
c.withdraw(100.00);
System.out.println("\nWithdrawing $600...");
c.withdraw(600.00);
} catch (InsufficientFundsException e) {
System.out.println("Sorry, but you are short $" + e.getAmount());
e.printStackTrace();
}
}
}
Compile all the above three files and run BankDemo. This will produce the following result
−
Output
Depositing $500...
Withdrawing $100...
Withdrawing $600...
Sorry, but you are short $200.0
InsufficientFundsException
at CheckingAccount.withdraw(CheckingAccount.java:25)
at BankDemo.main(BankDemo.java:13)
111
In java, there are two exception models. Java programming language has two models of
exception handling. The exception models that java suports are as follows.
Termination Model
Resumptive Model
Termination Model
In other words we can say that in termination model the error is so critical there is no way
to get back to where the exception occurred.
Resumptive Model
In resumptive model we may use a method call that want resumption like behavior. We
may also place the try block in a while loop that keeps re-entering the try block util the
result is satisfactory.
When a try catch block is present in another try block then it is called the nested try catch
block. Each time a try block does not have a catch handler for a particular exception, then
the catch blocks of parent try block are inspected for that exception, if match is found that
that catch block executes.
If neither catch block nor parent catch block handles exception then the system generated
message would be shown for the exception, similar to what we see when we don’t handle
exception.
Lets see the syntax first then we will discuss this with an example.
112
Syntax of Nested try Catch
....
//Main try block
try {
statement 1;
statement 2;
//try-catch block inside another try block
try {
statement 3;
statement 4;
//try-catch block inside nested try block
try {
statement 5;
statement 6;
}
catch(Exception e2) {
//Exception Message
}
}
catch(Exception e1) {
//Exception Message
}
}
//Catch of Main(parent) try block
catch(Exception e3) {
//Exception Message
}
....
Nested Try Catch Example
Here we have deep (two level) nesting which means we have a try-catch block inside a
nested try block. To make you understand better I have given the names to each try block
in comments like try-block2, try-block3 etc.
This is how the structure is: try-block3 is inside try-block2 and try-block2 is inside main
try-block, you can say that the main try-block is a grand parent of the try-block3. Refer the
explanation which is given at the end of this code.
class NestingDemo{
public static void main(String args[]){
//main try-block
try{
//try-block2
113
try{
//try-block3
try{
int arr[]= {1,2,3,4};
/* I'm trying to display the value of
* an element which doesn't exist. The
* code should throw an exception
*/
System.out.println(arr[10]);
}catch(ArithmeticException e){
System.out.print("Arithmetic Exception");
System.out.println(" handled in try-block3");
}
}
catch(ArithmeticException e){
System.out.print("Arithmetic Exception");
System.out.println(" handled in try-block2");
}
}
catch(ArithmeticException e3){
System.out.print("Arithmetic Exception");
System.out.println(" handled in main try-block");
}
catch(ArrayIndexOutOfBoundsException e4){
System.out.print("ArrayIndexOutOfBoundsException");
System.out.println(" handled in main try-block");
}
catch(Exception e5){
System.out.print("Exception");
System.out.println(" handled in main try-block");
}
}
}
Output:
114
Example 2: Nested try block
class Nest{
public static void main(String args[]){
//Parent try block
try{
//Child try block1
try{
System.out.println("Inside block1");
int b =45/0;
System.out.println(b);
}
catch(ArithmeticException e1){
System.out.println("Exception: e1");
}
//Child try block2
try{
System.out.println("Inside block2");
int b =45/0;
System.out.println(b);
}
catch(ArrayIndexOutOfBoundsException e2){
System.out.println("Exception: e2");
}
System.out.println("Just other statement");
}
catch(ArithmeticException e3){
System.out.println("Arithmetic Exception");
System.out.println("Inside parent try catch block");
}
catch(ArrayIndexOutOfBoundsException e4){
System.out.println("ArrayIndexOutOfBoundsException");
System.out.println("Inside parent try catch block");
}
catch(Exception e5){
System.out.println("Exception");
System.out.println("Inside parent try catch block");
}
System.out.println("Next statement..");
}
}
Output:
Inside block1
Exception: e1
115
Inside block2
Arithmetic Exception
Inside parent try catch block
Next statement..
Built-in Exceptions
Built-in exceptions are the exceptions which are available in Java libraries. These
exceptions are suitable to explain certain error situations. Below is the list of important
built-in exceptions in Java.
1. ArithmeticException
It is thrown when an exceptional condition has occurred in an arithmetic operation.
2. ArrayIndexOutOfBoundsException
It is thrown to indicate that an array has been accessed with an illegal index. The
index is either negative or greater than or equal to the size of the array.
3. ClassNotFoundException
This Exception is raised when we try to access a class whose definition is not found
4. FileNotFoundException
This Exception is raised when a file is not accessible or does not open.
5. IOException
It is thrown when an input-output operation failed or interrupted
6. InterruptedException
It is thrown when a thread is waiting , sleeping , or doing some processing , and it is
interrupted.
7. NoSuchFieldException
It is thrown when a class does not contain the field (or variable) specified
8. NoSuchMethodException
It is thrown when accessing a method which is not found.
9. NullPointerException
This exception is raised when referring to the members of a null object. Null
represents nothing
10. NumberFormatException
This exception is raised when a method could not convert a string into a numeric
format.
11. RuntimeException
This represents any exception which occurs during runtime.
12. StringIndexOutOfBoundsException
It is thrown by String class methods to indicate that an index is either negative or
greater than the size of the string
116
Arithmetic exception
Java
Output:
Java
Output:
NullPointerException..
117
StringIndexOutOfBound Exception
Java
Output:
StringIndexOutOfBoundsException
FileNotFound Exception
Java
118
}
}
Output:
File does not exist
NumberFormat Exception
Java
System.out.println(num);
} catch(NumberFormatException e) {
System.out.println("Number format exception");
}
}
}
Output:
Number format exception
ArrayIndexOutOfBounds Exception
Java
119
catch(ArrayIndexOutOfBoundsException e){
System.out.println ("Array Index is Out Of Bounds");
}
}
}
Output:
User-Defined Exceptions
Sometimes, the built-in exceptions in Java are not able to describe a certain situation. In
such cases, user can also create exceptions which are called ‘user-defined Exceptions’.
Following steps are followed for the creation of user-defined Exception.
The user should create an exception class as a subclass of Exception class. Since all the
exceptions are subclasses of Exception class, the user should also make his class a
subclass of it. This is done as:
MyException(){}
We can also create a parameterized constructor with a string as a parameter.
We can use this to store exception details. We can call super class(Exception)
constructor from this and send the string there.
MyException(String str)
{
super(str);
}
To raise exception of user-defined type, we need to create an object to his exception
class and throw it using throw clause, as:
120
The following program illustrates how to create own exception class MyException.
Details of account numbers, customer names, and balance amounts are taken in the
form of three arrays.
In main() method, the details are displayed using a for-loop. At this time, check is
done if in any account the balance amount is less than the minimum balance amount
to be apt in the account.
If it is so, then MyException is raised and a message is displayed “Balance amount is
less”.
Java
// default constructor
MyException() { }
// parametrized constructor
MyException(String str) { super(str); }
// write main()
public static void main(String[] args)
{
try {
// display the heading for the table
System.out.println("ACCNO" + "\t" + "CUSTOMER" +
"\t" + "BALANCE");
121
{
System.out.println(accno[i] + "\t" + name[i] +
"\t" + bal[i]);
catch (MyException e) {
e.printStackTrace();
}
}
}
RunTime Error
Java provides rich set of built-in exception classes like: ArithmeticException, IOException,
NullPointerException etc. all are available in the java.lang package and used in exception
handling. These exceptions are already set to trigger on pre-defined conditions such as
when you divide a number by zero it triggers ArithmeticException.
Apart from these classes, Java allows us to create our own exception class to provide own
exception implementation. These type of exceptions are called user-defined exceptions
or custom exceptions.
122
You can create your own exception simply by extending java Exception class. You can
define a constructor for your Exception (not compulsory) and you can override
the toString() function to display your customized message on catch. Lets see an example.
In this example, we are creating an exception class MyException that extends the Java
Exception class and
class Demo
{
static void sum(int a,int b) throws MyException
{
if(a<0)
{
throw new MyException(a); //calling constructor of user-defined exception class
}
else
{
System.out.println(a+b);
}
}
123
}
}
}
output
Lets take one more example to understand the custom exception. Here we created a class
ItemNotFound that extends the Exception class and helps to generate our own exception
implementation.
class Demo
{
static void find(int arr[], int item) throws ItemNotFound
{
boolean flag = false;
for (int i = 0; i < arr.length; i++) {
if(item == arr[i])
flag = true;
}
if(!flag)
{
throw new ItemNotFound("Item Not Found"); //calling constructor of user-defined
exception class
}
else
{
System.out.println("Item Found");
}
}
124
{
find(new int[]{12,25,45}, 10);
}
catch(ItemNotFound i)
{
System.out.println(i);
}
}
}
Output
multi-threaded
Thread Priorities
Every Java thread has a priority that helps the operating system determine the order in
which threads are scheduled.
Java thread priorities are in the range between MIN_PRIORITY (a constant of 1) and
MAX_PRIORITY (a constant of 10). By default, every thread is given priority
NORM_PRIORITY (a constant of 5).
Threads with higher priority are more important to a program and should be allocated
processor time before lower-priority threads. However, thread priorities cannot
guarantee the order in which threads execute and are very much platform dependent.
Step 1
As a first step, you need to implement a run() method provided by a Runnable interface.
This method provides an entry point for the thread and you will put your complete
business logic inside this method. Following is a simple syntax of the run() method −
public void run( )
Step 2
As a second step, you will instantiate a Thread object using the following constructor −
Thread(Runnable threadObj, String threadName);
Where, threadObj is an instance of a class that implements the Runnable interface
and threadName is the name given to the new thread.
126
Step 3
Once a Thread object is created, you can start it by calling start() method, which executes
a call to run( ) method. Following is a simple syntax of start() method −
void start();
Example
Here is an example that creates a new thread and starts running it −
class RunnableDemo implements Runnable {
private Thread t;
private String threadName;
127
RunnableDemo R2 = new RunnableDemo( "Thread-2");
R2.start();
}
}
This will produce the following result −
Output
Creating Thread-1
Starting Thread-1
Creating Thread-2
Starting Thread-2
Running Thread-1
Thread: Thread-1, 4
Running Thread-2
Thread: Thread-2, 4
Thread: Thread-1, 3
Thread: Thread-2, 3
Thread: Thread-1, 2
Thread: Thread-2, 2
Thread: Thread-1, 1
Thread: Thread-2, 1
Thread Thread-1 exiting.
Thread Thread-2 exiting.
Step 1
You will need to override run( ) method available in Thread class. This method provides
an entry point for the thread and you will put your complete business logic inside this
method. Following is a simple syntax of run() method −
public void run( )
Step 2
Once Thread object is created, you can start it by calling start() method, which executes a
call to run( ) method. Following is a simple syntax of start() method −
void start( );
Example
Here is the preceding program rewritten to extend the Thread −
class ThreadDemo extends Thread {
128
private Thread t;
private String threadName;
Output
Creating Thread-1
Starting Thread-1
129
Creating Thread-2
Starting Thread-2
Running Thread-1
Thread: Thread-1, 4
Running Thread-2
Thread: Thread-2, 4
Thread: Thread-1, 3
Thread: Thread-2, 3
Thread: Thread-1, 2
Thread: Thread-2, 2
Thread: Thread-1, 1
Thread: Thread-2, 1
Thread Thread-1 exiting.
Thread Thread-2 exiting.
Thread Methods
Following is the list of important methods available in the Thread class.
130
A parameter of true denotes this Thread as a daemon thread.
The previous methods are invoked on a particular Thread object. The following methods
in the Thread class are static. Invoking one of the static methods performs the operation
on the currently running thread.
131
Returns a reference to the currently running thread, which is the thread that invokes this
method.
Example
The following ThreadClassDemo program demonstrates some of these methods of the
Thread class. Consider a class DisplayMessage which implements Runnable −
// File Name : DisplayMessage.java
// Create a thread to implement Runnable
132
guess = (int) (Math.random() * 100 + 1);
System.out.println(this.getName() + " guesses " + guess);
counter++;
} while(guess != number);
System.out.println("** Correct!" + this.getName() + "in" + counter + "guesses.**");
}
}
Following is the main program, which makes use of the above-defined classes −
// File Name : ThreadClassDemo.java
public class ThreadClassDemo {
System.out.println("Starting thread3...");
Thread thread3 = new GuessANumber(27);
thread3.start();
try {
thread3.join();
} catch (InterruptedException e) {
System.out.println("Thread interrupted.");
}
System.out.println("Starting thread4...");
Thread thread4 = new GuessANumber(75);
thread4.start();
System.out.println("main() is ending...");
}
}
This will produce the following result. You can try this example again and again and you
will get a different result every time.
133
Output
Starting hello thread...
Starting goodbye thread...
Hello
Hello
Hello
Hello
Hello
Hello
Goodbye
Goodbye
Goodbye
Goodbye
Goodbye
.......
Thread Synchronization
When we start two or more threads within a program, there may be a situation when
multiple threads try to access the same resource and finally they can produce unforeseen
result due to concurrency issues. For example, if multiple threads try to write within a
same file then they may corrupt the data because one of the threads can override data or
while one thread is opening the same file at the same time another thread might be closing
the same file.
So there is a need to synchronize the action of multiple threads and make sure that only
one thread can access the resource at a given point in time. This is implemented using a
concept called monitors. Each object in Java is associated with a monitor, which a thread
can lock or unlock. Only one thread at a time may hold a lock on a monitor.
Java programming language provides a very handy way of creating threads and
synchronizing their task by using synchronized blocks. You keep shared resources within
this block. Following is the general form of the synchronized statement −
Syntax
synchronized(objectidentifier) {
// Access shared variables and other shared resources
}
Here, the objectidentifier is a reference to an object whose lock associates with the
monitor that the synchronized statement represents. Now we are going to see two
examples, where we will print a counter using two different threads. When threads are
not synchronized, they print counter value which is not in sequence, but when we print
counter by putting inside synchronized() block, then it prints counter very much in
sequence for both the threads.
134
Multithreading Example without Synchronization
Here is a simple example which may or may not print counter value in sequence and every
time we run it, it produces a different result based on CPU availability to a thread.
Example
class PrintDemo {
public void printCount() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("Counter --- " + i );
}
} catch (Exception e) {
System.out.println("Thread interrupted.");
}
}
}
135
ThreadDemo T1 = new ThreadDemo( "Thread - 1 ", PD );
ThreadDemo T2 = new ThreadDemo( "Thread - 2 ", PD );
T1.start();
T2.start();
Output
Starting Thread - 1
Starting Thread - 2
Counter --- 5
Counter --- 4
Counter --- 3
Counter --- 5
Counter --- 2
Counter --- 1
Counter --- 4
Thread Thread - 1 exiting.
Counter --- 3
Counter --- 2
Counter --- 1
Thread Thread - 2 exiting.
Example
class PrintDemo {
public void printCount() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("Counter --- " + i );
}
} catch (Exception e) {
136
System.out.println("Thread interrupted.");
}
}
}
T1.start();
T2.start();
137
} catch ( Exception e) {
System.out.println("Interrupted");
}
}
}
This produces the same result every time you run this program −
Output
Starting Thread - 1
Starting Thread - 2
Counter --- 5
Counter --- 4
Counter --- 3
Counter --- 2
Counter --- 1
Thread Thread - 1 exiting.
Counter --- 5
Counter --- 4
Counter --- 3
Counter --- 2
Counter --- 1
Thread Thread - 2 exiting.
If you are aware of interprocess communication then it will be easy for you to understand
interthread communication. Interthread communication is important when you develop
an application where two or more threads exchange some information.
There are three simple methods and a little trick which makes thread communication
possible. All the three methods are listed below −
138
Wakes up all the threads that called wait( ) on the same object.
These methods have been implemented as final methods in Object, so they are available in
all the classes. All three methods can be called only from within a synchronized context.
Example
This examples shows how two threads can communicate
using wait() and notify() method. You can create a complex system using the same
concept.
class Chat {
boolean flag = false;
System.out.println(msg);
flag = false;
notify();
}
}
139
public T1(Chat m1) {
this.m = m1;
new Thread(this, "Question").start();
}
140
Differences between thread-based multitasking and process-based multitasking,
Java
BASIS FOR
PROCESS THREAD
COMPARISON
Address Space Every process has its separate All the threads of a process share
address space. the same address space
cooperatively as that of a
process.
Components A process has its own address A thread has its own register,
space, global variables, signal state, stack, program counter.
handlers, open files, child
processes, accounting
information.
141
BASIS FOR
PROCESS THREAD
COMPARISON
Example You are working on text editor it You are printing a file from text
refers to the execution of a editor while working on it that
process. resembles the execution of a
thread in the process.
UNIT – IV
Collections in Java
Java Collections can achieve all the operations that you perform on a data such as
searching, sorting, insertion, manipulation, and deletion.
Java Collection means a single unit of objects. Java Collection framework provides many
interfaces (Set, List, Queue, Deque) and classes (ArrayList,
Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet).
142
What is Collection framework
The Collection framework represents a unified architecture for storing and manipulating a
group of objects. It has:
There are many methods declared in the Collection interface. They are as follows:
7 public int size() It returns the total number of elements in the collection.
8 public void clear() It removes the total number of elements from the
143
collection.
13 public <T> T[] toArray(T[] a) It converts collection into array. Here, the runtime
16 default Stream<E> stream() It returns a sequential Stream with the collection as its
source.
19 public int hashCode() It returns the hash code number of the collection.
Collections in Java
144
2. Hierarchy of Collection Framework
3. Collection interface
4. Iterator interface
The Collection in Java is a framework that provides an architecture to store and manipulate the gr
Java Collections can achieve all the operations that you perform on a data such as searching, sorting
deletion.
Java Collection means a single unit of objects. Java Collection framework provides many interfaces (
classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet).
The Collection framework represents a unified architecture for storing and manipulating a group of
Do You Know?
o What are the two ways to iterate the elements of a collection?
o What is the difference between ArrayList and LinkedList classes in collection framework?
o What is the difference between ArrayList and Vector classes in collection framework?
o What is the difference between HashSet and HashMap classes in collection framework?
o What is the difference between HashMap and Hashtable class?
o What is the difference between Iterator and Enumeration interface in collection framework?
o How can we sort the elements of an object? What is the difference between Comparable and
Comparator interfaces?
145
o What is the difference between Java collection and Java collections?
Let us see the hierarchy of Collection framework. The java.util package contains all the classes and
framework.
There are many methods declared in the Collection interface. They are as follows:
146
c) elements in the invoking collection.
the collection.
8 public void clear() It removes the total number of elements from the
1 public <T> T[] toArray(T[] a) It converts collection into array. Here, the
3
147
runtime type of the returned array is that of the
specified array.
1 public int hashCode() It returns the hash code number of the collection
9
Iterator interface
Iterator interface provides the facility of iterating the elements in a forward direction only.
There are only three methods in the Iterator interface. They are:
1 public boolean hasNext() It returns true if the iterator has more elements othe
2 public Object next() It returns the element and moves the cursor pointer
148
3 public void remove() It removes the last elements returned by the iterator
Iterable Interface
The Iterable interface is the root interface for all the collection classes. The Collection interface exte
therefore all the subclasses of Collection interface also implement the Iterable interface.
1. Iterator<T> iterator()
Collection Interface
The Collection interface is the interface which is implemented by all the classes in the collection fra
that every collection will have. In other words, we can say that the Collection interface builds the fo
framework depends.
Some of the methods of Collection interface are Boolean add ( Object obj), Boolean addAll ( Collectio
implemented by all the subclasses of Collection interface.
List Interface
List interface is the child interface of Collection interface. It inhibits a list type data structure in whi
collection of objects. It can have duplicate values.
List interface is implemented by the classes ArrayList, LinkedList, Vector, and Stack.
There are various methods in List interface that can be used to insert, delete, and access the
elements from the list.
The classes that implement the List interface are given below.
149
ArrayList
The ArrayList class implements the List interface. It uses a dynamic array to store the
duplicate element of different data types. The ArrayList class maintains the insertion order
and is non-synchronized. The elements stored in the ArrayList class can be randomly
accessed. Consider the following example.
1. import java.util.*;
2. class TestJavaCollection1{
3. public static void main(String args[]){
4. ArrayList<String> list=new ArrayList<String>();//Creating arraylist
5. list.add("Ravi");//Adding object in arraylist
6. list.add("Vijay");
7. list.add("Ravi");
8. list.add("Ajay");
9. //Traversing list through Iterator
10. Iterator itr=list.iterator();
11. while(itr.hasNext()){
12. System.out.println(itr.next());
13. }
14. }
15. }
Output:
Ravi
Vijay
Ravi
Ajay
LinkedList
LinkedList implements the Collection interface. It uses a doubly linked list internally to
store the elements. It can store the duplicate elements. It maintains the insertion order and
is not synchronized. In LinkedList, the manipulation is fast because no shifting is required.
1. import java.util.*;
2. public class TestJavaCollection2{
3. public static void main(String args[]){
4. LinkedList<String> al=new LinkedList<String>();
5. al.add("Ravi");
6. al.add("Vijay");
7. al.add("Ravi");
8. al.add("Ajay");
150
9. Iterator<String> itr=al.iterator();
10. while(itr.hasNext()){
11. System.out.println(itr.next());
12. }
13. }
14. }
Output:
Ravi
Vijay
Ravi
Ajay
Vector
Vector uses a dynamic array to store the data elements. It is similar to ArrayList. However,
It is synchronized and contains many methods that are not the part of Collection
framework.
1. import java.util.*;
2. public class TestJavaCollection3{
3. public static void main(String args[]){
4. Vector<String> v=new Vector<String>();
5. v.add("Ayush");
6. v.add("Amit");
7. v.add("Ashish");
8. v.add("Garima");
9. Iterator<String> itr=v.iterator();
10. while(itr.hasNext()){
11. System.out.println(itr.next());
12. }
13. }
14. }
Output:
Ayush
Amit
Ashish
Garima
151
Stack
The stack is the subclass of Vector. It implements the last-in-first-out data structure, i.e.,
Stack. The stack contains all of the methods of Vector class and also provides its methods
like boolean push(), boolean peek(), boolean push(object o), which defines its properties.
1. import java.util.*;
2. public class TestJavaCollection4{
3. public static void main(String args[]){
4. Stack<String> stack = new Stack<String>();
5. stack.push("Ayush");
6. stack.push("Garvit");
7. stack.push("Amit");
8. stack.push("Ashish");
9. stack.push("Garima");
10. stack.pop();
11. Iterator<String> itr=stack.iterator();
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }
Output:
Ayush
Garvit
Amit
Ashish
Queue Interface
Queue interface maintains the first-in-first-out order. It can be defined as an ordered list
that is used to hold the elements which are about to be processed. There are various
classes like PriorityQueue, Deque, and ArrayDeque which implements the Queue interface.
There are various classes that implement the Queue interface, some of them are given
below.
152
PriorityQueue
The PriorityQueue class implements the Queue interface. It holds the elements or objects
which are to be processed by their priorities. PriorityQueue doesn't allow null values to be
stored in the queue.
1. import java.util.*;
2. public class TestJavaCollection5{
3. public static void main(String args[]){
4. PriorityQueue<String> queue=new PriorityQueue<String>();
5. queue.add("Amit Sharma");
6. queue.add("Vijay Raj");
7. queue.add("JaiShankar");
8. queue.add("Raj");
9. System.out.println("head:"+queue.element());
10. System.out.println("head:"+queue.peek());
11. System.out.println("iterating the queue elements:");
12. Iterator itr=queue.iterator();
13. while(itr.hasNext()){
14. System.out.println(itr.next());
15. }
16. queue.remove();
17. queue.poll();
18. System.out.println("after removing two elements:");
19. Iterator<String> itr2=queue.iterator();
20. while(itr2.hasNext()){
21. System.out.println(itr2.next());
22. }
23. }
24. }
Output:
head:Amit Sharma
head:Amit Sharma
iterating the queue elements:
Amit Sharma
Raj
JaiShankar
Vijay Raj
after removing two elements:
Raj
153
Vijay Raj
Deque Interface
Deque interface extends the Queue interface. In Deque, we can remove and add the
elements from both the side. Deque stands for a double-ended queue which enables us to
perform the operations at both the ends.
ArrayDeque
ArrayDeque class implements the Deque interface. It facilitates us to use the Deque. Unlike
queue, we can add or delete the elements from both the ends.
ArrayDeque is faster than ArrayList and Stack and has no capacity restrictions.
1. import java.util.*;
2. public class TestJavaCollection6{
3. public static void main(String[] args) {
4. //Creating Deque and adding elements
5. Deque<String> deque = new ArrayDeque<String>();
6. deque.add("Gautam");
7. deque.add("Karan");
8. deque.add("Ajay");
9. //Traversing elements
10. for (String str : deque) {
11. System.out.println(str);
12. }
13. }
14. }
Output:
Gautam
Karan
Ajay
Set Interface
Set Interface in Java is present in java.util package. It extends the Collection interface. It
represents the unordered set of elements which doesn't allow us to store the duplicate
154
items. We can store at most one null value in Set. Set is implemented by HashSet,
LinkedHashSet, and TreeSet.
HashSet
HashSet class implements Set Interface. It represents the collection that uses a hash table
for storage. Hashing is used to store the elements in the HashSet. It contains unique items.
1. import java.util.*;
2. public class TestJavaCollection7{
3. public static void main(String args[]){
4. //Creating HashSet and adding elements
5. HashSet<String> set=new HashSet<String>();
6. set.add("Ravi");
7. set.add("Vijay");
8. set.add("Ravi");
9. set.add("Ajay");
10. //Traversing elements
11. Iterator<String> itr=set.iterator();
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }
Output:
Vijay
Ravi
Ajay
LinkedHashSet
155
1. import java.util.*;
2. public class TestJavaCollection8{
3. public static void main(String args[]){
4. LinkedHashSet<String> set=new LinkedHashSet<String>();
5. set.add("Ravi");
6. set.add("Vijay");
7. set.add("Ravi");
8. set.add("Ajay");
9. Iterator<String> itr=set.iterator();
10. while(itr.hasNext()){
11. System.out.println(itr.next());
12. }
13. }
14. }
Output:
Ravi
Vijay
Ajay
SortedSet Interface
SortedSet is the alternate of Set interface that provides a total ordering on its elements. The
elements of the SortedSet are arranged in the increasing (ascending) order. The SortedSet
provides the additional methods that inhibit the natural ordering of the elements.
TreeSet
Java TreeSet class implements the Set interface that uses a tree for storage. Like HashSet,
TreeSet also contains unique elements. However, the access and retrieval time of TreeSet is
quite fast. The elements in TreeSet stored in ascending order.
1. import java.util.*;
2. public class TestJavaCollection9{
3. public static void main(String args[]){
4. //Creating and adding elements
5. TreeSet<String> set=new TreeSet<String>();
6. set.add("Ravi");
7. set.add("Vijay");
156
8. set.add("Ravi");
9. set.add("Ajay");
10. //traversing elements
11. Iterator<String> itr=set.iterator();
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }
Output:
Ajay
Ravi
Vijay
The Map interface present in java.util package represents a mapping between a key and a
value. The Map interface is not a subtype of the Collection interface. Therefore it behaves
a bit differently from the rest of the collection types. A map contains unique keys.
Example:
import java.util.*;
class HashMapDemo {
public static void main(String args[])
{
157
Map<String, Integer> hm
= new HashMap<String, Integer>();
Output:
a:100
b:200
c:300
d:400
Method 1: One obvious approach is to write our own sort() function using one of the
standard algorithms. This solution requires rewriting the whole sorting code for different
criteria like Roll No. and Name.
Method 2: Using comparator interface- Comparator interface is used to order the objects
of a user-defined class. This interface is present in java.util package and contains 2
methods compare(Object obj1, Object obj2) and equals(Object element). Using a
comparator, we can sort the elements based on data members. For instance, it may be on
roll no, name, age, or anything else.
Method of Collections class for sorting List elements is used to sort the elements of List by
the given comparator.
158
// To sort a given list. ComparatorClass must implement
// Comparator interface.
public void sort(List list, ComparatorClass c)
How does Collections.Sort() work?
Internally the Sort method does call Compare method of the classes it is sorting. To
compare two elements, it asks “Which is greater?” Compare method returns -1, 0, or 1 to
say if it is less than, equal, or greater to the other. It uses this result to then determine if
they should be swapped for their sort.
Working Program:
Java
// interface
import java.io.*;
import java.lang.*;
import java.util.*;
// Constructor
public Student(int rollno, String name, String address)
{
this.rollno = rollno;
this.name = name;
this.address = address;
}
159
public int compare(Student a, Student b)
{
return a.rollno - b.rollno;
}
}
// Driver class
class Main {
public static void main(String[] args)
{
ArrayList<Student> ar = new ArrayList<Student>();
ar.add(new Student(111, "bbbb", "london"));
ar.add(new Student(131, "aaaa", "nyc"));
ar.add(new Student(121, "cccc", "jaipur"));
System.out.println("Unsorted");
for (int i = 0; i < ar.size(); i++)
System.out.println(ar.get(i));
System.out.println("\nSorted by rollno");
for (int i = 0; i < ar.size(); i++)
System.out.println(ar.get(i));
System.out.println("\nSorted by name");
for (int i = 0; i < ar.size(); i++)
System.out.println(ar.get(i));
}
}
Output
Unsorted
160
111 bbbb london
131 aaaa nyc
121 cccc jaipur
Sorted by rollno
111 bbbb london
121 cccc jaipur
131 aaaa nyc
Sorted by name
131 aaaa nyc
111 bbbb london
121 cccc jaipur
By changing the return value inside the compare method, you can sort in any order that
you wish to. Eg. for descending order just change the positions of ‘a’ and ‘b’ in the above
compare method.
Sort collection by more than one field:
In previous articles, we have discussed how to sort the list of objects on the basis of a
single field using Comparable and Comparator interface But, what if we have a
requirement to sort ArrayList objects in accordance with more than one fields like firstly,
sort according to the student name and secondly, sort according to student age.
Below is the implementation of the above approach:
Java
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
class Student {
161
// instance member variables
String Name;
int Age;
// parameterized constructor
public Student(String Name, Integer Age)
{
this.Name = Name;
this.Age = Age;
}
@Override
public int compare(Student customer1,
Student customer2)
{
// for comparison
int NameCompare = customer1.getName().compareTo(
customer2.getName());
int AgeCompare = customer1.getAge().compareTo(
customer2.getAge());
// 2-level comparison
return (NameCompare == 0) ? AgeCompare
: NameCompare;
}
162
}
System.out.println("Before Sorting:\n");
while (custIterator.hasNext()) {
System.out.println(custIterator.next());
}
163
}
Output
Before Sorting:
Customer{Name=Ajay, Age=27}
Customer{Name=Sneha, Age=23}
Customer{Name=Simran, Age=37}
Customer{Name=Ajay, Age=22}
Customer{Name=Ajay, Age=29}
Customer{Name=Sneha, Age=22}
After Sorting:
Customer{Name=Ajay, Age=22}
Customer{Name=Ajay, Age=27}
Customer{Name=Ajay, Age=29}
Customer{Name=Simran, Age=37}
Customer{Name=Sneha, Age=22}
Customer{Name=Sneha, Age=23}
164
Sr.No. Method & Description
165
Returns the maximum element in c as determined by comp.
166
Shuffles (i.e., randomizes) the elements in the list by using r as a source of random numbers.
167
Returns a thread-safe map backed by m.
168
Example
Following is an example, which demonstrates various algorithms.
import java.util.*;
public class AlgorithmsDemo {
// Get iterator
Iterator li = ll.iterator();
System.out.print("List sorted in reverse: ");
while(li.hasNext()) {
System.out.print(li.next() + " ");
}
System.out.println();
Collections.shuffle(ll);
while(li.hasNext()) {
System.out.print(li.next() + " ");
}
System.out.println();
System.out.println("Minimum: " + Collections.min(ll));
System.out.println("Maximum: " + Collections.max(ll));
}
}
This will produce the following result −
169
Output
List sorted in reverse: 20 8 -8 -20
List shuffled: 20 -20 8 -8
Minimum: -20
Maximum: 20
Early version of java did not include the Collections framework. It only defined several
classes and interfaces that provide methods for storing objects. When Collections
framework were added in J2SE 1.2, the original classes were reengineered to support the
collection interface. These classes are also known as Legacy classes. All legacy classes and
interface were redesign by JDK 5 to support Generics. In general, the legacy classes are
supported because there is still some code that uses them.
1. Dictionary
2. HashTable
3. Properties
4. Stack
5. Vector
Enumeration interface
3. However, some legacy classes such as Vector and Properties defines several
method in which Enumeration interface is used.
boolean hasMoreElements() //It returns true while there are still more elements to
extract,
and returns false when all the elements have been enumerated.
170
Object nextElement() //It returns the next object in the enumeration i.e. each call to
nextElement() method
enumeration is complete.
Vector class
2. There are two differences between Vector and ArrayList. First, Vector is
synchronized while ArrayList is not, and Second, it contains many legacy methods
that are not part of the Collections Framework.
3. With the release of JDK 5, Vector also implements Iterable. This means that Vector is
fully compatible with collections, and a Vector can have its contents iterated by the
for-each loop.
5. Vector() //This creates a default vector, which has an initial size of 10.
6.
7. Vector(int size) //This creates a vector whose initial capacity is specified by size.
8.
9. Vector(int size, int incr) //This creates a vector whose initial capacity is specified by
size and whose
10. increment is specified by incr. The increment specifies the number of elements to
allocate each time
12.
171
Vector defines several legacy methods. Lets see some important legacy methods defined
by Vector class.
Method Description
Example of Vector
import java.util.*;
public class Test
{
public static void main(String[] args)
{
Vector<Integer> ve = new Vector<Integer>();
ve.add(10);
ve.add(20);
ve.add(30);
ve.add(40);
ve.add(50);
ve.add(60);
Enumeration<Integer> en = ve.elements();
while(en.hasMoreElements())
{
System.out.println(en.nextElement());
}
172
}
10
20
30
40
50
60
Hashtable class
2. There is one more difference between HashMap and Hashtable that is Hashtable is
synchronized while HashMap is not.
5. Hashtable(int size) //This creates a hash table that has an initial size specified by
size.
6. Hashtable(int size, float fillratio) //This creates a hash table that has an initial size
specified by size
7. and a fill ratio specified by fillRatio. This ratio must be between 0.0 and 1.0, and it
determines how full
8. the hash table can be before it is resized upward. Specifically, when the number of
elements is greater
9. than the capacity of the hash table multiplied by its fill ratio, the hash table is
expanded.
173
11. Hashtable(Map< ? extends K, ? extends V> m) //This creates a hash table that is
initialized with the
12. elements in m. The capacity of the hash table is set to twice the number of elements
in m.
Example of Hashtable
import java.util.*;
class HashTableDemo
{
public static void main(String args[])
{
Hashtable<String,Integer> ht = new Hashtable<String,Integer>();
ht.put("a",new Integer(100));
ht.put("b",new Integer(200));
ht.put("c",new Integer(300));
ht.put("d",new Integer(400));
Set st = ht.entrySet();
Iterator itr=st.iterator();
while(itr.hasNext())
{
Map.Entry m=(Map.Entry)itr.next();
System.out.println(itr.getKey()+" "+itr.getValue());
}
}
}
a 100
b 200
c 300
d 400
Hashtable HashMap
174
Because of Thread-safe, Hashtable is
HashMap works faster.
slower than HashMap
Neither key nor values can be null Both key and values can be null
Order of table remain constant over does not guarantee that order of map
time. will remain constant over time.
Properties class
2. It is used to maintain list of value in which both key and value are String
5.
7. In Properties class, you can specify a default property that will be returned if no
value is associated with a certain key.
175
Example of Properties class
import java.util.*;
Stack class
4. If you want to put an object on the top of the stack, call push() method. If you want
to remove and return the top element, call pop() method. An EmptyStackException
is thrown if you call pop() method when the invoking stack is empty.
176
You can use peek() method to return, but not remove, the top object. The empty() method
returns true if nothing is on the stack. The search() method determines whether an object
exists on the stack and returns the number of pops that are required to bring it to the top of
the stack.
Example of Stack
import java.util.*;
class StackDemo {
public static void main(String args[]) {
Stack st = new Stack();
st.push(11);
st.push(22);
st.push(33);
st.push(44);
st.push(55);
Enumeration e1 = st.elements();
while(e1.hasMoreElements())
System.out.print(e1.nextElement()+" ");
st.pop();
st.pop();
Enumeration e2 = st.elements();
while(e2.hasMoreElements())
System.out.print(e2.nextElement()+" ");
}
}
11 22 33 44 55
After popping out two elements
11 22 33
Dictionary class
We already discussed about some of the utility classes in the earlier topic. In this section we
emphasize on String tokenizer class, time zone class, currency class etc. We’ll also discuss
about Formatter class which gives support for alignment as well as layout justification and
scanner class which enables a user to read values of various types. We’ll also explain what
java utility subpackages are.
The set of delimiters (the characters that separate tokens) may be specified either at
creation time or on a per-token basis.
Constructor Description
178
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:
A token is returned by taking a substring of the string that was used to create
the StringTokenizer object.
int countTokens() Calculates the number of times that this tokenizer's nextToken method ca
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
than String.
String nextToken() Returns the next token from this string tokenizer.
String nextToken(String Returns the next token in this string tokenizer's string.
delim)
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
179
the split method of String or the java.util.regex package instead.
CODE
import java.util.StringTokenizer;
class StringTokenizerDemo
{
public static void main(String arg[])
{
StringTokenizer st1 = new StringTokenizer("Welcome to Merit" +
" 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
while (st3.hasMoreTokens()) {
System.out.println(st3.nextToken());
}
}
}
OUTPUT
Welcome
to
Merit
Campus.
---------
It's an
Education
Website.
---------
Learn
~
programming
180
~
with Java.
BitSet
The BitSet class creates a special type of array that holds bit values. This array can increase
in size as needed. This makes it similar to a vector of bits. The bits of a BitSet are indexed
by nonnegative integers. Individual indexed bits can be examined, set, or cleared.
One BitSet may be used to modify the contents of another BitSet through logical AND,
logical inclusive OR, and logical exclusive OR operations.
Constructors :
BitSet class has two constructors:
Constructor Description
BitSet( int size ) Allows us to specify the initial size i.e. the no. of bits that the BitSet can hold
NOTE:
By default, all bits are initialized to zero.
Method Description
void set( int index, boolean v ) Sets the bit specified by index to the value passed in v. true sets t
void or( BitSet bitSet ) ORs the contents of the invoking BitSet object with that specified
into the invoking object.
181
void and( BitSet bitSet ) ANDs the contents of the invoking BitSet object with that specifi
result into the invoking object
void andNot( BitSet bitSet ) For each 1 bit in bitSet, the corresponding bit in the invoking Bit
void xor( BitSet bitSet ) XORs the contents of the invoking BitSet object with that specifie
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, Sets the bits from startIndex to (endIndex – 1) to the value passe
boolean v ) false clears the bits
void flip(int startIndex, int endIndex) Reverse the bits from startIndex to endIndex-1
BitSetDemo
CODE
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
182
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}
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
Date() Allocates a Date object and initializes it so that it represents the time at which it was allo
millisecond.
Date(long Allocates a Date object and initializes it to represent the specified number of millisecond
date) known as "the epoch", namely January 1, 1970, 00:00:00 GMT.
Date Methods:
183
Method Description
boolean after(Date date) Tests if this date is after the specified date.
long getTime() Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT
void setTime(long time) Sets this Date object to represent a point in time that is time milliseconds
184
M Month in a year July or 07
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
185
z Time zone Eastern Standard Time
G Era designator AD
Date Example
CODE
import java.util.*;
class DateExampleTest
{
public static void main(String arg[])
{
try
{
// Get current date and time
Date date = new Date(); // LINE A
System.out.println(date);
// Convert Date to String.
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
// LINE B
String stringDate = dateFormat.format(date); // LINE C
System.out.println(stringDate);
// Convert String to Date.
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
String dateInString = "15/08/1947 02:25:56";
date = df.parse(dateInString); // LINE D
System.out.println(date);
} catch (Exception e)
{
e.printStackTrace();
}
}
}
OUTPUT
186
Fri Apr 18 14:25:43 IST 2014
18/04/2014 02:25:43
Fri Aug 15 02:25:56 IST 1947
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
static Calender getInstance() This method returns the object of calender class for the default location
Int get(int const) This method returns the value of the requested
specified be ‘const’. It can be any one of the integer constants. For exam
Calender.HOUR etc.
Void set(int const,int value) This method sets the value of the date or time component specified by c
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 object.
dayOfMonth)
final void set(int year, int month, int Sets various date and time components of the invoking object.
dayOfMonth, int hours, int minutes)
187
final void set(int year, int month, int Sets various date and time components of the invoking object.
dayOfMonth, int hours, int minutes, int
seconds)
TimeZonegetTimeZone() These methods get and set the time zone for the invoking object.
Void setTimeZone(TimeZone+zObj) of setTimeZone() method specifies the TimeZone object to be set.
Boolean equals(Object calObj) This method returns true if both the invoking calender object and the o
Otherwise returns false.
Boolean after(Object calObj) This method returns true if the invoking calender object contains a date
specified by calObj object. Otherwise returns false.
Boolean before(Object calObj) This method returns true if the invoking calender object contains a date
specified by calObj object. Otherwise returns false.
Calendar defines the following int constants, which are used when you get or set components of the
calendar:
ALL_STYLES FRIDAY
AM HOUR
AM_PM HOUR_OF_DAY
APRIL JANUARY
AUGUST JULY
DATE JUNE
DAY_OF_MONTH LONG
188
DAY_OF_WEEK MARCH
DAY_OF_WEEK_IN_MONTH MAY
DAY_OF_YEAR MILLISECOND
DECEMBER MINUTE
DST_OFFSET MONDAY
ERA MONTH
FEBRUARY NOVEMBER
FIELD_COUNT OCTOBER
DateAndTime
CODE
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"};
189
System.out.println("Current Time: "); // LINE A
System.out.print(cal.get(Calendar.HOUR) + ":");
System.out.print(cal.get(Calendar.MINUTE) + ":");
System.out.println(cal.get(Calendar.SECOND));
}
}
OUTPUT
Date :
APR 9 2014
Current Time:
7:40:20
Updated time
10:29:22
Random
Random Constructors:
Constructor Description
Random(long seed) Creates a new random number generator using a single long seed.
Random Methods:
190
Method Description
boolean nextBoolean() Returns the next pseudorandom, uniformly distributed boolean value from this
sequence.
void nextBytes(byte[] Generates random bytes and places them into a user-supplied byte array.
bytes)
double nextDouble() Returns the next pseudorandom, uniformly distributed double value between
float nextFloat() Returns the next pseudorandom, uniformly distributed float value between
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
int nextInt(int n) Returns a pseudorandom, uniformly distributed int value between 0 (inclusive
value n (exclusive), drawn from this random number generator's sequence.
long nextLong() Returns the next pseudorandom, uniformly distributed long value from this
191
random number generator's sequence.
void setSeed(long Sets the seed of this random number generator using a single long seed.
seed)
Random
CODE
import java.util.Random;
class RandomTest
{
public static void main(String arg[])
{
Random r = new Random();
}
}
OUTPUT
192
The next Integer value between 0 to 4 : 1
The next Long value : 3604397887200514771
The set Seed value : -1150867590
Formatter
Formatter class in java.util package helps in formatting the display numbers, string, time
and date in any format you like. For e.g., we could write the
amount 123456.7 as 1,23,456.7 or 123,456.7 or 123456.70 or 123.456,70 depending upon
the requirement. The Formatter class helps in displaying them in required format.
Initially we will discuss various ways for creating the Formatter objects. Some of the
constructors are
/*1*/ Formatter()
/*2*/ Formatter(Appendable buf)
/*3*/ Formatter(Appendable buf, Locale loc)
/*4*/ Formatter(String filename) throws FileNotFoundException
/*5*/ Formatter(String filename, String charset) throws FileNotFoundException, Unsuppor
tedEncodingException
/*6*/ Formatter(File outF) throws FileNotFoundException
/*7*/ Formatter(OutputStream outStream)
The most commonly used constructor is the first one and by default any data formatted
using this type of Formatter, will be written to StringBuilder and using the default Locale.
The output of the Formatter can be accessed using out() method.
If we want to the output to be written to our own StringBuilder then we can use the
constructor 2 and 3. If we want to write to file or OutputStream we can use the other
constructors. We can also pass the Locale and charset as required.
In Java Formatter Methods we will discuss about various methods in the Formatter class.
Scanner
The Scanner class is a class in java.util package, which allows a user to read values of
various types.
The Scanner looks for tokens in the input. A token is a series of characters that ends with
whitespace. A whitespace character can be a blank, a tab character, a carriage return, or the
end of the file.
For example, if we read a line that has a series of numbers separated by blanks, the scanner
will take each number as a separate token.
193
Constructors
Scanner class has several constructors. Among them, the following are particularly useful.
Constructor Description
Scanner(File source) Constructs a new scanner that produces values scanned from the
Scanner(InputStream Constructs a new Scanner that produces values scanned from the
source)
specified input stream.
Scanner(String Constructs a new scanner that produces values scanned from the
source)
specified string.
CODE
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
class ScannerConstructorDemo1
{
public static void main(String arg[])
{
// Read from a file rather than the keyboard
Scanner sc = new Scanner(new File("FIFA14.txt")); // LINE A
194
}
OUTPUT
Germany
Argentina
Netherlands
Brazil
Colombia
France
Costa-Rica
Belgium
UNIT - V
Swing in Java is a Graphical User Interface (GUI) toolkit that includes the GUI components.
Swing provides a rich set of widgets and packages to make sophisticated GUI components
for Java applications. Swing is a part of Java Foundation Classes(JFC), which is an API for
Java programs that provide GUI.
The Java Swing library is built on top of the Java Abstract Widget Toolkit (AWT), an older,
platform dependent GUI toolkit. You can use the Java GUI programming components like
button, textbox, etc. from the library and do not have to create the components from
scratch.
GUI (Graphical User Interface) in Java is an easy-to-use visual experience builder for Java
applications. It is mainly made of graphical components like buttons, labels, windows, etc.
through which the user can interact with an application. GUI plays an important role to
build easy interfaces for Java applications.
195
Java GUI Example
Now in this Swing Java Tutorial, let's understand GUI with Java Swing examples.
import javax.swing.*;
class gui{
public static void main(String args[]){
JFrame frame = new JFrame("My First GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
JButton button = new JButton("Press");
frame.getContentPane().add(button); // Adds Button to content pane of frame
frame.setVisible(true);
}
}
import javax.swing.*;
class gui{
public static void main(String args[]){
JFrame frame = new JFrame("My First GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
JButton button1 = new JButton("Press");
frame.getContentPane().add(button1);
frame.setVisible(true);
}
}
196
Step 5) How about adding two buttons? Copy the following code into an editor.
import javax.swing.*;
class gui{
public static void main(String args[]){
JFrame frame = new JFrame("My First GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
JButton button1 = new JButton("Button 1");
JButton button2 = new JButton("Button 2");
frame.getContentPane().add(button1);
frame.getContentPane().add(button2);
frame.setVisible(true);
}
}
Java Swing tutorial is a part of Java Foundation Classes (JFC) that is used to create window-
based applications. It is built on the top of AWT (Abstract Windowing Toolkit) API and
entirely written in java.
The javax.swing package provides classes for java swing API such as JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.
197
Difference between AWT and Swing
There are many differences between java awt and swing that are given below.
3 AWT doesn't support pluggable look and Swing supports pluggable look
) feel. and feel.
198
In Java Programming context, the Model consists of simple Java classes, the View displays
the data and the Controller consists of servlets. This separation results in user requests
being processed as follows:
1. The browser on the client sends a request for a page to the controller present on the
server
2. The controller performs the action of invoking the model, thereby, retrieving the
data it needs in response to the request
3. The controller then gives the retrieved data to the view
4. The view is rendered and sent back to the client for the browser to display
Separating a software application into these three distinct components is a good idea for a
number of reasons. Let’s take a look at what those are.
Instructor-led Sessions
Real-life Case Studies
Assignments
Lifetime Access
Multiple developers can work with the three layers (Model, View, and Controller)
simultaneously
Offers improved scalability, that supplements the ability of the application to grow
As components have a low dependency on each other, they are easy to maintain
A model can be reused by multiple views which provides reusability of code
Adoption of MVC makes an application more expressive and easy to understand
199
Extending and testing of the application becomes easy
Now you know why the MVC is the most popular design patterns in the web programming
world. But, if you are still struggling to get your head around the concept of MVC, don’t
worry. We will dig deep into each of these layers and learn their purpose with the help of
an example program.
1 package MyPackage;
2
3 public class Course {
4 private String CourseName;
5 private String CourseId;
6 private String CourseCategory;
7
8 public String getId() {
9 return CourseId;
10 }
11
12 public void setId(String id) {
13 this.CourseId = id;
14 }
15
16 public String getName() {
17 return CourseName;
18 }
19
20 public void setName(String name) {
21 this.CourseName = name;
22 }
23
200
24 public String getCategory() {
25 return CourseCategory;
26 }
27
28 public void setCategory(String category) {
29 this.CourseCategory = category;
30 }
31
32 }
The code is easy to understand and is self-explanatory. It consists of functions to get/set
course details.
The View Layer
This layer of the MVC design pattern represents the output of the application or the user
interface. It displays the data fetched from the model layer by the controller and presents
the data to the user whenever asked for. It receives all the information it needs from the
controller and it doesn’t need to interact with the business layer directly. Let’s create a
view using CourseView Class.
package MyPackage;
This code is simply to print the values to the console. Next up we have the controller of the
web application.
201
back to the controller and then displayed on the view. Let’s create CourseContoller
Class which acts as a controller.
1
package MyPackage;
2
public class CourseController {
3 private Course model;
4 private CourseView view;
A cursory glance at the code will tell us that this controller class is just responsible for
calling the model to get/set the data and updating the view based on that. Now let’s have a
look at how all of these are tied together.
202
Main Java Class
Let’s call this class “MVCPatternDemo.java”. Check out the code below.
1 package MyPackage;
2
3 public class MVCPatternDemo {
4 public static void main(String[] args) {
5
6 //fetch student record based on his roll no from the database
7 Course model = retriveCourseFromDatabase();
8
9 //Create a view : to write course details on console
10 CourseView view = new CourseView();
11
12 CourseController controller = new CourseController(model, view);
13
14 controller.updateView();
15
16 //update model data
17 controller.setCourseName("Python");
18 System.out.println("nAfter updating, Course Details are as follows");
19
20 controller.updateView();
21 }
22
23 private static Course retriveCourseFromDatabase(){
24 Course course = new Course();
25 course.setName("Java");
26 course.setId("01");
27 course.setCategory("Programming");
28 return course;
29 }
30 }
The above class fetches the course data from the function using which user enters the set of
values. It then pushes those values into the Course model. Then, it initializes the view we
had created earlier in the article. Further, it also invokes the CourseController class and
binds it to the Course class and the CourseView class. The updateView() method which is a
part of the controller then updates the course details on the console. Check out the output
below.
Output
1 Course Details:
2 Name: Java
203
3 Course ID: 01
4 Course Category: Programming
5
7 Course Details:
8 Name: Python
9 Course ID: 01
204
BoxLayout: It arranges multiple components in either vertically or horizontally,
but not both. The components are arranged from left to right or top to bottom. If
the components are aligned horizontally, the height of all components will be the
same and equal to the largest sized components. If the components are
aligned vertically, the width of all components will be the same and equal to the
largest width components.
CardLayout: It arranges two or more components having the same size. The
components are arranged in a deck, where all the cards of the same size and
the only top card are visible at any time. The first component added in the
container will be kept at the top of the deck. The default gap at the left, right, top and
bottom edges are zero and the card components are displayed either horizontally
or vertically.
Example
import java.awt.*;
import javax.swing.*;
public LayoutManagerTest() {
setTitle("LayoutManager Test");
flowLayoutPanel1.add(one);
flowLayoutPanel1.add(two);
205
flowLayoutPanel1.add(three);
flowLayoutPanel2.add(bottom);
gridLayoutPanel2.add(lbl1);
gridLayoutPanel2.add(lbl2);
gridLayoutPanel2.add(lbl3);
gridLayoutPanel3.add(four);
gridLayoutPanel3.add(five);
gridLayoutPanel3.add(six);
gridLayoutPanel1.add(gridLayoutPanel2);
gridLayoutPanel1.add(gridLayoutPanel3);
206
add(flowLayoutPanel1, BorderLayout.NORTH);
add(flowLayoutPanel2, BorderLayout.SOUTH);
add(gridLayoutPanel1, BorderLayout.CENTER);
setSize(400, 325);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
new LayoutManagerTest();
}
Output
What is an Event?
Change in the state of an object is known as Event, i.e., event describes the change in the
state of the source. Events are generated as a result of user interaction with the graphical
207
user interface components. For example, clicking on a button, moving the mouse, entering
a character through keyboard, selecting an item from the list, and scrolling the page are
the activities that causes an event to occur.
Types of Event
The events can be broadly classified into two categories −
Foreground Events − These events require direct interaction of the user. They are
generated as consequences of a person interacting with the graphical components
in the Graphical User Interface. For example, clicking on a button, moving the
mouse, entering a character through keyboard, selecting an item from list, scrolling
the page, etc.
Background Events − These events require the interaction of the end user.
Operating system interrupts, hardware or software failure, timer expiration, and
operation completion are some examples of background events.
208
Step 4 − The method is gets executed and returns.
Callback Methods
These are the methods that are provided by API provider and are defined by the
application programmer and invoked by the application developer. Here the callback
methods represent an event method. In response to an event, java jre will fire callback
method. All such callback methods are provided in listener interfaces.
If a component wants some listener to listen ot its events, the source must register itself to
the listener.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public SwingControlDemo(){
prepareGUI();
}
public static void main(String[] args){
SwingControlDemo swingControlDemo = new SwingControlDemo();
swingControlDemo.showEventDemo();
}
private void prepareGUI(){
mainFrame = new JFrame("Java SWING Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
209
headerLabel = new JLabel("",JLabel.CENTER );
statusLabel = new JLabel("",JLabel.CENTER);
statusLabel.setSize(350,100);
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showEventDemo(){
headerLabel.setText("Control in action: Button");
okButton.setActionCommand("OK");
submitButton.setActionCommand("Submit");
cancelButton.setActionCommand("Cancel");
okButton.addActionListener(new ButtonClickListener());
submitButton.addActionListener(new ButtonClickListener());
cancelButton.addActionListener(new ButtonClickListener());
controlPanel.add(okButton);
controlPanel.add(submitButton);
controlPanel.add(cancelButton);
mainFrame.setVisible(true);
}
private class ButtonClickListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
210
statusLabel.setText("Submit Button clicked.");
} else {
statusLabel.setText("Cancel Button clicked.");
}
}
}
}
Compile the program using the command prompt. Go to D:/ > SWING and type the
following command.
D:\AWT>javac com\tutorialspoint\gui\SwingControlDemo.java
If no error occurs, it means the compilation is successful. Run the program using the
following command.
D:\AWT>java com.tutorialspoint.gui.SwingControlDemo
Verify the following output.
The Delegation Event model is defined to handle events in GUI programming languages.
The GUI stands for Graphical User Interface, where a user graphically/visually interacts
with the system.
The GUI programming is inherently event-driven; whenever a user initiates an activity such
as a mouse activity, clicks, scrolling, etc., each is known as an event that is mapped to a code
to respond to functionality to the user. This is known as event handling.
In this section, we will discuss event processing and how to implement the delegation
event model in Java. We will also discuss the different components of an Event Model.
211
Event Processing in Java
Java support event processing since Java 1.0. It provides support for AWT ( Abstract
Window Toolkit), which is an API used to develop the Desktop application. In Java 1.0, the
AWT was based on inheritance. To catch and process GUI events for a program, it should
hold subclass GUI components and override action() or handleEvent() methods. The below
image demonstrates the event processing.
But, the modern approach for event processing is based on the Delegation Model. It defines
a standard and compatible mechanism to generate and process events. In this model, a
source generates an event and forwards it to one or more listeners. The listener waits until
it receives an event. Once it receives the event, it is processed by the listener and returns it.
The UI elements are able to delegate the processing of an event to a separate function.
The key advantage of the Delegation Event Model is that the application logic is completely
separated from the interface logic.
In this model, the listener must be connected with a source to receive the event
notifications. Thus, the events will only be received by the listeners who wish to receive
them. So, this approach is more convenient than the inheritance-based event model (in Java
1.0).
In the older model, an event was propagated up the containment until a component was
handled. This needed components to receive events that were not processed, and it took
lots of time. The Delegation Event model overcame this issue.
o Events
o Events Sources
o Events Listeners
Events
The Events are the objects that define state change in a source. An event can be generated
as a reaction of a user while interacting with GUI elements. Some of the event generation
activities are moving the mouse pointer, clicking on a button, pressing the keyboard key,
selecting an item from the list, and so on. We can also consider many other user operations
as events.
212
The Events may also occur that may be not related to user interaction, such as a timer
expires, counter exceeded, system failures, or a task is completed, etc. We can define events
for any of the applied actions.
Event Sources
A source is an object that causes and generates an event. It generates an event when the
internal state of the object is changed. The sources are allowed to generate several different
types of events.
A source must register a listener to receive notifications for a specific event. Each event
contains its registration method. Below is an example:
From the above syntax, the Type is the name of the event, and e1 is a reference to the event
listener. For example, for a keyboard event listener, the method will be called
as addKeyListener(). For the mouse event listener, the method will be called
as addMouseMotionListener(). When an event is triggered using the respected source, all
the events will be notified to registered listeners and receive the event object. This process
is known as event multicasting. In few cases, the event notification will only be sent to
listeners that register to receive them.
From the above syntax, the Type is the name of the event, and e2 is the event listener's
reference. When the specified event occurs, it will be notified to the registered listener.
This process is known as unicasting events.
A source should contain a method that unregisters a specific type of event from the listener
if not needed. Below is an example of the method that will remove the event from the
listener.
From the above syntax, the Type is an event name, and e2 is the reference of the listener.
For example, to remove the keyboard listener, the removeKeyListener() method will be
called.
The source provides the methods to add or remove listeners that generate the events. For
example, the Component class contains the methods to operate on the different types of
events, such as adding or removing them from the listener.
213
Event Listeners
An event listener is an object that is invoked when an event triggers. The listeners require
two things; first, it must be registered with a source; however, it can be registered with
several resources to receive notification about the events. Second, it must implement the
methods to receive and process the received notifications.
The methods that deal with the events are defined in a set of interfaces. These interfaces
can be found in the java.awt.event package.
For example, the MouseMotionListener interface provides two methods when the mouse
is dragged and moved. Any object can receive and process these events if it implements the
MouseMotionListener interface.
Types of Events
The foreground events are those events that require direct interaction of the user. These
types of events are generated as a result of user interaction with the GUI component. For
example, clicking on a button, mouse movement, pressing a keyboard key, selecting an
option from the list, etc.
The Background events are those events that result from the interaction of the end-user.
For example, an Operating system interrupts system failure (Hardware or Software).
To handle these events, we need an event handling mechanism that provides control over
the events and responses.
The Delegation Model is available in Java since Java 1.1. it provides a new delegation-based
event model using AWT to resolve the event problems. It provides a convenient mechanism
to support complex Java programs.
Design Goals
214
o It provides robust event handling program code which is less error-prone (strong
compile-time checking)
o It is Flexible, can enable different types of application models for event flow and
propagation.
o It enables run-time discovery of both the component-generated events as well as
observable events.
o It provides support for the backward binary compatibility with the previous model.
The below is a Java program to handle events implementing the event deligation model:
TestApp.java:
1. import java.awt.*;
2. import java.awt.event.*;
3.
4. public class TestApp {
5. public void search() {
6. // For searching
7. System.out.println("Searching...");
8. }
9. public void sort() {
10. // for sorting
11. System.out.println("Sorting....");
12. }
13.
14. static public void main(String args[]) {
15. TestApp app = new TestApp();
16. GUI gui = new GUI(app);
17. }
18. }
19.
20. class Command implements ActionListener {
21. static final int SEARCH = 0;
22. static final int SORT = 1;
23. int id;
24. TestApp app;
25.
26. public Command(int id, TestApp app) {
27. this.id = id;
28. this.app = app;
29. }
215
30.
31. public void actionPerformed(ActionEvent e) {
32. switch(id) {
33. case SEARCH:
34. app.search();
35. break;
36. case SORT:
37. app.sort();
38. break;
39. }
40. }
41. }
42.
43. class GUI {
44.
45. public GUI(TestApp app) {
46. Frame f = new Frame();
47. f.setLayout(new FlowLayout());
48.
49. Command searchCmd = new Command(Command.SEARCH, app);
50. Command sortCmd = new Command(Command.SORT, app);
51.
52. Button b;
53. f.add(b = new Button("Search"));
54. b.addActionListener(searchCmd);
55. f.add(b = new Button("Sort"));
56. b.addActionListener(sortCmd);
57.
58. List l;
59. f.add(l = new List());
60. l.add("Alphabetical");
61. l.add("Chronological");
62. l.addActionListener(sortCmd);
63. f.pack();
64.
65. f.show();
66. }
67. }
Output:
216
Searching...
Java adapter classes provide the default implementation of listener interfaces. If you inherit
the adapter class, you will not be forced to provide the implementation of all the methods
of listener interfaces. So it saves code.
WindowAdapter WindowListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
FocusAdapter FocusListener
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
HierarchyBoundsAdapter HierarchyBoundsListener
DragSourceAdapter DragSourceListener
217
DragTargetAdapter DragTargetListener
MouseInputAdapter MouseInputListener
InternalFrameAdapter InternalFrameListener
Output:
218
Java MouseAdapter Example
1. import java.awt.*;
2. import java.awt.event.*;
3. public class MouseAdapterExample extends MouseAdapter{
4. Frame f;
5. MouseAdapterExample(){
6. f=new Frame("Mouse Adapter");
7. f.addMouseListener(this);
8.
9. f.setSize(300,300);
10. f.setLayout(null);
11. f.setVisible(true);
12. }
13. public void mouseClicked(MouseEvent e) {
14. Graphics g=f.getGraphics();
15. g.setColor(Color.BLUE);
16. g.fillOval(e.getX(),e.getY(),30,30);
17. }
18.
19. public static void main(String[] args) {
20. new MouseAdapterExample();
21. }
22. }
Output:
219
4. Types of Nested classes
Java inner class or nested class is a class which is declared inside the class or interface.
We use inner classes to logically group classes and interfaces in one place so that it can be
more readable and maintainable.
Additionally, it can access all the members of outer class including private data members
and methods.
There are basically three advantages of inner classes in java. They are as follows:
1) 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.
2) Nested classes are used to develop more readable and maintainable code because it
logically group classes and interfaces in one place only.
A class that have no name is known as anonymous inner class in java. It should be used if
you have to override method of class or interface. Java Anonymous inner class can be
created by two ways:
220
7. void eat(){System.out.println("nice fruits");}
8. };
9. p.eat();
10. }
11. }
Output:
nice fruits
Applet Definition:
Applets are small Java applications that can be accessed on an Internet server,
transported over Internet, and can be automatically installed and run as apart of a
web document.
After a user receives an applet, the applet can produce a graphical user interface. It
has limited access to resources so that it can run complex computations without
introducing the risk of viruses or breaching data integrity.
Any applet in Java is a class that extends the java.applet.Applet class.
An Applet class does not have any main() method. It is viewed using JVM. The JVM
can use either a plug-in of the Web browser or a separate runtime environment to
run an applet application.
JVM creates an instance of the applet class and invokes init() method to initialize an
Applet.
An applet is a Java program designed to be included in an HTML Web document. You can
write your Java applet and include it in an HTML page. When you use a Java-enabled
browser to view an HTML page that contains an applet, the applet's code is transferred to
your system and is run by the browser's Java virtual machine.
The HTML document contains tags, which specify the name of the Java applet and its
Uniform Resource Locator (URL). The URL is the location at which the applet bytecodes
reside on the Internet. When an HTML document containing a Java applet tag is displayed, a
Java-enabled Web browser downloads the Java bytecodes from the Internet and uses the
Java virtual machine to process the code from within the Web document. These Java
applets are what enable Web pages to contain animated graphics or interactive content.
221
The Applets are used to provide interactive features to web applications that cannot be
provided by HTML alone. They can capture mouse input and also have controls like buttons
or check boxes. In response to user actions, an applet can change the provided graphic
content.
Applications are just like a Java Applets are small Java programs that are
programs that can be execute designed to be included with the HTML web
independently without using the web document. They require a Java-enabled web
browser. browser for execution.
Application program requires a main Applet does not require a main function for its
function for its execution. execution.
Applications can executes the Applets cannot execute programs from the
programs from the local system. local machine.
In this article we will learn about passing parameters to applets using the param tag and
retrieving the values of parameters using getParameter method.
222
Parameters specify extra information that can be passed to an applet from the HTML page.
Parameters are specified using the HTML’s param tag.
Param Tag
The <param> tag is a sub tag of the <applet> tag. The <param> tag contains two
attributes: name and value which are used to specify the name of the parameter and the
value of the parameter respectively. For example, the param tags for passing name and age
parameters looks as shown below:
Now, these two parameters can be accessed in the applet program using
the getParameter() method of the Applet class.
getParameter() Method
The getParameter() method of the Applet class can be used to retrieve the parameters
passed from the HTML page. The syntax of getParameter() method is as follows:
Let’s look at a sample program which demonstrates the <param> HTML tag and
the getParameter() method:
1 import java.awt.*;
2 import java.applet.*;
4 {
5 String n;
223
6 String a;
8 {
9 n = getParameter("name");
10 a = getParameter("age");
11 }
13 {
16 }
17 }
18 /*
22 </applet>
23 */
224
Creating a Swing Apple
Swing Applets
So far, we have created the applets based on AWT(Abstract Window Toolkit) by extending
the Applet class of the awt package. 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.
Note:
JApplet is a top-level container class and you should never draw on it directly, instead you
should draw on the component class like JPanel and then add this JPanel to the JApplet, as
shown in the upcoming code.
225
Creating a swing applet
In the upcoming code, 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="Applet21" width="500" height="200">
</applet>
*/
B()
226
{
jb= new JLabel("Welcome, please click on any button to unbox some interesting
knowledge -");
Box2 = new JButton("Box2");
box2 = new JButton("Box2");
box3 = new JButton("Box3");
box4 = new JButton("Box4");
str ="";
setLayout(new FlowLayout());
add(jb);
add(Box2);
add(box2);
add(box3);
add(box4);
Box2.addActionListener(this);
box2.addActionListener(this);
box3.addActionListener(this);
box4.addActionListener(this);
}
if(ae.getActionCommand().equals("Box2"))
{
str="The Mariana Trench is the deepest point in Earth's ocean, with depth of over
10,994 metres.";
repaint();
}
if(ae.getActionCommand().equals("Box3"))
{
str="The coldest temperature ever recorded was -128.6F in Antarctica, on July 21,
1983.";
repaint();
}
227
if(ae.getActionCommand().equals("Box4"))
{
str="The oldest person to climb Mt. Everent was Japanese Miura Yiuchiro, at the age
of 80.";
repaint();
}
Output-
In the applet shown above, four buttons are presented in the output. These buttons are
added to B class(which has extended JPanel). This JPanel is in turn added to our Swing
applet class, Applet21. Whenever a button is clicked, an interesting fact about the
world is presented to the user.
Painting in Applet
228
MouseMotionListener.
1. import java.awt.*;
2. import java.awt.event.*;
3. import java.applet.*;
4. public class MouseDrag extends Applet implements MouseMotionListener{
5.
6. public void init(){
7. addMouseMotionListener(this);
8. setBackground(Color.red);
9. }
10.
11. public void mouseDragged(MouseEvent me){
12. Graphics g=getGraphics();
13. g.setColor(Color.white);
14. g.fillOval(me.getX(),me.getY(),5,5);
15. }
16. public void mouseMoved(MouseEvent me){}
17.
18. }
In the above example, getX() and getY() method of MouseEvent is used to get the current x-
axis and y-axis. The getGraphics() method of Component class returns the object of
Graphics.
myapplet.html
1. <html>
2. <body>
3. <applet code="MouseDrag.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>
In this article, I am going to discuss Swing Controls in Java with Examples. Please read our
previous article, where we discussed Swings in Java. At the end of this article, you will
understand the following swing controls in Java in detail with examples.
1. JLabel
2. JRadioButton
3. ButtonGroup
229
4. JCheckBox
5. JTextField
6. JTextArea
7. JButton
8. Border
9. JComboBox
10. JTabbedPane
11. JPasswordField
12. Look and Feel Management in Java Swing
JLabel
The object of the JLabel class may be a component for putting text during a container. It’s
used to display one line of read-only text. The text is often changed by an application but a
user cannot edit it directly. It inherits the JComponent class.
Declaration: public class JLabel extends JComponent implements SwingConstants,
Accessible
Syntax: JLabel jl = new JLabel();
JLabel Constructors
1. JLabel(): It is used to create a JLabel instance with no image and with an empty
string for the title.
2. JLabel(String s): It is used to create a JLabel instance with the specified text.
3. JLabel(Icon i): It is used to create a JLabel instance with the specified image.
4. JLabel(String s, Icon I, int horizontalAlignment): It is used to create a JLabel
instance with the specified text, image, and horizontal alignment.
Sample Program to understand JLabel Swing Control in Java:
import javax.swing.*;
import java.awt.*;
JLabel jl;
JLabelDemo ()
{
jl = new JLabel ("Good Morning");
Container c = this.getContentPane ();
c.setLayout (new FlowLayout ());
c.setBackground (Color.blue);
Font f = new Font ("arial", Font.BOLD, 34);
jl.setFont (f);
jl.setBackground (Color.white);
c.add (jl);
this.setVisible (true);
this.setSize (400, 400);
this.setTitle ("Label");
this.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
230
}
public static void main (String[]args)
{
new JLabelDemo ();
}
}
Output
JRadioButton
This component allows the user to select only one item from a group item. By using the
JRadioButton component you can choose one option from multiple options.
Declaration: public class JRadioButton extends JToggleButton implements Accessible
Syntax: JRadioButton jrb = new JRadioButton();
JRadioButton Constructors
1. JRadioButton(): It is used to create an unselected radio button with no text.
2. JRadioButton(Label): It is used to create an unselected radio button with specified
text.
3. JRadioButton(Label, boolean): It is used to create a radio button with the
specified text and selected status.
ButtonGroup
This class is used to place multiple RadioButton into a single group. So the user can select
only one value from that group. We can add RadioButtons to the ButtonGroup by using the
add method.
Example : add(jrb);
Syntax : ButtonGroup bg = new ButtonGroup();
JCheckBox
This component allows the user to select multiple items from a group of items. It is used to
create a CheckBox. It is used to turn an option ON or OFF.
Declaration: public class JCheckBox extends JToggleButton implements Accessible
JCheckBox Constructors
1. JCheckBox(): It is used to create an initially unselected checkbox button with no
text, no icon.
2. JCheckBox(Label): It is used to create an initially unselected checkbox with text.
3. JCheckBox(Label, boolean): It is used to create a checkbox with text and specifies
whether or not it is initially selected.
231
4. JCheckBox(Action a): It is used to create a checkbox where properties are taken
from the Action supplied.
JTextField
The JTextField component allows the user to type some text in a single line. It basically
inherits the JTextComponent class.
Declaration: public class JTextField extends JTextComponent implements
SwingConstants
Syntax: JTextField jtf = new JTextField();
JTextField Constructors
1. JTextField(): It is used to create a new Text Field.
2. JTextField(String text): It is used to create a new Text Field initialized with the
specified text.
3. JTextField(String text, int columns): It is used to create a new Text field initialized
with the specified text and columns.
4. JTextField(int columns): It is used to create a new empty TextField with the
specified number of columns.
JTextArea
The JTextArea component allows the user to type the text in multiple lines. It also allows
the editing of multiple-line text. It basically inherits the JTextComponent class.
Declaration: public class JTextArea extends JTextComponent
Syntax: JTextArea jta = new JTextArea();
JTextArea Constructors
1. JTextArea(): It is used to create a text area that displays no text initially.
2. JTextarea(String s): It is used to create a text area that displays specified text
initially.
3. JTextArea(int row, int column): It is used to create a text area with the specified
number of rows and columns that display no text initially.
4. JTextarea(String s, int row, int column): It is used to create a text area with the
specified number of rows and columns that display specified text.
Sample Program to understand the above-discussed Swing Controls in Java.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SwingDemo2 extends JFrame implements ActionListener
{
JRadioButton eng, doc;
ButtonGroup bg;
JTextField jtf;
JCheckBox bcd, ccb, acb;
JTextArea jta;
SwingDemo2 ()
{
eng = new JRadioButton ("Engineer");
doc = new JRadioButton ("Doctor");
bg = new ButtonGroup ();
232
bg.add (eng);
bg.add (doc);
jtf = new JTextField (20);
bcd = new JCheckBox ("Bike");
ccb = new JCheckBox ("Car");
acb = new JCheckBox ("Aeroplane");
jta = new JTextArea (3, 20);
Container c = this.getContentPane ();
c.setLayout (new FlowLayout ());
// Registering the listeners with the components
eng.addActionListener (this);
doc.addActionListener (this);
bcd.addActionListener (this);
ccb.addActionListener (this);
acb.addActionListener (this);
c.add (eng);
c.add (doc);
c.add (jtf);
c.add (bcd);
c.add (ccb);
c.add (acb);
c.add (jta);
this.setVisible (true);
this.setSize (500, 500);
this.setTitle ("Selection Example");
this.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed (ActionEvent ae)
{
if (ae.getSource () == eng)
{
jtf.setText ("You are an Engineer");
}
if (ae.getSource () == doc)
{
jtf.setText ("You are an Doctor");
}
String str = " ";
if (bcd.isSelected ())
{
str += "Bike\n";
}
if (ccb.isSelected ())
{
str += "Car\n";
}
233
if (acb.isSelected ())
{
str += "Aeroplane\n";
}
jta.setText (str);
}
public static void main (String[]args)
{
new SwingDemo2 ();
}
}
Output:
JButton
This component can be used to perform some operations when the user clicks on it. When
the button is pushed, the application results in some action. It basically inherits the
AbstractButton class.
Declaration: public class JButton extends AbstractButton implements Accessible
Syntax: JButton jb = new JButton();
JButton Constructors
1. JButton(): It is used to create a button with no text and icon.
2. JButton(String s): It is used to create a button with the specified text.
3. JButton(Icon i): It is used to create a button with the specified icon object.
Border
The border is an interface using which we can apply a border to every component. To
create the borders we have to use the methods available in BorderFactory class. We can
apply the created border to any component by using SetBorder() method.
Component.setBorder(Border);
Methods of Border
1. Border createLineBorder(Color, int): It is used to create a line border. Here, Color
object specifies the color of the line and int specifies the width in pixels of the line.
2. Border createEtchedBorder(int, Color, Color): It is used to create an etched
border. Here, Color arguments specify the highlight and shadow colors to be used.
Here, int arguments allow the border methods to be specified as
either EtchedBorder.RAISED or EtchedBorder.LOWERED. The methods without
the int arguments create a lowered etched border.
234
3. Border createBevelBorder(int, Color, Color): It is used to create a raised or
lowered beveled border, specifying the colors to use. Here, the integer argument can
be either BevelBorder.RAISED or BevelBorder.LOWERED. Here, Color specifies the
highlight and shadow colors.
4. MatteBorder createMatteBorder(int, int, int, int, Icon): It is used to create a
matte border. Here, the integer arguments specify the number of pixels that the
border occupies at the top, left, bottom, and right (in that order) of whatever
component uses it. Here, the color argument specifies the color which with the
border should fill its area. Here, the icon argument specifies the icon which with the
border should tile its area.
5. TitledBorder createTitledBorder(Border, String, int, int, Font, Color): Create a
titled border. Here, the string argument specifies the title to be displayed. Here, the
optional font and color arguments specify the font and color to be used for the title’s
text. Here, the border argument specifies the border that should be displayed along
with the title. Here, the integer arguments specify the number of pixels that the
border occupies at the top, left, bottom, and right (in that order) of whatever
component uses it.
6. CompoundBorder createCompoundBorder(Border, Border): Combine two
borders into one. Here, the first argument specifies the outer border; the second, the
inner border.
Sample Program to understand JButton and Border controls in Swing Java:
import javax.swing.*;
import java.awt.*;
public class JButtonDemo extends JFrame
{
private JButton button[];
private JPanel panel;
public JButtonDemo ()
{
setTitle ("JButton Borders");
panel = new JPanel ();
panel.setLayout (new GridLayout (7, 1));
button = new JButton[7];
for (int count = 0; count < button.length; count++)
{
button[count] = new JButton ("Button " + (count + 1));
panel.add (button[count]);
}
button[0].setBorder (BorderFactory.createLineBorder (Color.blue));
button[1].setBorder (BorderFactory.createBevelBorder (0));
button[2].setBorder (BorderFactory.createBevelBorder (1, Color.red, Color.blue));
button[3].setBorder (BorderFactory.createBevelBorder (1, Color.green,
Color.orange,Color.red, Color.blue));
button[4].setBorder (BorderFactory.createEmptyBorder (10, 10, 10, 10));
button[5].setBorder (BorderFactory.createEtchedBorder (0));
button[6].setBorder (BorderFactory.createTitledBorder ("Titled Border"));
235
add (panel, BorderLayout.CENTER);
setSize (400, 300);
setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo (null);
setVisible (true);
}
public static void main (String[]args)
{
new JButtonDemo ();
}
}
Output:
JComboBox
This component will display a group of items as a drop-down menu from which one item
can be selected. At the top of the menu the choice selected by the user is shown. It basically
inherits JComponent class. We can add the items to the ComboBox by using the addItem()
method.
Example: jcb.addItem(item);
Declaration: public class JComboBox extends JComponent implements
ItemSelectable, ListDataListener, ActionListener, Accessible
Syntax: JComboBox jcb = new JComboBox();
JComboBox Constructors
1. JComboBox(): It is used to create a JComboBox with a default data model.
2. JComboBox(Object[] items): It is used to create a JComboBox that contains the
elements in the specified array.
3. JComboBox(Vector<?> items): It is used to create a JComboBox that contains the
elements in the specified Vector.
Sample Program to understand JComboBox control in Java
import javax.swing.*;
public class JComboBoxDemo
{
JFrame f;
JComboBoxDemo ()
{
236
f = new JFrame ("ComboBox Example");
String country[] ={ "Hyderabad", "Chennai", "Bengaluru", "Mumbai", "Delhi" };
JComboBox cb = new JComboBox (country);
cb.setBounds (50, 50, 90, 20);
f.add (cb);
f.setLayout (null);
f.setSize (400, 500);
f.setVisible (true);
}
public static void main (String[]args)
{
new JComboBoxDemo ();
}
}
Output:
JTabbedPane
It is a pane that can contain tabs and each tab can display any component in the same pane.
It is used to switch between a group of components by clicking on a tab with a given title or
icon. To add the tabs to the JTabbedPane we can use the following methods:
jtp.add(TabName, Components)
jtp.addTab(TabName, Components)
Declaration: public class JTabbedPane extends JComponent implements Serializable,
Accessible, SwingConstants
Syntax: JTabbedPane jtp = new JTabbedPane();
JTabbedPane Constructors
1. JTabbedPane(): It is used to create an empty TabbedPane.
2. JTabbedPane(int tabPlacement): It is used to create an empty TabbedPane with a
specified tab placement.
3. JTabbedPane(int tabPlacement, int tabLayoutPolicy): It is used to create an
empty TabbedPane with a specified tab placement and tab layout policy.
Sample Program to understand JTabbedPane control in Java
import javax.swing.*;
import java.awt.*;
public class JTabbedPaneDemo
237
{
public static void main (String args[])
{
JFrame frame = new JFrame ("Technologies");
JTabbedPane tabbedPane = new JTabbedPane ();
JPanel panel1, panel2, panel3, panel4, panel5;
panel1 = new JPanel ();
panel2 = new JPanel ();
panel3 = new JPanel ();
panel4 = new JPanel ();
panel5 = new JPanel ();
tabbedPane.addTab ("Cricket", panel1);
tabbedPane.addTab ("Badminton ", panel2);
tabbedPane.addTab ("Football", panel3);
tabbedPane.addTab ("Basketball ", panel4);
tabbedPane.addTab ("Tennis", panel5);
frame.add (tabbedPane);
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.setSize (550, 350);
frame.setVisible (true);
}
}
Output:
JPasswordField
It is a text component specialized for password entry. It allows the editing of a single line of
text. It basically inherits the JTextField class.
Declaration: public class JPasswordField extends JTextField
Syntax: JPasswordField jpf = new JPasswordField();
JPasswordFiled Constructors
1. JPasswordField(): It is used to construct a new JPasswordField, with a default
document, null starting text string, and column width.
2. JPasswordField(int columns): It is used to construct a new empty JPasswordField
with the specified number of columns.
238
3. JPasswordField(String text): It is used to construct a new JPasswordField
initialized with the specified text.
4. JPasswordField(String text, int columns): It is used to construct a new
JPasswordField initialized with the specified text and columns.
Sample Program to understand JPasswordFiled Swing control in Java
import javax.swing.*;
public class JPasswordFieldDemo
{
public static void main (String[]args)
{
JFrame f = new JFrame ("Password Field Example");
JPasswordField value = new JPasswordField ();
JLabel l1 = new JLabel ("Password:");
l1.setBounds (20, 100, 80, 30);
value.setBounds (100, 100, 100, 30);
f.add (value);
f.add (l1);
f.setSize (300, 300);
f.setLayout (null);
f.setVisible (true);
}
}
Output:
239
4. WindowsLookAndFeel
5. WindowsClassicLookAndFeel
The above looks and feels are the predefined classes.
Steps to apply a look and feel:
1. Decide a look and feel type and inform a UI Manager to set a given look and feel and
this will be done using setLookAndFeel().
2. Once the look and feel are set we can apply to the UI Component or Component tree
(whole window).
Note: To update a UI component, we need to call updateUI() to update the look and feel
settings to the component. To update a whole component tree we need to call
updateComponentTreeUI() from SwingUtilities class.
Sample Program for Look and Feel Management in Java Swing
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class LookAndFeelDemo
{
static JFrame jf;
public static void main (String[]args)
{
jf = new JFrame ();
jf.setSize (250, 250);
FlowLayout ob = new FlowLayout ();
jf.setLayout (ob);
JButton jb1 = new JButton ("Metal");
JButton jb2 = new JButton ("Nimbus");
JButton jb3 = new JButton ("Motif");
JButton jb4 = new JButton ("Windows");
MyListener ob1 = new MyListener ();
jb1.addActionListener (ob1);
jb2.addActionListener (ob1);
jb3.addActionListener (ob1);
jb4.addActionListener (ob1);
jf.add (jb1);
jf.add (jb2);
jf.add (jb3);
jf.add (jb4);
jf.setVisible (true);
}
}
class MyListener implements ActionListener
{
public void actionPerformed (ActionEvent ae)
{
try
240
{
String buttonname = ae.getActionCommand ();
if (buttonname.equals ("Metal"))
{
UIManager.setLookAndFeel ("javax.swing.plaf.metal.MetalLookAndFeel");
SwingUtilities.updateComponentTreeUI (LookAndFeelDemo.jf);
}
else if (buttonname.equals ("Nimbus"))
{
UIManager.setLookAndFeel ("javax.swing.plaf.metal.NimbusLookAndFeel");
SwingUtilities.updateComponentTreeUI (LookAndFeelDemo.jf);
}
else if (buttonname.equals ("Motif"))
{
UIManager.setLookAndFeel ("javax.swing.plaf.metal.MotifLookAndFeel");
SwingUtilities.updateComponentTreeUI (LookAndFeelDemo.jf);
}
else if (buttonname.equals ("Windows"))
{
UIManager.setLookAndFeel ("javax.swing.plaf.metal.WindowsLookAndFeel");
SwingUtilities.updateComponentTreeUI (LookAndFeelDemo.jf);
}
}
catch (Exception e1)
{
}
}
}
Output:
In the next article, I am going to discuss the Swing Dialog box in Java with examples. Here,
in this article, I try to explain Swing Controls in Java with Examples and I hope you enjoy
this Swing Controls in Java with Examples article.
241
Swing Dialog Boxes in Java with Examples
In this article, I am going to discuss Swing Dialog boxes in Java with Examples. Please
read our previous article, where we discussed Swing Controls in Java. At the end of this
article, you will understand the different Dialog Boxes that are available in Java Swings
with Examples.
Dialog box : JOptionPane
Dialog Box is a small pop-up box and that was used for different cases like confirmation,
warning, message, etc. Dialog boxes are of three types:
1. Confirmation
2. Input
3. Message
Swing package provides a special class i.e. JOptionPane which was used for creating above
dialog boxes as ready-made.
Declaration: public class JOptionPane extends JComponent implements Accessible
JOptionPane Constructors
1. JOptionPane(): Creates a JOptionPane with a test message.
2. JOptionPane(Object message): Creates an instance of JOtionPane to display a
message.
3. JOptionPane(Object message, int messageType): Creates an instance of
JOtiopnPane to display a message with specified message type and default options.
JOptionPane Methods
Some of the static methods in the JOptionPane class are as follows:
1. showConfirmDialog(Component parentComponent, Object message): Creates a
dialog box with the option Yes, No, and Cancel; with the title, Select an Option.
2. showInputDialog(Component parentComponent, Object message): It show a
question-message dialog box requesting input from the user parented to parent
component.
3. showMessageDialog(Component parentComponent, Object message): Creates
an information-message dialog box titled “Message”.
Sample Program Message Dialog Box in Java:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class JOptionPaneDemo
{
static JTextField jf1;
public static void main (String[]args)
{
JFrame jf = new JFrame ();
jf.setSize (250, 250);
FlowLayout ob = new FlowLayout ();
jf.setLayout (ob);
JLabel j1 = new JLabel ("Enter Name");
jf1 = new JTextField (10);
JButton jb = new JButton ("Submit");
MyListener1 ob1 = new MyListener1 ();
242
jb.addActionListener (ob1);
jf.add (j1);
jf.add (jf1);
jf.add (jb);
jf.setVisible (true);
}
}
class MyListener1 implements ActionListener
{
public void actionPerformed (ActionEvent ae)
{
String name = JOptionPaneDemo.jf1.getText ();
JOptionPane.showMessageDialog (null, "Welcome," + name);
}
}
Output:
243