JAVA-PROGRAMMING-complete notes
JAVA-PROGRAMMING-complete notes
UNIT - I
Object-Oriented Thinking- A way of viewing world – Agents and Communities, messages and methods,
Responsibilities, Classes and Instances, Class Hierarchies- Inheritance, Method binding, Overriding and
Exceptions, Summary of Object-Oriented concepts. Java buzzwords, An Overview of Java, Data types,
Variables and Arrays, operators, expressions, control statements, Introducing classes, Methods and Classes,
String handling.
Inheritance– Inheritance concept, Inheritance basics, Member access, Constructors, Creating Multilevel
hierarchy, super uses, using final with inheritance, Polymorphism-ad hoc polymorphism, pure polymorphism,
method overriding, abstract classes, Object class, forms of inheritance- specialization, specification,
construction, extension, limitation, combination, benefits of inheritance, costs of inheritance.
What is Java?
Java is a programming language and a platform. Java is a high level, robust, object-oriented and secure
programming language.
Java was developed by Sun Microsystems (which is now the subsidiary of Oracle) in the year 1995. James
Gosling is known as the father of Java. Before Java, its name was Oak. Since Oak was already a registered
company, so James Gosling and his team changed the name from Oak to Java.
Platform: Any hardware or software environment in which a program runs, is known as a platform. Since Java
has a runtime environment (JRE) and API, it is called a platform.
Object-Oriented Programming is a paradigm that provides many concepts, such as inheritance, data
binding, polymorphism, etc.
Simula is considered the first object-oriented programming language. The programming paradigm
where everything is represented as an object is known as a truly object-oriented programming language.
Smalltalk is considered the first truly object-oriented programming language.
The popular object-oriented languages are Java, C#, PHP, Python, C++, etc
The main aim of object-oriented programming is to implement real-world entities, for example, object,
classes, abstraction, inheritance, polymorphism, etc.
Editions of Java
Each edition of Java has different capabilities. There are three editions of Java:
o Java Standard Editions (JSE): It is used to create programs for a desktop computer.
o Java Enterprise Edition (JEE): It is used to create large programs that run on the server and manages
heavy traffic and complex transactions.
o Java Micro Edition (JME): It is used to develop applications for small devices such as set-top boxes,
phone, and appliances.
o Standalone Applications: Java standalone applications uses GUI components such as AWT, Swing,
and JavaFX. These components contain buttons, list, menu, scroll panel, etc. It is also known as desktop
alienations.
o Enterprise Applications: An application which is distributed in nature is called enterprise applications.
o Web Applications: An applications that run on the server is called web applications. We use JSP,
Servlet, Spring, and Hibernate technologies for creating web applications.
o Mobile Applications: Java ME is a cross-platform to develop mobile applications which run across
smartphones. Java is a platform for App Development in Android.
Applications
According to Sun, 3 billion devices run Java. There are many devices where Java is currently used.
Object means a real-world entity such as a pen, chair, table, computer, watch, etc. Object-Oriented
Programming is a methodology or paradigm to design a program using classes and objects.
It simplifies software development and maintenance by
providing some concepts:
o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation
Apart from these concepts, there are some other terms which
are used in Object-Oriented design:
o Coupling
o Cohesion
o Association
o Aggregation
o Composition
Object
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
When one object acquires all the properties and behaviors of a parent object, it is known as inheritance.
It provides code reusability.
It is used to achieve runtime polymorphism.
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.
Encapsulation is the process of combining data and code into a single unit (object / class). In OOP, every
object is associated with its data and code.
In programming, data is defined as variables and code is defined as methods. The java programming
language uses the class concept to implement encapsulation.
Coupling
Coupling refers to the knowledge or information or dependency of another class. It arises when classes are
aware of each other. If a class has the details information of another class, there is strong coupling. In Java, we
use private, protected, and public modifiers to display the visibility level of a class, method, and field. You can
use interfaces for the weaker coupling because there is no concrete implementation.
Cohesion
Cohesion refers to the level of a component which performs a single well-defined task. A single well-defined
task is done by a highly cohesive method. The weakly cohesive method will split the task into separate parts.
The java.io package is a highly cohesive package because it has I/O related classes and interface. However, the
java.util package is a weakly cohesive package because it has unrelated classes and interfaces.
Association
Association represents the relationship between the objects. Here, one object can be associated with one object
or many objects. There can be four types of association between the objects:
o One to One
o One to Many
o Many to One, and
o Many to Many
Let's understand the relationship with real-time examples. For example, One country can have one prime
minister (one to one), and a prime minister can have many ministers (one to many). Also, many MP's can have
one prime minister (many to one), and many ministers can have many departments (many to many).
Association can be undirectional or bidirectional.
Aggregation
Aggregation is a way to achieve Association. Aggregation represents the relationship where one object contains
other objects as a part of its state. It represents the weak relationship between objects. It is also termed as a has-
a relationship in Java. Like, inheritance represents the is-a relationship. It is another way to reuse objects.
Composition
The composition is also a way to achieve Association. The composition represents the relationship where one
object contains other objects as a part of its state. There is a strong relationship between the containing object
and the dependent object. It is the state where containing objects do not have an independent existence. If you
delete the parent object, all the child objects will be deleted automatically.
A way of viewing the world is an idea to illustrate the object-oriented programming concept with an example of
a real-world situation.
Let us consider a situation, I am at my office and I wish to get food to my family members who are at my home
from a hotel. Because of the distance from my office to home, there is no possibility of getting food from a
hotel myself. So, how do we solve the issue?
To solve the problem, let me call zomato (an agent in food delevery community), tell them the variety and
quantity of food and the hotel name from which I wish to delever the food to my family members. Look at the
following image.
Agents and Communities
To solve my food delivery problem, I used a solution by finding an appropriate agent (Zomato) and pass a
message containing my request. It is the responsibility of the agent (Zomato) to satisfy my request. Here, the
agent uses some method to do this. I do not need to know the method that the agent has used to solve my
request. This is usually hidden from me.
So, in object-oriented programming, problem-solving is the solution to our problem which requires the help of
many individuals in the community. We may describe agents and communities as follows.
An object-oriented program is structured as a community of interacting agents, called objects. Where
each object provides a service (data and methods) that is used by other members of the community.
In our example, the online food delivery system is a community in which the agents are zomato and set of
hotels. Each hotel provides a variety of services that can be used by other members like zomato, myself, and my
family in the community.
Responsibilities
In object-oriented programming, behaviors of an object described in terms of responsibilities.
In our example, my request for action indicates only the desired outcome (food delivered to my family). The
agent (zomato) free to use any technique that solves my problem. By discussing a problem in terms of
responsibilities increases the level of abstraction. This enables more independence between the objects in
solving complex problems.
Classes Hierarchies
A graphical representation is often used to illustrate the relationships among the classes (objects) of a
community. This graphical representation shows classes listed in a hierarchical tree-like structure. In this more
abstract class listed near the top of the tree, and more specific classes in the middle of the tree, and the
individuals listed near the bottom.
In object-oriented programming, classes can be organized into a hierarchical inheritance structure. A
child class inherits properties from the parent class that higher in the tree.
1. Everything is an object.
2. Computation is performed by objects communicating with each other, requesting that
other objects perform actions. Objects communicate by sending and receiving mes-
sages. A message is a request for action bundled with whatever arguments may be
necessary to complete the task.
3. Each object has its own memory, which consists of other objects.
4. Every object is an instance of a class. A class simply represents a grouping of similar objects,
such as integers or lists.
5. The class is the repository for behavior associated with an object. That is, all objects that are
instances of the same class can perform the same actions.
6. Classes are organized into a singly rooted tree structure, called the inheritance hier-
archy. Memory and behavior associated with instances of a class are automatically
available to any class associated with a descendant in this tree structure.
The majority of experts cannot deny the fact that Java is one of the most powerful and effective
languages ever created and is the most widely used programming language in many areas.
But, we also know that every coin has two sides; similarly, Java can not run away from this fact
and therefore it has also got its own limitations and benefits; what we call it is a pros and cons of
Java.
In this article, we will acquaint you with the prominent advantages and disadvantages of Java,
which will help you have a clear vision of this language.
Advantages of Java
1. Java is Simple
Any language can be considered as simple if it is easy to learn and understand. The syntax of Java is
straightforward, easy to write, learn, maintain, and understand, the code is easily debuggable.
Moreover, Java is less complex than the languages like C and C++, because many of the complex features of
these languages are being removed from Java such as explicit pointers concept, storage classes, operator
overloading, and many more.
Java is an object-oriented language that helps us to enhance the flexibility and reusability of the code. Using the
OOPs concept, we can easily reuse the object in other programs.
It also helps us to increase security by binding the data and functions into a single unit and not letting it be
accessed by the outside world. It also helps to organize the bigger modules into smaller ones so they are easy to
understand.
Java reduces security threats and risks by avoiding the use of explicit pointers. A pointer stores the memory
address of another value that can cause unauthorized access to memory.
This issue is resolved by removing the concept of pointers. Also, there is a Security manager in Java for each
application that allows us to define the access rules for classes.
Java programs are cheap to develop and maintain as these programs are dependent on a specific hardware
infrastructure to run. We can easily execute them on any machine that reduces the extra cost to maintain.
5. Java is platform-independent
Java offers a very effective boon to its users by providing the feature of platform independence that is Write
Once Run Anywhere(WORA) feature.
The compiled code, i.e the byte code of java is platform-independent and can run on any machine irrespective
of the operating system. We can run this code on any machine that supports the Java Virtual Machine(JVM) as
shown in the figure below:
Java is a portable language due to its platform independence feature. As the Java code can be run on any
platform, it is portable and can be taken to any platform and can be executed on them. Therefore Java also
provides the advantage of portability.
There is automatic memory management in Java that is managed by the Java Virtual Machine(JVM).
Whenever the objects are not used by programs anymore and they do not refer to anything that they do not need
to be dereferenced or removed by the explicit programming.
Java automatically removes the unused objects with the help of the automatic Garbage Collection process.
Java is a multithreaded language that is in Java more than one thread can run at the same time. A thread is the
smallest unit of a process. Multithreading helps us to gain the maximum utilization of CPU.
Multiple threads share a common memory area and increase the efficiency and performance of the application.
These threads run independently of each other without affecting each other.
Java programs are more stable as compared to programs of other languages. Moreover, a new version of Java is
released in no time with more advanced features which makes it more stable.
11. Java is a distributed language
Java is a distributed language as it provides a mechanism for sharing data and programs among multiple
computers that improve the performance and efficiency of the system.
The RMI(Remote Method Invocation) is something that supports the distributed processing in Java. Moreover,
Java also supports Socket Programming and the CORBA technology that helps us to share objects in a
distributed environment.
Java has an efficient memory allocation strategy as it divides the memory mainly in two parts- Heap Area and
Stack Area.
The JVM provides us the memory space for any variable either from the heap area or the stack area. Whenever
we declare a variable JVM gives memory from either stack or heap space.
Disadvantages of Java
To start learning or working upon any programming language you must know its strengths and weaknesses so
that you can utilize the best things out of it and avoid causing the circumstances that portray in the bad side of
the language.
Java has also got some drawbacks that you should know before starting over. Let’s discuss the cons of using
Java.
Java is memory-consuming and significantly slower than native languages such as C or C++. It is also slow
compared to other languages like C and C++ because each code has to be interpreted to the machine level code.
This slow performance is due to the extra level of compilation and abstraction by the JVM. Moreover,
sometimes the garbage collector leads in the poor performance of Java as it consumes more CPU time
Though there are many GUI builders in Java for creating the graphical interface still they are not suitable for
creating complicated UI. There are many inconsistencies while using them.
There are many popular frameworks such as Swing, SWT, JavaFX, JSF for creating GUI. But they are not
mature enough to develop a complex UI. Choosing one of them which can be suitable for you may require
additional research.
3. Java provides no backup facility
Java mainly works on storage and not focuses on the backup of data. This is a major drawback that makes it
lose the interest and ratings among users.
Java requires a significant or major amount of memory space as compared to other languages like C and C++.
During the execution of garbage collection, the memory efficiency and the performance of the system may be
adversely affected.
Java codes are verbose, meaning that there are many words in it and there are many long and complex sentences
that are difficult to read and understand. This can reduce the readability of the code.
Java focuses on being more manageable but at the same time, it has to compromise it with the overly complex
codes and long explanations for each thing.
Simple
Secure
Portable
Object-oriented
Robust
Architecture-neutral (or) Platform Independent
Multi-threaded
Interpreted
High performance
Distributed
Dynamic
Simple
Java programming language is very simple and easy to learn, understand, and code. Most of the syntaxes in java
follow basic programming language C and object-oriented programming concepts are similar to C++. In a java
programming language, many complicated features like pointers, operator overloading, structures, unions, etc.
have been removed. One of the most useful features is the garbage collector it makes java more simple.
Secure
Java is said to be more secure programming language because it does not have pointers concept, java provides a
feature "applet" which can be embedded into a web application. The applet in java does not allow access to
other parts of the computer, which keeps away from harmful programs like viruses and unauthorized access.
Portable
Portability is one of the core features of java which enables the java programs to run on any computer or
operating system. For example, an applet developed using java runs on a wide variety of CPUs, operating
systems, and browsers connected to the Internet.
Object-oriented
Java is said to be a pure object-oriented programming language. In java, everything is an object. It supports all
the features of the object-oriented programming paradigm. The primitive data types java also implemented as
objects using wrapper classes, but still, it allows primitive data types to archive high-performance.
Robust
Java is more robust because the java code can be executed on a variety of environments, java has a strong
memory management mechanism (garbage collector), java is a strictly typed language, it has a strong set of
exception handling mechanism, and many more.
Multi-threaded
Java supports multi-threading programming, which allows us to write programs that do multiple operations
simultaneously.
Interpreted
Java enables the creation of cross-platform programs by compiling into an intermediate representation called
Java bytecode. The byte code is interpreted to any machine code so that it runs on the native machine.
High performance
Java provides high performance with the help of features like JVM, interpretation, and its simplicity.
Distributed
Java programming language supports TCP/IP protocols which enable the java to support the distributed
environment of the Internet. Java also supports Remote Method Invocation (RMI), this feature enables a
program to invoke methods across a network.
Dynamic
Java is said to be dynamic because the java byte code may be dynamically updated on a running system and it
has a dynamic memory allocation and deallocation (objects and garbage collector).
Overview of Java
Java is a computer programming language. Java was created based on C and C++.
Java uses C syntax and many of the object-oriented features are taken from C++.
Before Java was invented there were other languages like COBOL, FORTRAN, C, C++, Small Talk,
etc.
These languages had few disadvantages which were corrected in Java.
Java also innovated many new features to solve the fundamental problems which the previous languages
could not solve.
Java was invented by a team of 13 employees of Sun Microsystems, Inc. which is lead by James
Gosling, in 1991.
The team includes persons like Patrick Naughton, Chris Warth, Ed Frank, and Mike Sheridan, etc.,
Java was developed as a part of the Green project.
Initially, it was called Oak, later it was changed to Java in 1995.
History of Java
The C language developed in 1972 by Dennis Ritchie had taken a decade to become the most popular language.
In 1979, Bjarne Stroustrup developed C++, an enhancement to the C language with included OOP fundamentals
and features.
A project named “Green” was initiated in December of 1990, whose aim was to create a programming tool that
could render obsolete the C and C++ programming languages.
Finally in the year of 1991 the Green Team was created a new Programming language named “OAK”.
After some time they found that there is already a programming language with the name “OAK”.
So, the green team had a meeting to choose a new name. After so many discussions they want to have a coffee.
They went to a Coffee Shop which is just outside of the Gosling’s office and there they have decided name as
“JAVA”.
Java programming language has a rich set of data types. The data type is a category of data stored in variables.
In java, data types are classified into two types and they are as follows.
Java Variables
A variable is a named memory location used to store a data value. A variable can be defined as a container that
holds a data value.
In java, we use the following syntax to create variables.
Syntax
data_type variable_name;
(or)
data_type variable_name_1, variable_name_2,...;
(or)
data_type variable_name = value;
(or)
data_type variable_name_1 = value, variable_name_2 = value,...;
In java programming language variables are classified as follows.
Local variables
Instance variables or Member variables or Global variables
Static variables or Class variables
Final variables
Local variables
The variables declared inside a method or a block are known as local variables. A local variable is visible within
the method in which it is declared. The local variable is created when execution control enters into the method
or block and destroyed after the method or block execution completed.
Let's look at the following example java program to illustrate local variable in java.
Example
Let's look at the following example java program to illustrate instance variable in java.
Example
int x = 100;
Example
Example
void show() {
System.out.println("a = " + a);
a = 20; //Error due to final variable cann't be modified
}
Java Arrays
Creating an array
In the java programming language, an array must be created using new operator and with a specific size. The
size must be an integer value but not a byte, short, or long. We use the following syntax to create an array.
Syntax
Example
list[0] = 10;
System.out.println("Value at index 0 - " + list[0]);
System.out.println("Length of the array - " + list.length);
In java, an array can also be initialized at the time of its declaration. When an array is initialized at the time of
its declaration, it need not specify the size of the array and use of the new operator.
Here, the size is automatically decided based on the number of values that are initialized.
Example
Example
Example
Syntax
When we create a two-dimensional array, it created with a separate index for rows and columns. The individual
element is accessed using the respective row index followed by the column index. A multidimensional array can
be initialized while it has created using the following syntax.
Syntax
When an array is initialized at the time of declaration, it need not specify the size of the array and use of the
new operator. Here, the size is automatically decided based on the number of values that are initialized.
Example
The above statement creates a two-dimensional array of three rows and two columns.
Java Operators
An operator is a symbol used to perform arithmetic and logical operations. Java provides a rich set of operators.
In java, operators are classified into the following four types.
Arithmetic Operators
Relational (or) Comparison Operators
Logical Operators
Assignment Operators
Bitwise Operators
Conditional Operators
+ Addition 10 + 5 = 15
- Subtraction 10 - 5 = 5
* Multiplication 10 * 5 = 50
/ Division 10 / 5 = 2
++ Increment a++
-- Decrement a--
�The addition operator can be used with numerical data types and character or string data type. When it is used
with numerical values, it performs mathematical addition and when it is used with character or string data type
values, it performs concatination (appending).
�The modulus (remainder of the division) operator is used with integer data type only.
�The increment and decrement operators are used as pre-increment or pre-decrement and post-
increment or post-decrement.
�When they are used as pre, the value is get modified before it is used in the actual expresion and when it is
used as post, the value is get modified after the the actual expression evaluation.
Example
< Returns TRUE if the first value is smaller than second value 10 < 5 is FALSE
otherwise returns FALSE
> Returns TRUE if the first value is larger than second value 10 > 5 is TRUE
otherwise returns FALSE
<= Returns TRUE if the first value is smaller than or equal to 10 <= 5 is FALSE
second value otherwise returns FALSE
Operator Meaning Example
>= Returns TRUE if the first value is larger than or equal to second 10 >= 5 is TRUE
value otherwise returns FALSE
!= Returns TRUE if both values are not equal otherwise returns 10 != 5 is TRUE
FALSE
Example
Logical Operators
The logical operators are the symbols that are used to combine multiple conditions into one condition. The
following table provides information about logical operators.
Operator Meaning Example
& Logical AND - Returns TRUE if all conditions are TRUE otherwise returns false & true => false
FALSE
| Logical OR - Returns FALSE if all conditions are FALSE otherwise returns false | true => true
TRUE
^ Logical XOR - Returns FALSE if all conditions are same otherwise returns true ^ true => false
TRUE
! Logical NOT - Returns TRUE if condition is FLASE and returns FALSE if it !false => true
is TRUE
&& short-circuit AND - Similar to Logical AND (&), but once a decision is false & true => false
finalized it does not evaluate remianing.
|| short-circuit OR - Similar to Logical OR (|), but once a decision is finalized it false | true => true
does not evaluate remianing.
�The operators &, |, and ^ can be used with both boolean and integer data type values. When they are used
with integers, performs bitwise operations and with boolean, performs logical operations.
� Logical operators and Short-circuit operators both are similar, but in case of short-circuit operators once the
decision is finalized it does not evaluate remaining expressions.
Example
+= Add both left and right-hand side values and store the result into left-hand A += 10
side variable
-= Subtract right-hand side value from left-hand side variable value and store A -= B
the result into left-hand side variable
*= Multiply right-hand side value with left-hand side variable value and store A *= B
the result into left-hand side variable
/= Divide left-hand side variable value with right-hand side variable value and A /= B
store the result into the left-hand side variable
%= Divide left-hand side variable value with right-hand side variable value and A %= B
store the remainder into the left-hand side variable
|= Logical OR assignment -
Example
Bitwise Operators
The bitwise operators are used to perform bit-level operations in the java programming language.
When we use the bitwise operators, the operations are performed based on binary values.
The following table describes all the bitwise operators in the java programming language.
Let us consider two variables A and B as A = 25 (11001) and B = 20 (10100).
& the result of Bitwise AND is 1 if all the bits are 1 otherwise it is 0 A&B
⇒ 16 (10000)
^ the result of Bitwise XOR is 0 if all the bits are same otherwise it is 1 A^B
⇒ 13 (01101)
<< the Bitwise left shift operator shifts all the bits to the left by the specified number of A << 2
positions ⇒ 100 (1100100)
>> the Bitwise right shift operator shifts all the bits to the right by the specified A >> 2
number of positions ⇒ 6 (00110)
Example
Conditional Operators
The conditional operator is also called a ternary operator because it requires three operands. This operator is
used for decision making. In this operator, first, we verify a condition, then we perform one operation out of the
two operations based on the condition result. If the condition is TRUE the first option is performed, if the
condition is FALSE the second option is performed. The conditional operator is used with the following syntax.
Syntax
Example
Java Expressions
In any programming language, if we want to perform any calculation or to frame any condition etc., we
use a set of symbols to perform the task.
In the above definition, an operator is a symbol that performs tasks like arithmetic operations, logical
operations, and conditional operations, etc.
Operands are the values on which the operators perform the task. Here operand can be a direct value or
variable or address of memory location.
Expression Types
In the java programming language, expressions are divided into THREE types. They are as follows.
Infix Expression
Postfix Expression
Prefix Expression
Infix Expression
The expression in which the operator is used between operands is called infix expression.
The infix expression has the following general structure.
Example
Postfix Expression
The expression in which the operator is used after operands is called postfix expression.
The postfix expression has the following general structure.
Example
Prefix Expression
The expression in which the operator is used before operands is called a prefix expression.
The prefix expression has the following general structure.
Example
In java, the default execution flow of a program is a sequential order. But the sequential order of execution flow
may not be suitable for all situations. Sometimes, we may want to jump from line to another line, we may want
to skip a part of the program, or sometimes we may want to execute a part of the program again and again. To
solve this problem, java provides control statements.
In java, the control statements are the statements which will tell us that in which order the instructions are
getting executed. The control statements are used to control the order of execution according to our
requirements. Java provides several control statements, and they are classified as follows.
if statement
if-else statement
if-elif statement
nested if statement
switch statement
while statement
do-while statement
for statement
for-each statement
Jump Statements
In java, the jump statements are used to terminate a block or take the execution control to the next iteration.
Java provides the following jump statements.
break
continue
return
In java, the selection statements are also known as decision making statements or branching statements or
conditional control statements. The selection statements are used to select a part of the program to be executed
based on a condition. Java provides the following selection statements.
if statement
if-else statement
nested if statement
if-else if statement
switch statement
if statement in java
In java, we use the if statement to test a condition and decide the execution of a block of statements based on
that condition result. The if statement checks, the given condition then decides the execution of a block of
statements. If the condition is True, then the block of statements is executed and if it is False, then the block of
statements is ignored. The syntax and execution flow of if the statement is as follows.
Let's look at the following example java code.
Java Program
import java.util.Scanner;
public class IfStatementTest {
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
System.out.print("Enter any number: ");
int num = read.nextInt();
if((num % 5) == 0) {
System.out.println("We are inside the if-block!");
System.out.println("Given number is divisible by 5!!");
}
System.out.println("We are outside the if-block!!!");
}
}
In the above execution, the number 12 is not divisible by 5. So, the condition becomes False and the condition is
evaluated to False. Then the if statement ignores the execution of its block of statements.
When we enter a number which is divisible by 5, then it produces the output as follows.
if-else statement in java
In java, we use the if-else statement to test a condition and pick the execution of a block of statements out of
two blocks based on that condition result. The if-else statement checks the given condition then decides which
block of statements to be executed based on the condition result. If the condition is True, then the true block of
statements is executed and if it is False, then the false block of statements is executed. The syntax and execution
flow of if-else statement is as follows.
Java Program
import java.util.Scanner;
public class IfElseStatementTest {
public static void main(String[] args) {
Syntax
if(condition_1){
if(condition_2){
inner if-block of statements;
...
}
...
}
Java Program
import java.util.Scanner;
public class NestedIfStatementTest {
public static void main(String[] args) {
Syntax
if(condition_1){
condition_1 true-block;
...
}
else if(condition_2){
condition_2 true-block;
condition_1 false-block too;
...
}
Java Program
import java.util.Scanner;
public class IfElseIfStatementTest {
public static void main(String[] args) {
int num1, num2, num3;
Scanner read = new Scanner(System.in);
System.out.print("Enter any three numbers: ");
num1 = read.nextInt();
num2 = read.nextInt();
num3 = read.nextInt();
if( num1>=num2 && num1>=num3)
System.out.println("\nThe largest number is " + num1) ;
else if (num2>=num1 && num2>=num3)
System.out.println("\nThe largest number is " + num2) ;
else
System.out.println("\nThe largest number is " + num3) ;
System.out.println("\nWe are outside the if-block!!!");
}
}
Java Program
import java.util.Scanner;
public class SwitchStatementTest {
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
System.out.print("Press any digit: ");
int value = read.nextInt();
switch( value )
{
case 0: System.out.println("ZERO") ; break ;
case 1: System.out.println("ONE") ; break ;
case 2: System.out.println("TWO") ; break ;
case 3: System.out.println("THREE") ; break ;
case 4: System.out.println("FOUR") ; break ;
case 5: System.out.println("FIVE") ; break ;
case 6: System.out.println("SIX") ; break ;
case 7: System.out.println("SEVEN") ; break ;
case 8: System.out.println("EIGHT") ; break ;
case 9: System.out.println("NINE") ; break ;
default: System.out.println("Not a Digit") ;
}
}
}
The java programming language provides a set of iterative statements that are used to execute a statement or a
block of statements repeatedly as long as the given condition is true. The iterative statements are also known as
looping statements or repetitive statements. Java provides the following iterative statements.
while statement
do-while statement
for statement
for-each statement
while statement in java
The while statement is used to execute a single statement or block of statements repeatedly as long as the given
condition is TRUE. The while statement is also known as Entry control looping statement. The syntax and
execution flow of while statement is as follows.
Java Program
Java Program
Java Program
The for-each statement has the following syntax and execution flow diagram.
Java Program
break statement
continue statement
The break statement in java is used to terminate a switch or looping statement. That means the break statement
is used to come out of a switch statement and a looping statement like while, do-while, for, and for-each.
�Using the break statement outside the switch or loop statement is not allowed.
The following picture depicts the execution flow of the break statement.
Java Program
The continue statement is used to move the execution control to the beginning of the looping statement. When
the continue statement is encountered in a looping statement, the execution control skips the rest of the
statements in the looping block and directly jumps to the beginning of the loop. The continue statement can be
used with looping statements like while, do-while, for, and for-each.
When we use continue statement with while and do-while statements, the execution control directly jumps to
the condition. When we use continue statement with for statement the execution control directly jumps to the
modification portion (increment/decrement/any modification) of the for loop. The continue statement flow of
execution is as shown in the following figure.
The java programming langauge does not support goto statement, alternatively, the break and continue
statements can be used with label.
The labelled break statement terminates the block with specified label. The labbeled contonue statement takes
the execution control to the beginning of a loop with specified label.
Java Program
import java.util.Scanner;
public class JavaLabelledStatement {
public static void main(String args[]) {
Scanner read = new Scanner(System.in);
reading: for (int i = 1; i <= 3; i++) {
System.out.print("Enter a even number: ");
int value = read.nextInt();
verify: if (value % 2 == 0) {
System.out.println("\nYou won!!!");
System.out.println("Your score is " + i*10 + " out of 30.");
break reading;
} else {
System.out.println("\nSorry try again!!!");
System.out.println("You let with " + (3-i) + " more options...");
continue reading;
}
}
}
}
In java, the return statement used to terminate a method with or without a value. The return statement takes the
execution control to the calling function. That means the return statement transfer the execution control from
called function to the calling function by carrying a value.
�Java allows the use of return-statement with both, with and without return type methods.
In java, the return statement used with both methods with and without return type. In the case of a method with
the return type, the return statement is mandatory, and it is optional for a method without return type.
When a return statement used with a return type, it carries a value of return type. But, when it is used without a
return type, it does not carry any value. Instead, simply transfers the execution control.
Java Program
import java.util.Scanner;
public class JavaReturnStatementExample {
int value; int readValue() {
Scanner read = new Scanner(System.in);
System.out.print("Enter any number: ");
return this.value=read.nextInt(); }
void showValue(int value) {
for(int i = 0; i <= value; i++) {
if(i == 5) return;
System.out.println(i);
} }
public static void main(String[] args) {
JavaReturnStatementExample obj = new JavaReturnStatementExample();
obj.showValue(obj.readValue());
} }
Java Classes
Java is an object-oriented programming language, so everything in java program must be based on the
object concept. In a java programming language, the class concept defines the skeleton of an object.
The java class is a template of an object. The class defines the blueprint of an object. Every class in java
forms a new data type.
Once a class got created, we can generate as many objects as we want. Every class defines the properties
and behaviors of an object. All the objects of a class have the same properties and behaviors that were
defined in the class.
Every class of java programming language has the following characteristics.
Look at the following picture to understand the class and object concept.
Creating a Class
In java, we use the keyword class to create a class. A class in java contains properties as variables and behaviors
as methods. Following is the syntax of class in the java.
Syntax
class <ClassName>{
data members declaration;
methods defination;
}
�The ClassName must begin with an alphabet, and the Upper-case letter is preferred.
�The ClassName must follow all naming rules.
Creating an Object
In java, an object is an instance of a class. When an object of a class is created, the class is said to be
instantiated. All the objects that are created using a single class have the same properties and methods. But the
value of properties is different for every object. Following is the syntax of class in the java.
Syntax
�The objectName must begin with an alphabet, and a Lower-case letter is preferred.
�The objectName must follow all naming rules.
Java Methods
A method is a block of statements under a name that gets executes only when it is called. Every method is used
to perform a specific task. The major advantage of methods is code re-usability (define the code once, and use it
many times).
In a java programming language, a method defined as a behavior of an object. That means, every method in java
must belong to a class.
Every method in java must be declared inside a class.
Every method declaration has the following characteristics.
Creating a method
A method is created inside the class and it may be created with any access specifier. However, specifying access
specifier is optional.
Following is the syntax for creating methods in java.
Syntax
class <ClassName>{
<accessSpecifier> <returnType> <methodName>( parameters ){
...
block of statements;
...
}
}
�The methodName must begin with an alphabet, and the Lower-case letter is preferred.
�The methodName must follow all naming rules.
� If you don't want to pass parameters, we ignore it.
� If a method defined with return type other than void, it must contain the return statement, otherwise, it may
be ignored.
Calling a method
In java, a method call precedes with the object name of the class to which it belongs and a dot operator. It may
call directly if the method defined with the static modifier. Every method call must be made, as to the method
name with parentheses (), and it must terminate with a semicolon.
Syntax
<objectName>.<methodName>( actualArguments );
Example
import java.util.Scanner;
public class JavaMethodsExample {
int sNo;
String name;
Scanner read = new Scanner(System.in);
void readData() {
System.out.print("Enter Serial Number: ");
sNo = read.nextInt();
System.out.print("Enter the Name: ");
name = read.next();
}
static void showData(int sNo, String name) {
System.out.println("Hello, " + name + "! your serial number is " + sNo);
}
public static void main(String[] args) {
Syntax
<returnType> <methodName>(dataType...parameterName);
Example
for(int i : list) {
System.out.print(i + "\t");
}
}
public static void main(String[] args) {
JavaMethodWithVariableArgs obj = new JavaMethodWithVariableArgs();
obj.diaplay(1, 2);
obj.diaplay(10, 20, 30, 40, 50);
} }
� When a method has both the normal parameter and variable-argument, then the variable argument must be specified at the end in
the parameters list.
Constructor
A constructor is a special method of a class that has the same name as the class name. The constructor gets
executes automatically on object creation. It does not require the explicit method call. A constructor may have
parameters and access specifiers too. In java, if you do not provide any constructor the compiler automatically
creates a default constructor.
Let's look at the following example java code.
Example
ConstructorExample() {
System.out.println("Object created!");
}
public static void main(String[] args) {
A string is a sequence of characters surrounded by double quotations. In a java programming language, a string
is the object of a built-in class String.
In the background, the string values are organized as an array of a character data type.
The string created using a character array can not be extended. It does not allow to append more characters after
its definition, but it can be modified.
Let's look at the following example java code.
Example
char[] name = {'J', 'a', 'v', 'a', ' ', 'T', 'u', 't', 'o', 'r', 'i', 'a', 'l', 's'};
//name[14] = '@'; //ArrayIndexOutOfBoundsException
name[5] = '-';
System.out.println(name);
The String class defined in the package java.lang package. The String class
implements Serializable, Comparable, and CharSequence interfaces.
The string created using the String class can be extended. It allows us to add more characters after its
definition, and also it can be modified.
Let's look at the following example java code.
Example
Example
�The String class constructor accepts both string and character array as an argument.
equalsIgnoreCase(String) Checks whether two strings are same, ignoring case boolean
startsWith(String) Checks whether a string starts with the specified string boolean
endsWith(String) Checks whether a string ends with the specified string boolean
indexOf(String) Finds the first index of argument string in object string int
lastIndexOf(String) Finds the last index of argument string in object string int
Method Description Return Value
replace(String, String) Replaces the first string with second string String
replaceAll(String, String) Replaces the first string with second string at all String
occurrences.
substring(int, int) Extracts a sub-string from specified start and end index String
values
join(String, String, ...) Joins all strings, first string as delimiter. String
Java Program
}
Inheritance Inheritance concept
Inheritance Concept
The inheritance is a very useful and powerful concept of object-oriented programming. In java, using the
inheritance concept, we can use the existing features of one class in another class.
The inheritance provides a great advantage called code re-usability.
With the help of code re-usability, the commonly used code in an application need not be written again
and again.
Inheritance Basics
In inheritance, we use the terms like parent class, child class, base class, derived class, superclass, and
subclass.
The Parent class is the class which provides features to another class. The parent class is also known
as Base class or Superclass.
The Child class is the class which receives features from another class. The child class is also known as
the Derived Class or Subclass.
In the inheritance, the child class acquires the features from its parent class. But the parent class never acquires
the features from its child class.
The java programming language does not support multiple inheritance type. However, it provides an alternate
with the concept of interfaces.
Syntax
class <ChildClassName> extends <ParentClassName>{
...
//Implementation of child class
... }
In a java programming language, a class extends only one class. Extending multiple classes is not allowed in
java.
Let's look at individual inheritance types and how they get implemented in java with an example.
class ParentClass{
int a;
void setData(int a) {
this.a = a;
}
}
class ChildClass extends ParentClass{
void showData() {
System.out.println("Value of a is " + a);
}
}
class ChildChildClass extends ChildClass{
void display() {
System.out.println("Inside ChildChildClass!");
}
}
public class MultipleInheritance {
public static void main(String[] args) {
ChildChildClass obj = new ChildChildClass();
obj.setData(100);
obj.showData();
obj.display();
}
}
Example
class ParentClass{
int a;
void setData(int a) {
this.a = a;
}
}
class ChildClass extends ParentClass{
void showData() {
System.out.println("Inside ChildClass!");
System.out.println("Value of a is " + a);
}
}
class ChildClassToo extends ParentClass{
void display() {
System.out.println("Inside ChildClassToo!");
System.out.println("Value of a is " + a);
} }
public class HierarchicalInheritance {
In java, we cannot employ all access specifiers on everything. The following table describes where we can
apply the access specifiers.
Let's look at the following example java code, which generates an error because a class does not allow private
access specifier unless it is an inner class.
Example
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.
�The public members can be accessed everywhere.
�The private members can be accessed only inside the same class.
�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.
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);
}
}
class ChildClass extends ParentClass{
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 {
public static void main(String[] args) {
ChildClass obj = new ChildClass();
obj.showData();
obj.accessData();
} }
Java Constructors in Inheritance
It is very important to understand how the constructors get executed in the inheritance concept. In the
inheritance, the constructors never get inherited to any child class.
In java, the default constructor of a parent class called automatically by the constructor of its child class. That
means when we create an object of the child class, the parent class constructor executed, followed by the child
class constructor executed.
Let's look at the following example java code.
Example
class ParentClass{
int a;
ParentClass(){
System.out.println("Inside ParentClass constructor!");
}
}
class ChildClass extends ParentClass{
ChildClass(){
System.out.println("Inside ChildClass constructor!!");
} }
class ChildChildClass extends ChildClass{
ChildChildClass(){
System.out.println("Inside ChildChildClass constructor!!");
}
}
public class ConstructorInInheritance {
public static void main(String[] args) {
ChildChildClass obj = new ChildChildClass();
}
}
However, if the parent class contains both default and parameterized constructor, then only the default
constructor called automatically by the child class constructor.
Let's look at the following example java code.
Example
class ParentClass{
int a;
ParentClass(int a){
System.out.println("Inside ParentClass parameterized constructor!");
this.a = a;
}
ParentClass(){
System.out.println("Inside ParentClass default constructor!");
}
}
class ChildClass extends ParentClass{
ChildClass(){
System.out.println("Inside ChildClass constructor!!");
}
}
public class ConstructorInInheritance {
public static void main(String[] args) {
ChildClass obj = new ChildClass();
}
}
The parameterized constructor of parent class must be called explicitly using the super keyword.
When both parent class and child class have data members with the same name, then the super keyword is used
to refer to the parent class data member from child class.
Example
class ParentClass{
int num = 10;
}
class ChildClass extends ParentClass{
int num = 20;
void showData() {
System.out.println("Inside the ChildClass");
System.out.println("ChildClass num = " + num);
System.out.println("ParentClass num = " + super.num);
}
}
public class SuperKeywordExample {
public static void main(String[] args) {
ChildClass obj = new ChildClass();
obj.showData();
System.out.println("\nInside the non-child class");
System.out.println("ChildClass num = " + obj.num);
//System.out.println("ParentClass num = " + super.num); //super can't be used here } }
When both parent class and child class have method with the same name, then the super keyword is used to
refer to the parent class method from child class.
Example
class ParentClass{
int num1 = 10;
void showData() {
System.out.println("\nInside the ParentClass showData method");
System.out.println("ChildClass num = " + num1);
}
}
class ChildClass extends ParentClass{
int num2 = 20;
void showData() {
System.out.println("\nInside the ChildClass showData method");
System.out.println("ChildClass num = " + num2);
super.showData();
}
}
public class SuperKeywordExample {
public static void main(String[] args) {
ChildClass obj = new ChildClass();
obj.showData();
//super.showData(); // super can't be used here
}
}
When an object of child class is created, it automatically calls the parent class default-constructor before it's
own. But, the parameterized constructor of parent class must be called explicitly using the super keyword
inside the child class constructor.
Example
class ParentClass{
int num1;
ParentClass(){
System.out.println("\nInside the ParentClass default constructor");
num1 = 10;
}
ParentClass(int value){
System.out.println("\nInside the ParentClass parameterized constructor");
num1 = value;
} }
class ChildClass extends ParentClass{
int num2;
ChildClass(){
super(100);
System.out.println("\nInside the ChildClass constructor");
num2 = 200;
} }
public class SuperKeywordExample {
public static void main(String[] args) {
ChildClass obj = new ChildClass();
}
}
To call the parameterized constructor of the parent class, the super keyword must be the first statement inside
the child class constructor, and we must pass the parameter values.
Example
class ParentClass{
int num = 10;
final void showData() {
System.out.println("Inside ParentClass showData() method");
System.out.println("num = " + num);
} }
class ChildClass extends ParentClass{
void showData() {
System.out.println("Inside ChildClass showData() method");
System.out.println("num = " + num);
} }
public class FinalKeywordExample {
public static void main(String[] args) {
ChildClass obj = new ChildClass();
obj.showData();
}
}
final with class
When a class defined with final keyword, it can not be extended by any other class.
Example
Java Polymorphism
The polymorphism is the process of defining same method with different implementation.
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.
Example
import java.util.Arrays;
public class AdHocPolymorphismExample {
void sorting(int[] list) {
Arrays.parallelSort(list);
System.out.println("Integers after sort: " + Arrays.toString(list) );
}
void sorting(String[] names) {
Arrays.parallelSort(names);
System.out.println("Names after sort: " + Arrays.toString(names) );
}
public static void main(String[] args) {
AdHocPolymorphismExample obj = new AdHocPolymorphismExample();
int list[] = {2, 3, 1, 5, 4};
obj.sorting(list); // Calling with integer array
String[] names = {"rama", "raja", "shyam", "seeta"};
obj.sorting(names); // Calling with String array
}
}
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.
Example
class ParentClass{
int num = 10;
void showData() {
System.out.println("Inside ParentClass showData() method");
System.out.println("num = " + num);
}
}
class ChildClass extends ParentClass{
void showData() {
System.out.println("Inside ChildClass showData() method");
System.out.println("num = " + num);
}
}
public class PurePolymorphism {
public static void main(String[] args) {
ParentClass obj = new ParentClass();
obj.showData();
obj = new ChildClass();
obj.showData();
}
}
parent class. When both parent and child classes have the same method, then that method is said to be the
overriding method.
The method overriding enables the child class to change the implementation of the method which aquired from
parent class according to its requirement.
In the case of the method overriding, the method binding happens at run time. The method binding which
happens at run time is known as late binding. So, the method overriding follows late binding. The method
overriding is also known as dynamic method dispatch or run time polymorphism or pure polymorphism.
Example
class ParentClass{
int num = 10;
void showData() {
System.out.println("Inside ParentClass showData() method");
System.out.println("num = " + num);
}
}
class ChildClass extends ParentClass{
void showData() {
System.out.println("Inside ChildClass showData() method");
System.out.println("num = " + num);
}
}
public class PurePolymorphism {
public static void main(String[] args) {
ParentClass obj = new ParentClass();
obj.showData();
obj = new ChildClass();
obj.showData();
} }
In java, an abstract class may contain abstract methods (methods without implementation) and also non-abstract
methods (methods with implementation).
Syntax
Example
import java.util.*;
abstract class Shape {
int length, breadth, radius;
Scanner input = new Scanner(System.in);
abstract void printArea();
}
class Rectangle extends Shape {
void printArea() {
System.out.println("*** Finding the Area of Rectangle ***");
System.out.print("Enter length and breadth: ");
length = input.nextInt();
breadth = input.nextInt();
System.out.println("The area of Rectangle is: " + length * breadth);
}
}
class Triangle extends Shape {
void printArea() {
System.out.println("\n*** Finding the Area of Triangle ***");
System.out.print("Enter Base And Height: ");
length = input.nextInt();
breadth = input.nextInt();
System.out.println("The area of Triangle is: " + (length * breadth) / 2);
}
}
class Cricle extends Shape {
void printArea() {
System.out.println("\n*** Finding the Area of Cricle ***");
System.out.print("Enter Radius: ");
radius = input.nextInt();
System.out.println("The area of Cricle is: " + 3.14f * radius * radius);
}
}
public class AbstractClassExample {
public static void main(String[] args) {
Rectangle rec = new Rectangle();
rec.printArea();
Triangle tri = new Triangle();
tri.printArea();
Cricle cri = new Cricle();
cri.printArea();
}
}
� An abstract class can not be instantiated but can be referenced. That means we can not create an object of an
abstract class, but base reference can be created.
In the above example program, the child class objects are created to invoke the overridden abstract method. But
we may also create base class reference and assign it with child class instance to invoke the same. The main
method of the above program can be written as follows that produce the same output.
Example
An abstract class may contain final methods that can not be overridden.
An abstract class may contain static methods, but the abstract method can not be static.
An abstract class may have a constructor that gets executed when the child class object created.
An abstract method must be overridden by the child class, otherwise, it must be defined as an abstract
class.
An abstract class can not be instantiated but can be referenced.
Java Object Class
In java, the Object class is the super most class of any class hierarchy. The Object class in the java
programming language is present inside the java.lang package.
Every class in the java programming language is a subclass of Object class by default.
The Object class is useful when you want to refer to any object whose type you don't know. Because it is the
superclass of all other classes in java, it can refer to any type of object.
Return
Method Description Value
hashCode() returns the hashcode number for object being used. int
wait() causes the current thread to wait, until another thread void
notifies.
Return
Method Description Value
wait(long,int) causes the current thread to wait for the specified void
milliseconds and nanoseconds, until another thread notifies.
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 different forms of inheritance in java.
Specialization
Specification
Construction
Extension
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.
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.
Specialization
This is another most common use of inheritance. Two different mechanisms are provided by Java, interface
and abstract, to make use of subclassification for specification. Subtype is formed and substitutability is
explicitly upheld.
Mostly, not used for refinement of its parent class, but instead is used for definitions of the properties
provided by its parent.
Specification
The next most common form of inheritance involves specification. The parent class specifies some
behavior, but does not implement the behavior
Child class implements the behavior
Similar to Java interface or abstract class
When parent class does not implement actual behavior but merely defines the behavior that
will be implemented in child classes
Example, Java 1.1 Event Listeners:
ActionListener, MouseListener, and so on specify behavior, but must be subclassed.
Child class inherits most of its functionality from parent, but may change the name or parameters of methods
inherited from parent class to form its interface.
This type of inheritance is also widely used for code reuse purposes. It simplifies the construction of newly
formed abstraction but is not a form of subtype, and often violates substitutability.
Example is Stack class defined in Java libraries.
Construction
The parent class is used only for its behavior, the child class has no is-a relationship to the parent.
Child modify the arguments or names of methods
An example might be subclassing the idea of a Set from an existing List class.
Child class is not a more specialized form of parent class; no substitutability
Subclassification for extension occurs when a child class only adds new behavior to the parent class and
does not modify or alter any of the inherited attributes.
Such subclasses are always subtypes, and substitutability can be used.
Example of this type of inheritance is done in the definition of the class Properties which is an extension of
the class HashTable.
Generalization or Extension
The child class generalizes or extends the parent class by providing more functionality
In some sense, opposite of subclassing for specialization
The child doesn't change anything inherited from the parent, it simply adds new features
Often used when we cannot modify existing base parent class
Example, ColoredWindow inheriting from Window
Add additional data fields
Override window display methods
Subclassification for limitation occurs when the behavior of the subclass is smaller or more restrictive that
the behavior of its parent class.
Like subclassification for extension, this form of inheritance occurs most frequently when a programmer is
building on a base of existing classes.
Is not a subtype, and substitutability is not proper.
Limitation
The child class limits some of the behavior of the parent class.
Example, you have an existing List data type, and you want a Stack
Inherit from List, but override the methods that allow access to elements other than top so as to
produce errors.
Although the Java does not permit a subclass to be formed be inheritance from more than one parent class,
several approximations to the concept are possible.
Combination
Two or more classes that seem to be related, but its not clear who should be the parent and who
should be the child.
Example: Mouse and TouchPad and JoyStick
Better solution, abstract out common parts to new parent class, and use subclassing for
specialization.
Summary of Forms of Inheritance
Specialization. The child class is a special case of the parent class; in other words, the child class
is a subtype of the parent class.
Specification. The parent class defines behavior that is implemented in the child class but not in
the parent class.
Construction. The child class makes use of the behavior provided by the parent class, but is not a
subtype of the parent class.
Generalization. The child class modifies or overrides some of the methods of the parent class.
Extension. The child class adds new functionality to the parent class, but does not change any
inherited behavior.
Limitation. The child class restricts the use of some of the behavior inherited from the parent
class.
Variance. The child class and parent class are variants of each other, and the class-subclass
relationship is arbitrary.
Combination. The child class inherits features from more than one parent class. This is multiple
inheritance and will be the subject of a later chapter.
UNIT - II
Java Package
A java package is a group of similar types of classes, interfaces and sub-packages.
Package in java can be categorized in two form, built-in package and user-defined package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
1. Maintenance: Java packages are used for proper maintenance. If any developer newly joined a company, he
can easily reach to files needed.
2. Reusability: We can place the common code in a common folder so that everybody can check that folder and
use it whenever needed.
3. Name conflict: Packages help to resolve the naming conflict between the two classes with the same name.
Assume that there are two classes with the same name Student.java.
Each class will be stored in its own packages such as stdPack1 and stdPack2 without having any conflict of
names.
4. Organized: It also helps in organizing the files within our project.
5. Access Protection: A package provides access protection. It can be used to provide visibility control. The
members of the class can be defined in such a manner that they will be visible only to elements of that package.
Here, packageName is the name of package. The package statement must be the first line in a java
source code file followed by one or more classes.
For example:
package myPackage;
public class A {
// class body
}
While developing your project, you must follow some naming conventions regarding packages
declaration. Let’s take an example to understand the convention.
See below a complete package structure of the project.
1. Suppose you are working in IBM and the domain name of IBM is www.ibm.com. You can
declare the package by reversing the domain like this:
package com.ibm;
where,
com ➝ It is generally company specification name and the folder starts with com which is
called root folder.
ibm ➝ Company name where the product is developed. It is the subfolder.
2. hdfc ➝ Client name for which we are developing our product or working for the project.
3. loan ➝ Name of the project.
4. homeloan ➝ It is the name of the modules of the loan project. There are a number of modules in
the loan project like a Home loan, Car loan, or Personal loan. Suppose you are working for Home
loan module.
This is a complete packages structure like a professional which is adopted in the company.
Another example is:
package com.tcs.icici.loan.carloan.penalty;
Note: Keep in mind Root folder should be always the same for all the classes.
�The private members can be accessed only inside the same class.
�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 When we run this code, it produce the following output.
In java, the import keyword used to import built-in and user-defined packages.
When a package has imported, we can refer to all the classes of that package using their
name directly.
The import statement must be after the package statement, and before any other
statement.
Using an import statement, we may import a specific class or all the classes from a
package.
�Using one import statement, we may import only one package or a class.
� Using an import statement, we can not import a class directly, but it must be a part of a
package.
�A program may contain any number of import statements.
Importing specific class
Using an importing statement, we can import a specific class. The following syntax is employed
to import a specific class.
Syntax
import packageName.ClassName;
Let's look at an import statement to import a built-in package and Scanner class.
Example
package myPackage;
import java.util.Scanner;
public class ImportingExample {
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
int i = read.nextInt();
System.out.println("You have entered a number " + i);
} }
In the above code, the class ImportingExample belongs to myPackage package, and it also
importing a class called Scanner from java.util package.
import packageName.*;
In the above code, the class ImportingExample belongs to myPackage package, and it also
importing all the classes like Scanner, Random, Stack, Vector, ArrayList, HashSet, etc. from
the java.util package.
� The import statement imports only classes of the package, but not sub-packages and its
classes.
� We may also import sub-packages by using a symbol '.' (dot) to separate parent package and
sub-package.
Consider the following import statement.
import java.util.*;
The above import statement util is a sub-package of java package. It imports all the classes
of util package only, but not classes of java package.
In java, an interface is similar to a class, but it contains abstract methods and static final
variables only. The interface in Java is another mechanism to achieve abstraction.
We may think of an interface as a completely abstract class. None of the methods in the
interface has an implementation, and all the variables in the interface are constants.
All the methods of an interface, implemented by the class that implements it.
The interface in java enables java to support multiple-inheritance. An interface may
extend only one interface, but a class may implement any number of interfaces.
�An interface is a container of abstract methods and static final variables.
�An interface, implemented by a class. (class implements interface).
�An interface may extend another interface. (Interface extends Interface).
�An interface never implements another interface, or class.
�A class may implement any number of interfaces.
�We can not instantiate an interface.
�Specifying the keyword abstract for interface methods is optional, it automatically added.
�All the members of an interface are public by default.
Defining an interface is similar to that of a class. We use the keyword interface to define an
interface. All the members of an interface are public by default. The following is the syntax for
defining an interface.
Syntax
interface InterfaceName{
...
members declaration; ...
}
interface HumanInterfaceExample {
void learn(String str);
void work();
int duration = 10;
}
In the above code defines an interface HumanInterfaceExample that contains two abstract
methods learn(), work() and one constant duration.
Every interface in Java is auto-completed by the compiler. For example, in the above example
code, no member is defined as public, but all are public automatically.
The above code automatically converted as follows.
Converted code
interface HumanInterfaceExample {
public abstract void learn(String str);
public abstract void work();
public static final int duration = 10;
}
In the next tutorial, we will learn how a class implements an interface to make use of the
interface concept.
interface Human {
void learn(String str);
void work();
int duration = 10;
}
class Programmer implements Human{
public void learn(String str) {
System.out.println("Learn using " + str);
}
public void work() {
System.out.println("Develop applications");
}
}
public class HumanTest {
public static void main(String[] args) {
Programmer trainee = new Programmer();
trainee.learn("coding");
trainee.work();
}
}
In the above code defines an interface Human that contains two abstract methods learn(),
work() and one constant duration. The class Programmer implements the interface. As it
implementing the Human interface it must provide the body of all the methods those defined in
the Human interface.
Let's look at an example code to define a class that implements multiple interfaces.
Example
In the code defines two interfaces Human and Recruitment, and a class Programmer
implements both the interfaces.
The nested interface cannot be accessed directly. We can only access the nested interface by
using outer interface or outer class name followed by dot( . ), followed by the nested interface
name.
Stream in java
In java, the IO operations are performed using the concept of streams.
Generally, a stream means a continuous flow of data.
In java, a stream is a logical container of data that allows us to read from and write to it.
A stream can be linked to a data source, or data destination, like a console, file or
network connection by java IO system.
The stream-based IO operations are faster than normal IO operations.
The Stream is defined in the java.io package.
To understand the functionality of java streams, look at the following picture.
In java, the stream-based IO operations are performed using two separate streams input
stream and output stream.
The input stream is used for input operations, and the output stream is used for output
operations.
The java stream is composed of bytes.
In Java, every program creates 3 streams automatically, and these streams are attached to
the console.
System.out: standard output stream for console output operations.
System.in: standard input stream for console input operations.
System.err: standard error stream for console error output operations.
The Java streams support many different kinds of data, including simple bytes, primitive
data types, localized characters, and objects.
Byte Stream
Character Stream
The following picture shows how streams are categorized, and various built-in classes used by
the java IO system.
Both character and byte streams essentially provides a convenient and efficient way to handle
data streams in Java.
The InputStream class has defined as an abstract class, and it has the following methods which
have implemented by its concrete classes.
1 int available()
It returns the number of bytes that can be read from the input stream.
2 int read()
3 int read(byte[] b)
It reads a chunk of bytes from the input stream and store them in its byte array, b.
4 void close()
It closes the input stream and also frees any resources connected with this input stream.
OutputStream class
The OutputStream class has defined as an abstract class, and it has the following methods which
have implemented by its concrete classes.
1 void write(int n)
2 void write(byte[] b)
3 void flush()
It flushes the output steam by forcing out buffered bytes to be written out.
4 void close()
It closes the output stream and also frees any resources connected with this output stream.
In java, when the IO stream manages 16-bit Unicode characters, it is called a character
stream.
The unicode set is basically a type of character set where each character corresponds to a
specific numeric value within the given character set, and every programming language
has a character set.
In java, the character stream is a 16 bits carrier. The character stream in java allows us to
transmit 16 bits of data.
The character stream was introduced in Java 1.1 version. The charater stream
The java character stream is defined by two abstract classes, Reader and Writer. The
Reader class used for character stream based input operations, and the Writer class used
for charater stream based output operations.
The Reader and Writer classes have several concreate classes to perform various IO
operations based on the character stream.
The following picture shows the classes used for character stream operations.
Reader class
The Reader class has defined as an abstract class, and it has the following methods which have
implemented by its concrete classes.
1 int read()
It reads a chunk of charaters from the input stream and store them in its byte array,
cbuffer.
S.No. Method with Description
5 String readLine()
It reads a line of text. A line is considered to be terminated by any oneof a line feed
('\n'), a carriage return ('\r'), or a carriage returnfollowed immediately by a linefeed.
6 boolean ready()
7 void close()
It closes the input stream and also frees any resources connected with this input stream.
Writer class
The Writer class has defined as an abstract class, and it has the following methods which have
implemented by its concrete classes.
1 void flush()
It flushes the output steam by forcing out buffered bytes to be written out.
4 void write(int c)
It writes a string.
7 Writer append(char c)
10 void close()
It closes the output stream and also frees any resources connected with this output
stream.
Example
Example
3. Reading console input using Console class in java
Reading input data using the Console class is the most commonly used method. This class was introduced in
Java 1.6 version.
The Console class has defined in the java.io package.
Consider the following example code to understand how to read console input using Console class.
Example
import java.io.*;
public class ReadingDemo {
public static void main(String[] args) {
String name;
Console con = System.console();
if(con != null) {
name = con.readLine("Please enter your name : ");
System.out.println("Hello, " + name + "!!");
}
else {
System.out.println("Console not available.");
}
}
}
1 File(String pathname)
It creates a new File instance by converting the givenpathname string into an abstract
pathname. If the given string isthe empty string, then the result is the empty abstract
pathname.
4 File(URI uri)
It creates a new File instance by converting the given file: URI into an abstract
pathname.
1 String getName()
It returns the name of the file or directory that referenced by the current File object.
2 String getParent()
It returns the pathname of the pathname's parent, or null if the pathname does not name
a parent directory.
3 String getPath()
It returns the path of curent File.
4 File getParentFile()
It returns the path of the current file's parent; or null if it does not exist.
5 String getAbsolutePath()
It returns the current file or directory path from the root.
6 boolean isAbsolute()
It returns true if the current file is absolute, false otherwise.
7 boolean isDirectory()
It returns true, if the current file is a directory; otherwise returns false.
8 boolean isFile()
It returns true, if the current file is a file; otherwise returns false.
S.No. Methods with Description
9 boolean exists()
It returns true if the current file or directory exist; otherwise returns false.
10 boolean canRead()
It returns true if and only if the file specified exists and can be read by the application;
false otherwise.
11 boolean canWrite()
It returns true if and only if the file specified exists and the application is allowed to
write to the file; false otherwise.
12 long length()
It returns the length of the current file.
13 long lastModified()
It returns the time that specifies the file was last modified.
14 boolean createNewFile()
It returns true if the named file does not exist and was successfully created; false if the
named file already exists.
15 boolean delete()
It deletes the file or directory. And returns true if and only if the file or directory is
successfully deleted; false otherwise.
16 void deleteOnExit()
It sends a requests that the file or directory needs be deleted when the virtual machine
terminates.
17 boolean mkdir()
It returns true if and only if the directory was created; false otherwise.
18 boolean mkdirs()
It returns true if and only if the directory was created, along with all necessary parent
directories; false otherwise.
otherwise.
21 boolean setReadOnly()
It sets the file permission to only read operations; Returns true if and only if the
operation succeeded; false otherwise.
22 String[] list()
It returns an array of strings containing names of all the files and directories in the
current directory.
24 File[] listFiles()
It returns an array of file references containing names of all the files and directories in
the current directory.
equal to this abstract pathname, a value less than zero if this abstract pathname is
lexicographically less than the argument, or a value greater than zero if this abstract
pathname is lexicographically greater than the argument.
import java.io.*;
public class FileClassTest {
}
Let's look at the following java code to list all the files in a directory including the files present
in all its subdirectories.
Example
import java.util.Scanner;
import java.io.*;
public class ListingFiles {
public static void main(String[] args) {
String path = null;
Scanner read = new Scanner(System.in);
System.out.print("Enter the root directory name: ");
path = read.next() + ":\\";
File f_ref = new File(path);
if (!f_ref.exists()) {
printLine();
System.out.println("Root directory does not exists!");
printLine();
} else {
String ch = "y";
while (ch.equalsIgnoreCase("y")) {
printFiles(path);
System.out.print("Do you want to open any sub-directory
(Y/N): ");
ch = read.next().toLowerCase();
if (ch.equalsIgnoreCase("y")) {
System.out.print("Enter the sub-directory name: ");
path = path + "\\\\" + read.next();
File f_ref_2 = new File(path);
if (!f_ref_2.exists()) {
printLine();
System.out.println("The sub-directory does not
exists!");
printLine();
int lastIndex = path.lastIndexOf("\\");
path = path.substring(0, lastIndex);
}
}
}
}
System.out.println("***** Program Closed *****");
}
In java, there multiple ways to read data from a file and to write data to a file. The most
commonly used ways are as follows.
FileInputStream - It is a built-in class in java that allows reading data from a file. This
class has implemented based on the byte stream. The FileInputStream class provides a
method read() to read data from a file byte by byte.
FileOutputStream - It is a built-in class in java that allows writing data to a file. This
class has implemented based on the byte stream. The FileOutputStream class provides a
method write() to write data to a file byte by byte.
Let's look at the following example program that reads data from a file and writes the same to
another file using FileInoutStream and FileOutputStream classes.
Example
import java.io.*;
public class FileReadingTest {
try {
in = new FileInputStream("C:\\Raja\\Input-File.txt");
out = new FileOutputStream("C:\\Raja\\Output-File.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
System.out.println("Reading and Writing has been success!!!");
}
catch(Exception e){
System.out.println(e);
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
FileReader - It is a built-in class in java that allows reading data from a file. This class
has implemented based on the character stream. The FileReader class provides a
method read() to read data from a file character by character.
FileWriter - It is a built-in class in java that allows writing data to a file. This class has
implemented based on the character stream. The FileWriter class provides a
method write() to write data to a file character by character.
Let's look at the following example program that reads data from a file and writes the same to
another file using FIleReader and FileWriter classes.
Example
import java.io.*;
public class FileIO {
public static void main(String args[]) throws IOException {
FileReader in = null;
FileWriter out = null;
try {
in = new FileReader("C:\\Raja\\Input-File.txt");
out = new FileWriter("C:\\Raja\\Output-File.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
System.out.println("Reading and Writing in a file is done!!!");
}
catch(Exception e) {
System.out.println(e);
}
finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
RandomAccessFile in Java
In java, the java.io package has a built-in class RandomAccessFile that enables a file to be
accessed randomly. The RandomAccessFile class has several methods used to move the cursor
position in a file.
A random access file behaves like a large array of bytes stored in a file.
RandomAccessFile Constructors
The RandomAccessFile class in java has the following constructors.
It creates a random access file stream to read from, and optionally to write to, the file specified
argument.
It creates a random access file stream to read from, and optionally to write to, a file with th
fileName.
Access Modes
Using the RandomAccessFile, a file may created in th following modes.
r - Creates the file with read mode; Calling write methods will result in an IOException.
rw - Creates the file with read and write mode.
rwd - Creates the file with read and write mode - synchronously. All updates to file
content is written to the disk synchronously.
rws - Creates the file with read and write mode - synchronously. All updates to file
content or meta data is written to the disk synchronously.
RandomAccessFile methods
The RandomAccessFile class in java has the following methods.
1 int read()
It reads byte of data from a file. The byte is returned as an integer in the range 0-255.
S.No. Methods with Description
2 int read(byte[] b)
It reads byte of data from file upto b.length, -1 if end of file is reached.
It reads bytes initialising from offset position upto b.length from the buffer.
4 boolean readBoolean()
5 byte readByte()
6 char readChar()
It reads a character value from file.
7 double readDouble()
8 float readFloat()
It reads a float value from file.
9 long readLong()
10 int readInt()
11 void readFully(byte[] b)
It reads bytes initialising from offset position upto b.length from the buffer.
S.No. Methods with Description
It reads bytes initialising from offset position upto b.length from the buffer.
13 String readUTF()
It sets the file-pointer(cursor) measured from the beginning of the file, at which the
next read or write occurs.
15 long length()
16 void write(int b)
It writes the specified byte to the file from the current cursor position.
17 void writeFloat(float v)
It converts the float argument to an int using the floatToIntBits method in class Float,
and then writes that int value to the file as a four-byte quantity, high byte first.
18 void writeDouble(double v)
It converts the double argument to a long using the doubleToLongBits method in class
Double, and then writes that long value to the file as an eight-byte quantity, high byte
first.
import java.io.*;
// Writing to file
f_ref.writeUTF("Hello, Good Morning!");
// read() method :
System.out.println("Use of read() method : " + f_ref.read());
f_ref.seek(0);
// readByte() method :
System.out.println("Use of readByte() : " + f_ref.readByte());
f_ref.writeChar('c');
f_ref.seek(0);
// readChar() :
System.out.println("Use of readChar() : " + f_ref.readChar());
f_ref.seek(0);
f_ref.writeDouble(d);
f_ref.seek(0);
// read double
System.out.println("Use of readDouble() : " + f_ref.readDouble());
f_ref.seek(0);
f_ref.writeFloat(f);
f_ref.seek(0);
// readFloat() :
System.out.println("Use of readFloat() : " + f_ref.readFloat());
f_ref.seek(0);
// Create array upto geek.length
byte[] arr = new byte[(int) f_ref.length()];
// readFully() :
f_ref.readFully(arr);
String str1 = new String(arr);
System.out.println("Use of readFully() : " + str1);
f_ref.seek(0);
1 void flush( )
2 String readLine( )
It reads a string value from the keyboard, the input is terminated on pressing enter key.
It displays the given promptingString, and reads a string fron the keyboard; input is
terminated on pressng Enter key.
4 char[ ] readPassword( )
It reads a string value from the keyboard, the string is not displayed; the input is
terminated on pressing enter key.
It displays the given promptingString, and reads a string value from the keyboard, the
string is not displayed; the input is terminated on pressing enter key.
8 Reader reader( )
9 PrintWriter writer( )
S.No. Methods with Description
Let's look at the following example program for reading a string using Console class.
Example
import java.io.*;
public class ReadingDemo {
public static void main(String[] args) {
String name;
Console con = System.console();
if(con != null) {
name = con.readLine("Please enter your name : ");
System.out.println("Hello, " + name + "!!");
}
else {
System.out.println("Console not available.");
}
}
}
Let's look at the following example program for writing to the console using Console class.
Example
import java.io.*;
public class WritingDemo {
public static void main(String[] args) {
Using serialization and deserialization, we can transfer the Object Code from one Java
Virtual machine to another.
Serialization in Java
The class whose object needs to be serialized must implement the Serializable interface.
Step 1 - Define the class whose object needs to be serialized; it must implement
Serializable interface.
Step 2 - Create a file reference with file path using FileOutputStream class.
Step 3 - Create reference to ObjectOutputStream object with file reference.
Step 4 - Use writeObject(object) method by passing the object that wants to be serialized.
Step 5 - Close the FileOutputStream and ObjectOutputStream.
Example
import java.io.*;
public class SerializationExample {
public static void main(String[] args) {
Student stud = new Student();
stud.studName = "Rama";
stud.studBranch = "IT";
try {
FileOutputStream fos = new FileOutputStream("my_data.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(stud);
oos.close();
fos.close();
System.out.println("The object has been saved to my_data file!");
}
catch(Exception e) {
System.out.println(e);
}
}
}
Deserialization in Java
Step 1 - Create a file reference with file path in which serialized object is available using
FileInputStream class.
Step 2 - Create reference to ObjectInputStream object with file reference.
Step 3 - Use readObject() method to access serialized object, and typecaste it to
destination type.
Step 4 - Close the FileInputStream and ObjectInputStream.
Example
import java.io.*;
public class DeserializationExample {
public static void main(String[] args) throws Exception{
try {
FileInputStream fis = new FileInputStream("my_data.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
fis.close();
ois.close();
Enum in Java
In java, an Enumeration is a list of named constants.
The enum concept was introduced in Java SE 5 version.
The enum in Java programming the concept of enumeration is greatly expanded with lot
more new features compared to the other languages like C, and C++.
In java, the enumeration concept was defined based on the class concept.
When we create an enum in java, it converts into a class type. This concept enables the
java enum to have constructors, methods, and instance variables.
All the constants of an enum are public, static, and final. As they are static, we can
access directly using enum name.
The main objective of enum is to define our own data types in Java, and they are said to
be enumeration data types.
Let's look at the following example program for creating a basic enum.
Example
enum WeekDay{
MONDAY, TUESDAY, WEDNESSDAY, THURSDAY, FRIDAY, SATURDAY,
SUNDAY;
}
public class EnumerationExample {
public static void main(String[] args) {
WeekDay day = WeekDay.FRIDAY;
System.out.println("Today is " + day);
System.out.println("\nAll WeekDays: ");
for(WeekDay d:WeekDay.values())
System.out.println(d);
}
}
�Every enum is converted to a class that extends the built-in class Enum.
�Every constant of an enum is defined as an object.
� As an enum represents a class, it can have methods, constructors. It also gets a few extra
methods from the Enum class, and one of them is the values() method.
enum WeekDay{
MONDAY, TUESDAY, WEDNESSDAY, THURSDAY, FRIDAY, SATURDAY,
SUNDAY("Holiday");
String msg;
WeekDay(){
System.out.println("Default constructor!");
}
WeekDay(String str){
System.out.println("Parameterized constructor!");
msg = str;
}
}
public class EnumerationExample {
public static void main(String[] args) {
WeekDay day = WeekDay.SUNDAY;
System.out.println("\nToday is " + day + " and its " + day.msg);
}
}
In the above example, the constant SUNDAY is created by calling the parameterized
constructor, other constants created by calling default constructor.
enum WeekDay{
MONDAY, TUESDAY, WEDNESSDAY, THURSDAY, FRIDAY, SATURDAY,
SUNDAY("Holiday");
String msg;
WeekDay(){
System.out.println("Default constructor!");
}
WeekDay(String str){
System.out.println("Parameterized constructor!");
msg = str;
}
void printMessage() {
System.out.println("Today is also " + msg);
}
}
public class EnumerationExample {
public static void main(String[] args) {
WeekDay day = WeekDay.SUNDAY;
System.out.println("\nToday is " + day);
day.printMessage();
}
}
�In java, enum can not extend another enum and a class.
�In java, enum can implement interfaces.
�In java, enum does not allow to create an object of it.
�In java, every enum extends a built-in class Enum by default.
In java, all the primitive data types have defined using the class concept, these classes
known as wrapper classes. In java, every primitive type has its corresponding wrapper
class.
All the wrapper classes in Java were defined in the java.lang package.
The following table shows the primitive type and its corresponding wrapper class.
1 byte Byte
2 short Short
3 int Interger
4 long Long
S.No. Primitive Type Wrapper class
5 float Float
6 double Double
7 char Character
8 boolean Boolean
The Java 1.5 version introduced a concept that converts primitive type to corresponding
wrapper type and reverses of it.
Autoboxing in Java
In java, the process of converting a primitive type value into its corresponding wrapper class
object is called autoboxing or simply boxing.
For example, converting an int value to an Integer class object.
The compiler automatically performs the autoboxing when a primitive type value has assigned
to an object of the corresponding wrapper class.
� We can also perform autoboxing manually using the method valueOf( ), which is provided
by every wrapper class.
Example - Autoboxing
import java.lang.*;
public class AutoBoxingExample {
public static void main(String[] args) {
// Auto boxing : primitive to Wrapper
int num = 100;
Integer i = num;
Integer j = Integer.valueOf(num);
System.out.println("num = " + num + ", i = " + i + ", j = " + j);
}
}
In java, the process of converting an object of a wrapper class type to a primitive type value is
called auto un-boxing or simply unboxing. For example, converting an Integer object to an int
value.
The compiler automatically performs the auto un-boxing when a wrapper class object has
assigned to a primitive type.
� We can also perform auto un-boxing manually using the method intValue( ), which is
provided by Integer wrapper class. Similarly every wrapper class has a method for auto un-
boxing.
import java.lang.*;
Generic Method
Generic Classe
In the above example code, the method displayData( ) is a generic method that allows a
different type of parameter values for every function call.
JDBC is an international standard for programming access to SQL databases. It was developed
by JavaSoft, a subsidiary of Sun Microsystems.
Relational Database Management System supports SQL. As we know that Java is platform
independent, JDBC makes it possible to write a single database application that can run on
different platforms and interact with different Database Management Systems.
Java Database Connectivity is similar to Open Database Connectivity (ODBC) which is used
for accessing and managing database, but the difference is that JDBC is designed specifically for
Java programs, whereas ODBC is not dependent upon any language.
As another layer, the Manager should communicate with various third party drivers that actually
connect to the database and return information from the query or perform action specified by the
query.
II. Three-tier Model
In this model, client connects with database server through a middle-tier server, which is used for
various purposes. Middle-tier server performs various functions.
It extracts the SQL command from the client and sends these commands to the database server.
Also, it extracts the result from the database server and submits the same to the client.
JDBC Type-1 driver is not specific to any database software because it does not interact with
database software directly. It interacts with database software by using the database software-
specific ODBC driver.
Type-1 driver is supplied only by Sun Microsystems. It has a built-in JDK software. JDK
software supplies a basic and built-in service called DriverManager which serves to manage a set
of JDBC drivers and to establish the connection with database software by using JDBC driver.
Type-1 driver class name is: sun.jdbc.odbc.JdbcOdbcDriver
Every JDBC driver must be registered with DriverManager service, as this creates JDBC
class object in DriverManager service.
Advantages of JDBC-ODBC Bridge Driver
• Serves as a single driver that can be used to interact with different data stores.
• Allows you to communicate with all the databases supported by the ODBC driver.
• Represents a vendor-independent driver and is available with JDK
Disadvantages of JDBC-ODBC Bridge Driver
• Decreases the execution speed due to more number of transactions. (Include JDBC ODBC DB
Native call)
• Depends on the ODBC driver due to which Java application indirectly becomes dependent on
ODBC drivers.
ii. Type-2(JAVA to Native API)
Type-2 driver converts JDBC calls in a client machine. It uses native code to communicate with
vendor database library.
Type-2 JDBC driver takes the support of vendor database software. In the figure, the java
application is programmed using JDBC API, making JDBC calls. These JDBC calls are then
converted into database specific native calls and the request is then dispatched to the database
specific native libraries.
Type-2 drivers are suitable to use with server-side application. It is not recommended to use
type-2 drivers with client-side application since native libraries for the client platform should be
installed on the client machines.
Studying Javax.sql.* package:
Class.forName() : Here we load the driver’s class file into memory at the runtime. No
need of using new or creation of object .The following example uses Class.forName() to
load the Oracle driver –
Class.forName(“oracle.jdbc.driver.OracleDriver”);
DriverManager.registerDriver(): DriverManager is a Java inbuilt class with a static
member register. Here we call the constructor of the driver class at compile time . The
following example uses DriverManager.registerDriver()to register the Oracle driver
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver())
Statement st = con.createStatement();
Here, con is a reference to Connection interface used in previous step .
4. Execute the query
Now comes the most important part i.e executing the query. Query here is an SQL Query . Now
we know we can have multiple types of queries. Some of them are as follows:
Query for updating / inserting table in a database.
Query for retrieving data .
The executeQuery() method of Statement interface is used to execute queries of retrieving values
from the database. This method returns the object of ResultSet that can be used to get all the
records of a table.
The executeUpdate(sql query) method ofStatement interface is used to execute queries of
updating/inserting .
Example:
int m = st.executeUpdate(sql);
if (m==1)
System.out.println("inserted successfully : "+sql);
else
System.out.println("insertion failed");
Here sql is sql query of the type String
5.Close the connections
So finally we have sent the data to the specified location and now we are at the verge of
completion of our task .
By closing connection, objects of Statement and ResultSet will be closed automatically. The
close() method of Connection interface is used to close the connection.
Example :
importjava.sql.*;
importjava.util.*;
class Main
System.out.println("enter name");
Connection con=null;
try
{
DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
con = DriverManager.getConnection(url,user,pass);
Statement st = con.createStatement();
int m = st.executeUpdate(sql);
if (m == 1)
else
System.out.println("insertion failed");
con.close();
catch(Exception ex)
{
System.err.println(ex);
}
}
}
Java Programming (R20CSE2204)
UNIT - III
When we try to open a file that does not exist may lead to an exception.
When the user enters invalid input data, it may lead to an exception.
When a network connection has lost during the program execution may lead to an
exception.
When we try to access the memory beyond the allocated range may lead to an exception.
The physical device problems may also lead to an exception.
Types of Exception
In java, exceptions have categorized into two types, and they are as follows.
Checked Exception - An exception that is checked by the compiler at the time of
compilation is called a checked exception.
Unchecked Exception - An exception that can not be caught by the compiler but occurrs
at the time of program execution is called an unchecked exception.
In java, exceptions are mainly categorized into two types, and they are as follows.
Checked Exceptions
Unchecked Exceptions
Checked Exceptions
The checked exception is an exception that is checked by the compiler during the compilation
process to confirm whether the exception is handled by the programmer or not. If it is not
handled, the compiler displays a compilation error using built-in classes.
The checked exceptions are generally caused by faults outside of the code itself like missing
resources, networking errors, and problems with threads come to mind.
The following are a few built-in classes used to handle checked exceptions in java.
IOException
FileNotFoundException
ClassNotFoundException
SQLException
DataAccessException
InstantiationException
UnknownHostException
� In the exception class hierarchy, the checked exception classes are the direct children of the
Exception class.
The checked exception is also known as a compile-time exception.
Let's look at the following example program for the checked exception method.
Example - Checked Exceptions
Unchecked Exceptions
The unchecked exception is an exception that occurs at the time of program execution. The
unchecked exceptions are not caught by the compiler at the time of compilation.
The unchecked exceptions are generally caused due to bugs such as logic errors, improper use
of resources, etc.
The following are a few built-in classes used to handle unchecked exceptions in java.
ArithmeticException
NullPointerException
NumberFormatException
ArrayIndexOutOfBoundsException
StringIndexOutOfBoundsException
� In the exception class hierarchy, the unchecked exception classes are the children of
RuntimeException class, which is a child class of Exception class.
The unchecked exception is also known as a runtime exception.
Let's look at the following example program for the unchecked exceptions.
Example - Unchecked Exceptions
In java, the built-in classes used to handle exceptions have the following class hierarchy.
Exception Models in Java
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 the termination model, when a method encounters an exception, further processing in that
method is terminated and control is transferred to the nearest catch block that can handle the
type of exception encountered.
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
The alternative of termination model is resumptive model. In resumptive model, the exception
handler is expected to do something to stable the situation, and then the faulting method is
retried. In resumptive model we hope to continue the execution after the exception is handled.
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.
In java, assume that, if we do not handle the exceptions in a program. In this case, when
an exception occurs in a particular function, then Java prints a exception message with
the help of uncaught exception handler.
The uncaught exceptions are the exceptions that are not caught by the compiler but
automatically caught and handled by the Java built-in exception handler.
Java programming language has a very strong exception handling mechanism. It allow us
to handle the exception use the keywords like try, catch, finally, throw, and throws.
When an uncaught exception occurs, the JVM calls a special private method
known dispatchUncaughtException( ), on the Thread class in which the exception
occurs and terminates the thread.
The Division by zero exception is one of the example for uncaught exceptions. Look at
the following code.
Example
When we execute the above code, it produce the following output for the value
a = 10 and b = 0.
In the above example code, we are not used try and catch blocks, but when the value of b is zero
the division by zero exception occurs and it caught by the default exception handler.
In java, the trytry and catch, both are the keywords used for exception handling.
The keyword try is used to define a block of code that will be tests the occurence of an
exception. The keyword catch is used to define a block of code that handles the exception
occured in the respective try block.
The uncaught exceptions are the exceptions that are not caught by the compiler but
automatically caught and handled by the Java built-in exception handler.
Both try and catch are used as a pair. Every try block must have one or more catch blocks. We
can not use try without atleast one catch, and catch alone can be used (catch without try is not
allowed).
The following is the syntax of try and catch blocks.
Syntax
try{
...
code to be tested
...
}
catch(ExceptionType object){
...
code for handling the exception
...
}
Consider the following example code to illustrate try and catch blocks in Java.
Example
In the above example code, when an exception occurs in the try block the execution control
transfered to the catch block and the catch block handles it.
In java, the keywords throw, throws, and finally are used in the exception handling concept.
Let's look at each of these keywords.
The following is the general syntax for using throw keyword in a try block.
Syntax
throw instance;
Here the instace must be throwable instance and it can be created dynamically using new
operator.
Let's look at the following example Java code to illustrate throw keyword.
Example
throws keyword in Java
The throws keyword specifies the exceptions that a method can throw to the default handler and
does not handle itself. That means when we need a method to throw an exception automatically,
we use throws keyword followed by method declaration
� When a method throws an exception, we must put the calling statement of method in try-
catch block.
Let's look at the following example Java code to illustrate throws keyword.
Example
import java.util.Scanner;
public class ThrowsExample {
int num1, num2, result;
Scanner input = new Scanner(System.in);
try {
new ThrowsExample().division();
}
catch(ArithmeticException ae) {
System.out.println("Problem info: " + ae.getMessage());
}
System.out.println("End of the program");
}
}
The finally keyword used to define a block that must be executed irrespective of exception
occurence.
The basic purpose of finally keyword is to cleanup resources allocated by try block, such as
closing file, closing database connection, etc.
�Only one finally block is allowed for each try block.
�Use of finally block is optional.
Let's look at the following example Java code to illustrate throws keyword.
Example
Built-in Exceptions in Java
The Java programming language has several built-in exception class that support exception
handling. Every exception class is suitable to explain certain error situations at run time.
All the built-in exception classes in Java were defined a package java.lang.
Few built-in exceptions in Java are shown in the following image.
List of checked exceptions in Java
S.
No. Exception Class with Description
1 ClassNotFoundException
It is thrown when the Java Virtual Machine (JVM) tries to load a particular class and the
specified class cannot be found in the classpath.
2 CloneNotSupportedException
Used to indicate that the clone method in class Object has been called to clone an object,
but that the object's class does not implement the Cloneable interface.
3 IllegalAccessException
It is thrown when one attempts to access a method or member that visibility qualifiers do
not allow.
4 InstantiationException
It is thrown when an application tries to create an instance of a class using the newInstance
method in class Class , but the specified class object cannot be instantiated because it is an
interface or is an abstract class.
5 InterruptedException
6 NoSuchFieldException
7 NoSuchMethodException
It is thrown when some JAR file has a different version at runtime that it had at compile
time, a NoSuchMethodException occurs during reflection when we try to access a method
that does not exist.
List of unchecked exceptions in Java
The following table shows the list of several unchecked exceptions.
S.
No. Exception Class with Description
1 ArithmeticException
2 ArrayIndexOutOfBoundsException
It handles the situations like 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 ArrayStoreException
It handles the situations like when an attempt has been made to store the wrong type of
object into an array of objects
4 AssertionError
5 ClassCastException
It handles the situation when we try to improperly cast a class from one type to another.
6 IllegalArgumentException
This exception is thrown in order to indicate that a method has been passed an illegal or
inappropriate argument.
7 IllegalMonitorStateException
This indicates that the calling thread has attempted to wait on an object's monitor, or has
attempted to notify other threads that wait on an object's monitor, without owning the
specified monitor.
8 IllegalStateException
9 IllegalThreadStateException
It is thrown by the Java runtime environment, when the programmer is trying to modify
the state of the thread when it is illegal.
10 IndexOutOfBoundsException
11 NegativeArraySizeException
12 NullPointerException
it is thrown when program attempts to use an object reference that has the null value.
13 NumberFormatException
It is thrown when we try to convert a string into a numeric value such as float or integer,
but the format of the input string is not appropriate or illegal.
14 SecurityException
It is thrown by the Java Card Virtual Machine to indicate a security violation.
15 StringIndexOutOfBounds
It is thrown by the methods of the String class, in order to indicate that an index is either
negative, or greater than the size of the string itself.
16 UnsupportedOperationException
The Java programming language allow us to create our own exception classes which are
basically subclasses built-in class Exception.
To create our own exception class simply create a class as a subclass of built-in
Exception class.
We may create constructor in the user-defined exception class and pass a string to
Exception class constructor using super(). We can use getMessage() method to access
the string.
Let's look at the following Java code that illustrates the creation of user-defined
exception.
Example
import java.util.Scanner;
class NotEligibleException extends Exception{
NotEligibleException(String msg){
super(msg); } }
class VoterList{
int age;
VoterList(int age){ this.age = age; }
void checkEligibility() {
try {
if(age < 18) {
throw new NotEligibleException("Error: Not eligible for vote due to under age.");
}
System.out.println("Congrates! You are eligible for vote.");
}
catch(NotEligibleException nee) { System.out.println(nee.getMessage()); } }
public static void main(String args[]) {
Scanner input = new Scanner(System.in); System.out.println("Enter your age in years: ");
int age = input.nextInt(); VoterList person = new VoterList(age);
person.checkEligibility();
} }
Multithreading in java
The java programming language allows us to create a program that contains one or more
parts that can run simultaneously at the same time.
This type of program is known as a multithreading program.
Each part of this program is called a thread.
Every thread defines a separate path of execution in java.
A thread is explained in different ways, and a few of them are as specified below.
A thread is a light wieght process.
A thread may also be defined as follows.
A thread is a subpart of a process that can run individually.
In java, multiple threads can run at a time, which enables the java to write multitasking
programs. The multithreading is a specialized form of multitasking. All modern operating
systems support multitasking. There are two types of multitasking, and they are as follows.
Process-based multitasking
Thread-based multitasking
It allows the computer to run two or more programs It allows the computer to run two or
concurrently more threads concurrently
In this process is the smallest unit. In this thread is the smallest unit.
Process requires seperate address space for each. Threads share same address space.
Process never gain access over idle time of CPU. Thread gain access over idle time of
CPU.
expensive.
The java programming language allows us to create a program that contains one or more
parts that can run simultaneously at the same time.
This type of program is known as a multithreading program. Each part of this program is
called a thread. Every thread defines a separate path of execution in java.
A thread is explained in different ways, and a few of them are as specified below.
In java, a thread goes through different states throughout its execution. These stages are called
thread life cycle states or phases. A thread may in any of the states like new, ready or runnable,
running, blocked or wait, and dead or terminated state. The life cycle of a thread in java is
shown in the following figure.
New
When a thread object is created using new, then the thread is said to be in the New state. This
state is also known as Born state.
Example
Runnable / Ready
When a thread calls start( ) method, then the thread is said to be in the Runnable state. This state
is also known as a Ready state.
Example
t1.start( );
Running
When a thread calls run( ) method, then the thread is said to be Running. The run( ) method of a
thread called automatically by the start( ) method.
Blocked / Waiting
A thread in the Running state may move into the blocked state due to various reasons like sleep(
) method called, wait( ) method called, suspend( ) method called, and join( ) method called, etc.
When a thread is in the blocked or waiting state, it may move to Runnable state due to reasons
like sleep time completed, waiting time completed, notify( ) or notifyAll( ) method called,
resume( ) method called, etc.
Example
Thread.sleep(1000);
wait(1000);
wait(); suspened(); notify(); notifyAll(); resume();
Dead / Terminated
A thread in the Running state may move into the dead state due to either its execution
completed or the stop( ) method called. The dead state is also known as the terminated state.
Step-1: Create a class as a child of Thread class. That means, create a class that extends
Thread class.
Step-2: Override the run( ) method with the code that is to be executed by the thread. The
run( ) method must be public while overriding.
Step-3: Create the object of the newly created class in the main( ) method.
Step-4: Call the start( ) method on the object created in the above step.
The Thread class in java is a subclass of Object class and it implements Runnable interface. The
Thread class is available inside the java.lang package. The Thread class has the following
syntax.
Thread( )
Thread( String threadName )
Thread( Runnable objectName )
Thread( Runnable objectName, String threadName )
The Thread classs contains the following methods.
Return
Method Description Value
start( ) It moves thre thread from Ready state to Running state by void
calling run( ) method.
currentThread( ) Returns the reference of the thread that currently in running void
state.
sleep( long ) moves the thread to blocked state till the specified number of void
milliseconds.
yield( ) Tells to the scheduler that the current thread is willing to yield void
its current use of a processor.
� The Thread class in java also contains methods like stop( ), destroy( ), suspend( ),
and resume( ). But they are depricated.
In a java programming language, every thread has a property called priority. Most of the
scheduling algorithms use the thread priority to schedule the execution sequence. In java, the
thread priority range from 1 to 10. Priority 1 is considered as the lowest priority, and priority 10
is considered as the highest priority. The thread with more priority allocates the processor first.
The java programming language Thread class provides two methods setPriority(int),
and getPriority( ) to handle thread priorities.
The Thread class also contains three constants that are used to set the thread priority, and they
are listed below.
setPriority( ) method
The setPriority( ) method of Thread class used to set the priority of a thread. It takes an integer
range from 1 to 10 as an argument and returns nothing (void).
The regular use of the setPriority( ) method is as follows.
Example
threadObject.setPriority(4); or
threadObject.setPriority(MAX_PRIORITY);
getPriority( ) method
The getPriority( ) method of Thread class used to access the priority of a thread. It does not
takes anyargument and returns name of the thread as String.
The regular use of the getPriority( ) method is as follows.
Example
Mutual Exclusion
Inter thread communication
In this tutorial, we discuss mutual exclusion only, and the interthread communication will be
discussed in the next tutorial.
Mutual Exclusion
Using the mutual exclusion process, we keep threads from interfering with one another while
they accessing the shared resource. In java, mutual exclusion is achieved using the following
concepts.
Synchronized method
Synchronized block
Synchronized method
When a method created using a synchronized keyword, it allows only one object to access it at a
time. When an object calls a synchronized method, it put a lock on that method so that other
objects or thread that are trying to call the same method must wait, until the lock is released.
Once the lock is released on the shared resource, one of the threads among the waiting threads
will be allocated to the shared resource.
In the above image, initially the thread-1 is accessing the synchronized method and other
threads (thread-2, thread-3, and thread-4) are waiting for the resource (synchronized method).
When thread-1 completes it task, then one of the threads that are waiting is allocated with the
synchronized method, in the above it is thread-3.
Example
class Table{
synchronized void printTable(int n) {
for(int i = 1; i <= 10; i++)
System.out.println(n + " * " + i + " = " + i*n);
}
}
synchronized(object){
...
block code
...
}
import java.util.*;
class NameList {
String name = "";
public int count = 0;
public void addName(String name, List<String> namesList){
synchronized(this){
this.name = name;
count++;
} namesList.add(name);
}
public int getCount(){
return count;
}
}
public class SynchronizedBlockExample {
public static void main (String[] args)
{
NameList namesList_1 = new NameList();
NameList namesList_2 = new NameList();
List<String> list = new ArrayList<String>();
namesList_1.addName("Rama", list);
namesList_2.addName("Seetha", list);
System.out.println("Thread1: " + namesList_1.name + ", " + namesList_1.getCount() +
"\n");
System.out.println("Thread2: " + namesList_2.name + ", " + namesList_2.getCount() +
"\n"); } }
� The complete code of a method may be written inside the synchronized block, where it works
similarly to the synchronized method.
Inter thread communication is the concept where two or more threads communicate to
solve the problem of polling.
In java, polling is the situation to check some condition repeatedly, to take appropriate
action, once the condition is true.
That means, in inter-thread communication, a thread waits until a condition becomes true
such that other threads can execute its task. T
he inter-thread communication allows the synchronized threads to communicate with
each other.
Java provides the following methods to achieve inter thread communication.
wait( )
notify( )
notifyAll( )
The following table gives detailed description about the above methods.
Method Description
void wait( ) It makes the current thread to pause its execution until other thread in the
same monitor calls notify( )
void notify( ) It wakes up the thread that called wait( ) on the same object.
void It wakes up all the threads that called wait( ) on the same object.
notifyAll()
class ItemQueue {
int item;
boolean valueSet = false;
synchronized int getItem()
{
while (!valueSet)
try { wait();} catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
System.out.println("Consummed:" + item);
valueSet = false;
try { Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("InterruptedException caught");
} notify(); return item; }
synchronized void putItem(int item) {
while (valueSet)
try { wait();
} catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
this.item = item; valueSet = true;
System.out.println("Produced: " + item);
try { Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
notify();
} }
class Producer implements Runnable{
ItemQueue itemQueue;
Producer(ItemQueue itemQueue){
this.itemQueue = itemQueue;
new Thread(this, "Producer").start();
}
public void run() {
int i = 0;
while(true) {
itemQueue.putItem(i++);
} } }
class Consumer implements Runnable{
ItemQueue itemQueue;
Consumer(ItemQueue itemQueue){
this.itemQueue = itemQueue;
new Thread(this, "Consumer").start();
}
public void run() {
while(true) { itemQueue.getItem(); }
} }
class ProducerConsumer{
public static void main(String args[]) {
ItemQueue itemQueue = new ItemQueue();
new Producer(itemQueue);
new Consumer(itemQueue);
}
}
UNIT - IV
Java collection framework is a collection of interfaces and classes used to storing and processing a group
of individual objects as a single unit.
The java collection framework holds several classes that provide a large number of methods to store and
process a group of objects.
These classes make the programmer task super easy and fast.
Java collection framework was introduced in java 1.2 version.
Before the collection framework in java (before java 1.2 version), there was a set of classes
like Array, Vector, Stack, HashTable. These classes are known as legacy classes.
The java collection framework contains List, Queue, Set, and Map as top-level interfaces.
The List, Queue, and Set stores single value as its element, whereas Map stores a pair of a key and value
as its element.
The Collection interface is the root interface for most of the interfaces and classes of collection
framework.
The Collection interface is available inside the java.util package.
It defines the methods that are commonly used by almost all the collections.
The Collection interface defines the following methods.
Operations on ArrayList
The ArrayList class allow us to perform several operations like adding, accesing, deleting, updating, looping, etc.
Let's look at each operation with examples.
Adding Items
The ArrayList class has the following methods to add items.
Accessing Items
Updating Items
The ArrayList class has the following methods to update or change items.
E set(int index, E newElement) - Replace the element at specified index with newElement in the
invoking ArrayList.
ArrayList replaceAll(UnaryOperator e) - Replaces each element of invoking ArrayList with the result
of applying the operator to that element.
E remove(int index) - Removes the element at specified index in the invoking ArrayList.
boolean remove(Object element) - Removes the first occurence of the given element from the invoking
ArrayList.
boolean removeAll(Collection c) - Removes the given collection of elements from the invoking
ArrayList.
void retainAll(Collection c) - Removes all the elements except the given collection of elements from the
invoking ArrayList.
boolean removeIf(Predicate filter) - Removes all the elements from the ArrayList that satisfies the given
predicate.
void clear( ) - Removes all the elements from the ArrayList.
Let's consider an example program to illustrate removing items from the ArrayList.
Example
import java.util.*;
public class ArrayListExample {
public static void main(String[] args) {
ArrayList<String> list_1 = new ArrayList<String>();
ArrayList list_2 = new ArrayList();
ArrayList list_3 = new ArrayList();
list_1.add("BTech");
list_1.add("Smart");
list_1.add("Class");
list_1.add("-");
list_1.add("Java");
list_1.add("Tutorial");
list_1.add("Classes");
list_1.add("on");
list_1.add("Collection");
list_1.add("framwork");
list_1.add("-");
list_1.add("ArrayList");
list_2.add("Tutorial");
list_2.add("Java");
list_3.add("BTech");
list_3.add("Smart");
list_3.add("Class");
System.out.println("\nList_1 before remove:\n" + list_1);
System.out.println("\nList_2 before remove:\n" + list_2);
System.out.println("\nList_3 before remove:\n" + list_3);
list_1.remove(3);
System.out.println("\nList after removing element from index 3:\n" + list_1);
list_1.remove("Tutorial");
System.out.println("\nList after removing \'Tutorial\' element:\n" + list_1);
list_1.removeAll(list_2);
System.out.println("\nList after removing all elements of list_2 from list_1:\n" + list_1);
list_1.removeIf(n -> n.equals("Classes"));
System.out.println("\nList after removing all elements that are equal to \'Classes\':\n" + list_1);
list_1.retainAll(list_3);
System.out.println("\nList after removing all elements from list_1 except elements of list_3:\n" + list_1);
list_1.clear();
System.out.println("\nList after removing all elements from list_1:\n" + list_1);
}
}
Other utility methods
The ArrayList class has the following methods to work with elements of it.
int size( ) - Returns the total number of elements in the invoking ArrayList.
boolean isEmpty( ) - Returns true if the list is empty otherwise returns false.
boolean contains(Object element) - Returns true if the list contains given element otherwise returns
false.
void sort(Comparator c) - Sorts all the elements of invoking list based on the given comparator.
List[ ] subList(int startIndex, int endIndex) - Returns list of elements starting from startIndex to
endIndex-1.
Object clone( ) - Returns a shallow copy of an ArrayList.
Object[ ] toArray( ) - Returns an array of Object instances that contains all the elements from invoking
ArrayList.
Spliterator spliterator( ) - Creates spliterator over the elements in a list.
void trimToSize( ) - Used to trim a ArrayList instance to the number of elements it contains.
Let's consider an example program to illustrate other utility methods of the ArrayList.
Example
Consolidated list of methods
The following table providess a consolidated view of all methods of ArrayList.
Method Description
void add(int index, E element) Inserts the given element at specified index.
boolean addAll(int index, Collection c) Inserts the given collection of elements at specified index.
ArrayList subList(int startIndex, int Returns an ArrayList that contails elements from specified startIndex
lastIndex) to lastIndex-1 from the invoking ArrayList.
int indexOf(E element) Returns the index value of given element first occurence in the
ArrayList.
int lastIndexOf(E element) Returns the index value of given element last occurence in the
ArrayList.
E set(int index, E newElement) Replace the element at specified index with newElement in the
invoking ArrayList.
ArrayList replaceAll(UnaryOperator e) Replaces each element of invoking ArrayList with the result of
applying the operator to that element.
E remove(int index) Removes the element at specified index in the invoking ArrayList.
boolean remove(Object element) Removes the first occurence of the given element from the invoking
ArrayList.
Method Description
boolean removeAll(Collection c) Removes the given collection of elements from the invoking
ArrayList.
void retainAll(Collection c) Removes all the elements except the given collection of elements
from the invoking ArrayList.
boolean removeIf(Predicate filter) Removes all the elements from the ArrayList that satisfies the given
predicate.
int size( ) Returns the total number of elements in the invoking ArrayList.
boolean isEmpty( ) Returns true if the list is empty otherwise returns false.
boolean contains(Object element) Returns true if the list contains given element otherwise returns false.
void sort(Comparator c) Sorts all the elements of invoking list based on the given comparator.
List[ ] subList(int startIndex, int Returns list of elements starting from startIndex to endIndex-1.
endIndex)
Object[ ] toArray( ) Returns an array of Object instances that contains all the elements
from invoking ArrayList.
Operations on LinkedList
The LinkedList class allow us to perform several operations like adding, accesing, deleting, updating, looping,
etc. Let's look at each operation with examples.
Adding Items
The LinkedList class has the following methods to add items.
Accessing Items
Let's consider an example program to illustrate accessing items from the LinkedList.
Example
Updating Items
The LinkedList class has the following methods to update or change items.
E set(int index, E newElement) - Replace the element at specified index with newElement in the
invoking LinkedList.
Let's consider an example program to illustrate removing items from the LinkedList.
Example
Other utility methods
The LinkedList class has the following methods to work with elements of it.
int size( ) - Returns the total number of elements in the invoking LinkedList.
boolean isEmpty( ) - Returns true if the list is empty otherwise returns false.
boolean contains(Object element) - Returns true if the list contains given element otherwise returns
false.
void sort(Comparator c) - Sorts all the elements of invoking list based on the given comparator.
List[ ] subList(int startIndex, int endIndex) - Returns list of elements starting from startIndex to
endIndex-1.
Object clone( ) - Returns a shallow copy of an LinkedList.
Object[ ] toArray( ) - Returns an array of Object instances that contains all the elements from invoking
LinkedList.
Spliterator spliterator( ) - Creates spliterator over the elements in a list.
void trimToSize( ) - Used to trim a LinkedList instance to the number of elements it contains.
Let's consider an example program to illustrate other utility methods of the LinkedList.
Example
Consolidated list of methods
Method Description
void add(int index, E element) Inserts the given element at specified index.
boolean addAll(int index, Collection c) Inserts the given collection of elements at specified index.
void addFirst(E element) Inserts the given element at beggining of the list.
void addLast(E element) Inserts the given element at end of the list.
boolean offer(E element) Inserts the given element at end of the list.
boolean offerFirst(E element) Inserts the given element at beggining of the list.
boolean offerLast(E element) Inserts the given element at end of the list.
void push(E element) Inserts the given element at beggining of the list.
E peekFirst( ) Returns the first element from the invoking LinkedList, and returns null if
list is empty.
E peekLast( ) Returns the last element from the invoking LinkedList, and returns null if
list is empty.
int indexOf(E element) Returns the index value of given element first occurence in the list.
int lastIndexOf(E element) Returns the index value of given element last occurence in the list.
E set(int index, E newElement) Replace the element at specified index with newElement in the invoking
list.
E remove(int index) Removes the element at specified index in the invoking list.
boolean remove(Object element) Removes the first occurence of the given element from the invoking list.
boolean removeAll(Collection c) Removes the given collection of elements from the invoking LinkedList.
E removeFirstOccurrence(Object Removes from the first occurrence of the given element from the invoking
element) LinkedList.
E removeLastOccurrence(Object Removes from the last occurrence of the given element from the invoking
Method Description
element) LinkedList.
E poll( ) Removes the first element from the LinkedList, and returns null if the list
is empty.
E pollFirst( ) Removes the first element from the LinkedList, and returns null if the list
is empty.
E pollLast( ) Removes the last element from the LinkedList, and returns null if the list
is empty.
int size( ) Returns the total number of elements in the invoking LinkedList.
boolean isEmpty( ) Returns true if the list is empty otherwise returns false.
boolean contains(Object element) Returns true if the list contains given element otherwise returns false.
void sort(Comparator c) Sorts all the elements of invoking list based on the given comparator.
List[ ] subList(int startIndex, int Returns list of elements starting from startIndex to endIndex-1.
endIndex)
Object[ ] toArray( ) Returns an array of Object instances that contains all the elements from
invoking LinkedList.
Method Description
void trimToSize( ) Used to trim a LinkedList instance to the number of elements it contains.
HashSet( ) - Creates an empty HashSet with the default initial capacity (16).
HashSet(Collection c) - Creates a HashSet with given collection of elements.
HashSet(int initialCapacity) - Creates an empty HashSet with the specified initial capacity.
HashSet(int initialCapacity, float loadFactor) - Creates an empty HashSet with the specified initial
capacity and loadFactor.
Operations on HashSet
The HashSet class allow us to perform several operations like adding, accesing, deleting, updating, looping, etc.
Let's look at each operation with examples.
Adding Items
The HashSet class has the following methods to add items.
Accessing Items
The HashSet class has no methods to access items, we can access whole set using its name.
Updating Items
The HashSet class has no methods to update or change items.
Removing Items
The HashSet class has the following methods to remove items.
boolean remove(Object o) - Removes the specified element from the invoking HashSet.
boolean removeAll(Collection c) - Removes all the elements of specified collection from the invoking
HashSet.
boolean removeIf(Predicate p) - Removes all of the elements of HashSet collection that satisfy the given
predicate.
boolean retainAll(Collection c) - Removes all of the elements of HashSet collection except specified
collection of elements.
void clear( ) - Removes all the elements from the HashSet.
Let's consider an example program to illustrate removing items from the HashSet.
Example
The HashSet class has the following methods to work with elements of it.
int size( ) - Returns the total number of elements in the invoking HashSet.
boolean isEmpty( ) - Returns true if the HashSet is empty otherwise returns false.
HashSet clone( ) - Returns a copy of the invoking HashSet.
boolean contains(Object element) - Returns true if the HashSet contains given element otherwise returns
false.
boolean containsAll(Collection c) - Returns true if the HashSet contains given collection of elements
otherwise returns false.
boolean equals(Object o) - Compares the specified object with invoking HashSet collection for equality.
int hashCode( ) - Returns the hash code of the invoking HashSet.
Object[ ] toArray( ) - Returns an array of Object instances that contains all the elements from invoking
HashSet.
Spliterator spliterator( ) - Creates spliterator over the elements in a HashSet.
Iterator iterator( ) - Returns an iterator over the elements in the HashSet. The iterator does not return the
elements in any particular order.
Let's consider an example program to illustrate other utility methods of the HashSet.
Example
Method Description
boolean remove(Object Removes the first occurence of the given element from the invoking HashSet.
element)
boolean removeAll(Collection Removes all the elements those are in the specified collection from the invoking
c) HashSet.
boolean removeIf(Predicate p) Removes all of the elements of the HashSet collection that satisfy the given
predicate.
boolean retainAll(Collection c) Removes all the elements except those are in the specified collection from the
invoking HashSet.
int size( ) Returns the total number of elements in the invoking HashSet.
boolean isEmpty( ) Returns true if the HashSet is empty otherwise returns false.
boolean equals( ) Compares the specified object with invoking HashSet collection for equality.
boolean contains(Object Returns true if the HashSet contains given element otherwise returns false.
element)
boolean containsAll(Collection Returns true if the HashSet contains all elements of given collection otherwise
c) returns false.
Object[ ] toArray( ) Returns an array of Object instances that contains all the elements from
Method Description
invoking HashSet.
Iterator iterator( ) Returns an iterator over the elements in the HashSet. The iterator does not
return the elements in any particular order.
TreeSet( ) - Creates an empty TreeSet in which elements will get stored in default natural sorting order.
TreeSet(Collection c) - Creates a TreeSet with given collection of elements.
TreeSet(Comparator c) - Creates an empty TreeSet with the specified sorting order.
TreeSet(SortedSet s) - This constructor is used to convert SortedSet to TreeSet.
Operations on TreeSet
The TreeSet class allow us to perform several operations like adding, accesing, deleting, updating, looping, etc.
Let's look at each operation with examples.
Adding Items
The TreeSet class has the following methods to add items.
boolean add(E element) - Inserts given element to the TreeSet if it does not exist.
boolean addAll(Collection c) - Inserts given collection of elements to the TreeSet.
E First( ) - Returns the first (smallest) element from the invoking TreeSet.
E last( ) - Returns the last (largest) element from the invoking TreeSet.
E higher(E obj) - Returns the largest element e such that e>obj. If it does not found returns null.
E lower(E obj) - Returns the largest element e such that e<obj. If it does not found returns null.
E ceiling(E obj) - Returns the smallest element e such that e>=obj. If it does not found returns null.
E floor(E obj) - Returns the largest element e such that e<=obj. If it does not found returns null.
SortedSet subSet(E fromElement, E toElement) - Returns a set of elements that lie between the given
range which includes fromElement and excludes toElement.
NavigableSet subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) -
Returns a set of elements that lie between the given range from the invoking TreeSet.
SortedSet tailSet(E fromElement) - Returns a set of elements that are greater than or equal to the
specified fromElement from the invoking TreeSet.
NavigableSet tailSet(E fromElement, boolean inclusive) - Returns a set of elements that are greater than
or equal to (if, inclusive is true) the specified element from the invoking TreeSet.
SortedSet headSet(E fromElement) - Returns a set of elements that are smaller than or equal to the
specified fromElement from the invoking TreeSet.
NavigableSet headSet(E fromElement, boolean inclusive) - Returns a set of elements that are smaller
than or equal to (if, inclusive is true) the specified element from the invoking TreeSet.
Removing Items
The TreeSet class has the following methods to remove items.
boolean remove(Object o) - Removes the specified element from the invoking TreeSet.
boolean removeAll(Collection c) - Removes all the elements those are in the specified collection from
the invoking TreeSet.
boolean removeIf(Predicate p) - Removes all of the elements of the TreeSet collection that satisfy the
given predicate.
boolean retainAll(Collection c) - Removes all the elements except those are in the specified collection
from the invoking TreeSet.
E pollFirst( ) - Removes the first (smallest) element from the invoking TreeSet, and returns the same.
E pollLast( ) - Removes the last (largest) element from the invoking TreeSet, and returns the same.
void clear( ) - Removes all the elements from the TreeSet.
Let's consider an example program to illustrate removing items from the TreeSet.
Example
Other utility methods
The TreeSet class has the following methods to work with elements of it.
int size( ) - Returns the total number of elements in the invoking TreeSet.
boolean isEmpty( ) - Returns true if the TreeSet is empty otherwise returns false.
TreeSet clone( ) - Returns a copy of the invoking TreeSet.
boolean contains(Object element) - Returns true if the TreeSet contains given element otherwise returns
false.
boolean containsAll(Collection c) - Returns true if the TreeSet contains given collection of elements
otherwise returns false.
boolean equals(Object o) - Compares the specified object with invoking TreeSet collection for equality.
int hashCode( ) - Returns the hash code of the invoking TreeSet.
Object clone( ) - Returns a shallow copy of invoking TreeSet instance.
Spliterator spliterator( ) - Creates spliterator over the elements in a TreeSet.
Iterator iterator( ) - Returns an iterator over the elements in the TreeSet. The iterator does not return the
elements in any particular order.
Let's consider an example program to illustrate other utility methods of the TreeSet.
Example
Consolidated list of methods
The following table providess a consolidated view of all methods of TreeSet.
Method Description
SortedSet subSet(E fromElement, E toElement) Returns a set of elements that lie between the given
range which includes fromElement and excludes
toElement.
NavigableSet subSet(E fromElement, boolean Returns a set of elements that lie between the given
fromInclusive, E toElement, boolean toInclusive) range from the invoking TreeSet.
SortedSet tailSet(E fromElement) Returns a set of elements that are greater than or
equal to the specified fromElement from the
Method Description
invoking TreeSet.
NavigableSet tailSet(E fromElement, boolean inclusive) Returns a set of elements that are greater than or
equal to (if, inclusive is true) the specified element
from the invoking TreeSet.
SortedSet headSet(E fromElement) Returns a set of elements that are smaller than or
equal to the specified fromElement from the
invoking TreeSet.
NavigableSet headSet(E fromElement, boolean inclusive) Returns a set of elements that are smaller than or
equal to (if, inclusive is true) the specified element
from the invoking TreeSet.
boolean remove(Object element) Removes the first occurence of the given element
from the invoking TreeSet.
boolean removeAll(Collection c) Removes all the elements those are in the specified
collection from the invoking TreeSet.
boolean retainAll(Collection c) Removes all the elements except those are in the
specified collection from the invoking TreeSet.
boolean contains(Object element) Returns true if the HashSet contains given element
otherwise returns false.
PriorityQueue( ) - Creates an empty PriorityQueue with the default initial capacity (11) that orders its
elements according to their natural ordering.
PriorityQueue(Collection c) - Creates a PriorityQueue with given collection of elements.
PriorityQueue(int initialCapacity) - Creates an empty PriorityQueue with the specified initial capacity.
PriorityQueue(int initialCapacity, Comparator comparator) - Creates an empty PriorityQueue with
the specified initial capacity that orders its elements according to the specified comparator.
PriorityQueue(PriorityQueue pq) - Creates a PriorityQueue with the elements in the specified priority
queue.
PriorityQueue(SortedSet ss) - Creates a PriorityQueue with the elements in the specified SortedSet.
Operations on PriorityQueue
The PriorityQueue class allow us to perform several operations like adding, accesing, deleting, updating, looping,
etc. Let's look at each operation with examples.
Adding Items
The PriorityQueue class has the following methods to add items.
Let's consider an example program to illustrate accessing items from the PriorityQueue.
Example
Updating Items
Removing Items
The PriorityQueue class has the following methods to remove items.
Let's consider an example program to illustrate removing items from the PriorityQueue.
Example
int size( ) - Returns the total number of elements in the invoking PriorityQueue.
boolean isEmpty( ) - Returns true if the list is empty otherwise returns false.
boolean contains(Object element) - Returns true if the list contains given element otherwise returns
false.
Object[ ] toArray( ) - Returns an array of Object instances that contains all the elements from invoking
LinkedList.
Spliterator spliterator( ) - Creates spliterator over the elements in a list.
void trimToSize( ) - Used to trim a LinkedList instance to the number of elements it contains.
Iterator iterator( ) - Returns an iterator over the elements in the PriorityQueue. The iterator does not
return the elements in any particular order.
Let's consider an example program to illustrate other utility methods of the PriorityQueue.
Example
Method Description
boolean offer(E element) Inserts the given element at end of the PriorityQueue.
boolean remove(Object element) Removes the first occurence of the given element from the invoking
PriorityQueue.
boolean removeAll(Collection c) Removes the given collection of elements from the invoking PriorityQueue.
boolean removeIf(Predicate p) Removes all of the elements of this collection that satisfy the given
predicate.
boolean retainAll(Collection c) Removes all the elements except those are in the specified collection from
the invoking PriorityQueue.
E poll( ) Removes the first element from the PriorityQueue, and returns null if the
PriorityQueue is empty.
int size( ) Returns the total number of elements in the invoking PriorityQueue.
boolean isEmpty( ) Returns true if the PriorityQueue is empty otherwise returns false.
boolean contains(Object element) Returns true if the PriorityQueue contains given element otherwise returns
false.
Object[ ] toArray( ) Returns an array of Object instances that contains all the elements from
invoking PriorityQueue.
void trimToSize( ) Used to trim a PriorityQueue instance to the number of elements it contains.
Java ArrayDeque Class
ArrayDeque( ) - Creates an empty ArrayDeque with the default initial capacity (16).
ArrayDeque(Collection c) - Creates a ArrayDeque with given collection of elements.
ArrayDeque(int initialCapacity) - Creates an empty ArrayDeque with the specified initial capacity.
Operations on ArrayDeque
The ArrayDeque class allow us to perform several operations like adding, accesing, deleting, updating, looping,
etc. Let's look at each operation with examples.
Adding Items
The ArrayDeque class has the following methods to add items.
Accessing Items
Updating Items
Removing Items
The ArrayDeque class has the following methods to remove items.
Let's consider an example program to illustrate removing items from the ArrayDeque.
Example
int size( ) - Returns the total number of elements in the invoking ArrayDeque.
boolean isEmpty( ) - Returns true if the ArrayDeque is empty otherwise returns false.
ArrayDeque clone( ) - Returns a copy of the invoking ArrayDeque.
boolean contains(Object element) - Returns true if the ArrayDeque contains given element otherwise
returns false.
boolean containsAll(Collection c) - Returns true if the ArrayDeque contains given collection of elements
otherwise returns false.
boolean equals(Object o) - Compares the specified object with invoking ArrayDeque collection for
equality.
int hashCode( ) - Returns the hash code of the invoking ArrayDeque.
Object[ ] toArray( ) - Returns an array of Object instances that contains all the elements from invoking
ArrayDeque.
Spliterator spliterator( ) - Creates spliterator over the elements in a ArrayDeque.
Iterator iterator( ) - Returns an iterator over the elements in the ArrayDeque. The iterator does not return
the elements in any particular order.
Let's consider an example program to illustrate other utility methods of the ArrayDeque.
Example
Method Description
void addFirst(E element) Inserts the given element at front of the ArrayDeque.
void addLast(E element) Inserts the given element at end of the ArrayDeque.
boolean offer(E element) Inserts the given element at end of the ArrayDeque.
boolean offerFirst(E element) Inserts the given element at front of the ArrayDeque.
boolean offerLast(E element) Inserts the given element at end of the ArrayDeque.
void push(E element) Inserts the given element at front of the ArrayDeque.
E peek( ) Returns the first element from the invoking ArrayDeque, returns null
if this queue is empty.
E peekFirst( ) Returns the first element from the invoking ArrayDeque, returns null
if this queue is empty.
E peekLast( ) Returns the last element from the invoking ArrayDeque, returns null
if this queue is empty.
boolean remove(Object element) Removes the first occurence of the given element from the invoking
ArrayDeque.
boolean removeFirstOccurrence(Object Removes the first occurrence of the specified element in this
element) ArrayDeque.
boolean removLastOccurrence(Object Removes the last occurrence of the specified element in this
element) ArrayDeque.
boolean removeIf(Predicate p) Removes all of the elements of the ArrayDeque collection that satisfy
the given predicate.
boolean retainAll(Collection c) Removes all the elements except those are in the specified collection
from the invoking ArrayDeque.
E poll( ) Removes the first element from the ArrayDeque, and returns null if
the ArrayDeque is empty.
E pollFirst( ) Removes the first element from the ArrayDeque, and returns null if
the ArrayDeque is empty.
E pollLast( ) Removes the last element from the ArrayDeque, and returns null if
the ArrayDeque is empty.
int size( ) Returns the total number of elements in the invoking ArrayDeque.
Method Description
boolean isEmpty( ) Returns true if the ArrayDeque is empty otherwise returns false.
boolean equals( ) Compares the specified object with invoking ArrayDeque collection
for equality.
boolean contains(Object element) Returns true if the ArrayDeque contains given element otherwise
returns false.
boolean containsAll(Collection c) Returns true if the ArrayDeque contains all elements of given
collection otherwise returns false.
Object[ ] toArray( ) Returns an array of Object instances that contains all the elements
from invoking ArrayDeque.
Iterator iterator( ) Returns an iterator over the elements in the ArrayDeque. The iterator
does not return the elements in any particular order.
Method Description
boolean hasNext( ) Returns true if the collection has the next element, otherwise, it returns false.
Let's consider an example program to illustrate accessing elements of a collection via the Iterator.
Example
Using for-each, we can access the elements of a collection. But for-each can only be used if we don't want
to modify the contents of a collection, and we don't want any reverse access.
Alternatively, we can use the Iterator to access or cycle through a collection of elements.
Let's consider an example program to illustrate The for-each alternative.
Example
Accessing elements using ListIterator
The ListIterator interface is used to traverse through a list in both forward and backward directions. It does not
support all types of collections. It supports only the collection which implements the List interface.
The ListIterator provides the following methods to traverse through a list of elements.
Method Description
boolean hasNext( ) Returns true if the list collection has next element, otherwise it returns false.
boolean hasPrevious( ) Returns true if the list collection has previous element, otherwise it returns false.
int nextIndex( ) Returns the index of the next element. If there is no next element, returns the size of
the list.
E previousIndex( ) Returns the index of the previous element. If there is no previous element, returns -1.
The java collection framework has an interface Map that is available inside the java.util package.
The Map interface is not a subtype of Collection interface.
�The Map stores the elements as a pair of key and value.
�The Map does not allows duplicate keys, but allows duplicate values.
� In a Map, each key can map to at most one value only.
� In a Map, the order of elements depends on specific implementations, e.g TreeMap and LinkedHashMap have
predictable order, while HashMap does not.
Interface Description
Map.Entry Describe an element in key and value pair in a map. Entry is sub interface of Map.
NavigableMap It is a child of SortedMap to handle the retrienal of entries based on closest match searches.
Class Description
HashMap It implements the Map interface, but it doesn't maintain any order.
LinkedHashMap It implements the Map interface, it also extends HashMap class. It maintains the insertion order.
TreeMap It implements the Map and SortedMap interfaces. It maintains the ascending order.
void putAll(Map map) Inserts the specified map into the invoking map.
V putIfAbsent(K key, V value) Inserts the specified value with the specified key in the map only if
that key does not exist.
Set keySet( ) Returns a Set that contains all the keys of invoking Map.
Collection values( ) Returns a collection that contains all the values of invoking Map.
Set<Map.Entry<K,V>> entrySet() Returns a Set that contains all the keys and values of invoking Map.
V get(Object key) Returns the value associated with the specified key.
V getOrDefault(Object key, V Returns the value associated with the specified key, or defaultValue
defaultValue) if the map does not contain the key.
boolean containsValue(Object value) Returns true if specified value found in the map, else return false.
boolean containsKey(Object key) Returns true if specified key found in the map, else return false.
V replace(K key, V value) Used to replace the specified value for the specified key.
boolean replace(K key, V oldValue, V Used to replaces the oldValue with the newValue for a specified key.
newValue)
void replaceAll(BiFunction function) Replaces each entry's value with the result of invoking the given
function on that entry until all entries have been processed or the
function throws an exception.
V merge(K key, V value, BiFunction If the specified key is not already associated with a value or is
Method Description
remappingFunction) associated with null, associates it with the given non-null value.
V compute(K key, BiFunction Used to compute a mapping for the specified key and its current
remappingFunction) mapped value.
V computeIfAbsent(K key, Function Used to compute its value using the given mapping function, if the
mappingFunction) specified key is not already associated with a value, and enters it into
this map unless null.
V computeIfPresent(K key, BiFunction Used to compute a new mapping given the key and its current
remappingFunction) mapped value if the value for the specified key is present and non-
null.
void forEach(BiConsumer action) It performs the given action for each entry in the map until all entries
have been processed or the action throws an exception.
boolean remove(Object key, Object Removes the specified values with the associated specified keys from
value) the map.
boolean equals(Object o) It is used to compare the specified Object with the Map.
int hashCode() Returns the hash code for invoking the Map.
boolean isEmpty() Returns true if the map is empty; otherwise returns false.
The java collection framework has an interface Map that is available inside the java.util package.
The Map interface is not a subtype of Collection interface.
The Map interface has the following three classes.
Class Description
HashMap It implements the Map interface, but it doesn't maintain any order.
LinkedHashMap It implements the Map interface, it also extends HashMap class. It maintains the insertion
order.
TreeMap It implements the Map and SortedMap interfaces. It maintains the ascending order.
Method Description
Set keySet() It returns a set that contains all the keys from the invoking Map.
Set valueSet() It returns a set that contains all the values from the invoking Map.
Set entrySet() It returns a set that contains all the entries from the invoking Map.
Method Description
int compare(Object obj1, Object obj2) It is used to compares the obj1 with o bj2 .
boolean equals(Object obj) It is used to check the equity between current object and argumented
object.
The java collection framework defines several algorithms as static methods that can be used with
collections and map objects.
All the collection algorithms in the java are defined in a class called Collections which defined in
the java.util package.
All these algorithms are highly efficient and make coding very easy. It is better to use them than trying to
re-implement them.
The collection framework has the following methods as algorithms.
Method Description
void sort(List list) Sorts the elements of the list as determined by their natural
ordering.
void sort(List list, Comparator comp) Sorts the elements of the list as determined by Comparator
comp.
void rotate(List list, int n) Rotates list by n places to the right. To rotate left, use a
negative value for n.
void shuffle(List list, Random r) Shuffles the elements in the list by using r as a source of
random numbers.
void copy(List list1, List list2) Copies the elements of list2 to list1.
List nCopies(int num, Object obj) Returns num copies of obj contained in an immutable list. num
can not be zero or negative.
void swap(List list, int idx1, int idx2) Exchanges the elements in the list at the indices specified by
idx1 and idx2.
int binarySearch(List list, Object value) Returns the position of value in the list (must be in the sorted
order), or -1 if value is not found.
Method Description
int binarySearch(List list, Object value, Returns the position of value in the list ordered according to c,
Comparator c) or -1 if value is not found.
int indexOfSubList(List list, List subList) Returns the index of the first match of subList in the list, or -1
if no match is found.
int lastIndexOfSubList(List list, List subList) Returns the index of the last match of subList in the list, or -1
if no match is found.
Object max(Collection c) Returns the largest element from the collection c as determined
by natural ordering.
Object max(Collection c, Comparator comp) Returns the largest element from the collection c as determined
by Comparator comp.
Object min(Collection c, Comparator comp) Returns the smallest element from the collection c as
determined by Comparator comp.
void fill(List list, Object obj) Assigns obj to each element of the list.
boolean replaceAll(List list, Object old, Object Replaces all occurrences of old with new in the list.
new)
ArrayList list(Enumeration enum) Returns an ArrayList that contains the elements of enum.
The java collection framework has a class Arrays that provides methods for creating dynamic array and
perform various operations like search, asList, campare, etc.
The Arrays class in java is defined in the java.util package. All the methods defined by Arrays class are
static methods.
The Arrays class in java has the following methods.
Method Description
List<T> asList(T[] arr) It returns a fixed-size list backed by the specified Arrays.
int binarySearch(T[] arr, element) It searches for the specified element in the array with the help of
Binary Search algorithm, and returns the position.
int binarySearch(T[] arr, int fromIndex, int It searches a range of the specified array for the specified object
Method Description
T[] copyOf(T[] originalArr, int newLength) It copies the specified array, truncating or padding with the default
value (if necessary) so the copy has the specified length.
T[] copyOfRange(T[] originalArr, int It copies the specified range of the specified array into a new
fromIndex, int endIndex) Arrays.
boolean equals(T[] arr1, T[] arr2) It returns true if the two specified arrays of booleans are equal to
one another, otherwise retruns false.
boolean deepEquals(T[] arr1, T[] arr2) It returns true if the two specified arrays of booleans are deeply
equal to one another, otherwise retruns false (it compares including
nested arrays).
int hashCode(T[] arr) It returns the hash code for the specified array.
int deepHashCode(T[] arr) It returns the hash code for the specified array including nested
arrays.
String toString(T[] arr) It Returns a string representation of the contents of the specified
array.
String deepToString(T[] arr) It Returns a string representation of the contents of the specified
array including nested arrays.
void fill(T[] arr, T value) It assigns the specified value to each element of the specified
array.
void fill(T[] arr, int fromIndex, int toIndex, It assigns the specified value to each element of the specified range
T value) of the specified array. The range to be filled extends from
fromIndex, inclusive, to toIndex, exclusive.
void parallelPrefix(T[] arr, BinaryOperator It Cumulates, in parallel, each element of the given array in place,
o) using the supplied function.
Method Description
void setAll(T[] arr, FunctionGenerator) It sets all elements of the specified array, using the provided
generator function to compute each element.
void parallelSetAll(T[] arr, It Sets all elements of the specified array, in parallel, using the
FunctionGenerator) provided generator function to compute each element.
void sort(T[] arr) It sorts the specified array into ascending order.
void parallelSort(T[] arr) It sorts the specified array of objects into ascending order,
according to the natural ordering of its elements.
Of<T> spliterator(T[] arr) It returns a Spliterator.Of<T> covering all of the specified array.
Stream<T> stream(T[] arr) It returns a sequential Stream with the specified array as its source.
In java, the package java.util contains a class called Dictionary which works like a Map.
The Dictionary is an abstract class used to store and manage elements in the form of a pair of key and
value.
The Dictionary stores data as a pair of key and value. In the dictionary, each key associates with a value.
We can use the key to retrieve the value back when needed.
�The Dictionary class is no longer in use, it is obsolete.
�As Dictionary is an abstract class we can not create its object. It needs a child class like Hashtable.
The Dictionary class in java has the following methods.
S.
No. Methods with Description
1 Dictionary( )
It's a constructor.
Inserts a key and its value into the dictionary. Returns null on success; returns the previous value
associated with the key if the key is already exist.
5 Enumeration keys( )
Returns an enumeration of the keys contained in the dictionary.
6 Enumeration elements( )
Returns an enumeration of the values contained in the dictionary.
7 boolean isEmpty( )
It returns true if dictionary has no elements; otherwise returns false.
8 int size( )
It returns the total number of elements in the dictionary.
In java, the package java.util contains a class called Hashtable which works like a HashMap but it is
synchronized.
The Hashtable is a concrete class of Dictionary.
It is used to store and manage elements in the form of a pair of key and value.
The Hashtable stores data as a pair of key and value. In the Hashtable, each key associates with a value.
Any non-null object can be used as a key or as a value.
We can use the key to retrieve the value back when needed.
�The Hashtable class is no longer in use, it is obsolete. The alternate class is HashMap.
�The Hashtable class is a concrete class of Dictionary.
�The Hashtable class is synchronized.
�The Hashtable does no allow null key or value.
�The Hashtable has the initial default capacity 11.
The Hashtable class in java has the following constructors.
S. No. Constructor with Description
1 Hashtable( )
2 Hashtable(int capacity)
It creates an empty hashtable with the specified initial capacity.
4 Hashtable(Map m)
It creates a hashtable containing elements of Map m.
S.
No. Methods with Description
It inserts the specified key and value into the hash table.
5 V get(Object key)
It returns the value associated with the given key.
6 Enumeration keys()
Returns an enumeration of the keys of the hashtable.
7 Set keySet()
Returns a set view of the keys of the hashtable.
S.
No. Methods with Description
8 Collection values()
It returns a collection view of the values contained in the Hashtable.
9 Enumeration elements()
Returns an enumeration of the values of the hashtable.
10 Set entrySet()
It returns a set view of the mappings contained in the hashtable.
11 int hashCode()
It returns the hash code of the hashtable.
12 Object clone()
It returns a shallow copy of the Hashtable.
13 V remove(Object key)
It returns the value associated with given key and removes the same.
21 void rehash()
S.
No. Methods with Description
It is used to increase the size of the hash table and rehashes all of its keys.
22 String toString()
It returns a string representation of the Hashtable object.
25 boolean isEmpty( )
It returns true if Hashtable has no elements; otherwise returns false.
26 int size( )
It returns the total number of elements in the Hashtable.
27 void clear()
It is used to remove all the lements of a Hashtable.
28 boolean equals(Object o)
It is used to compare the specified Object with the Hashtable.
In java, the package java.util contains a class called Properties which is a child class of Hashtable class.
It implements interfaces like Map, Cloneable, and Serializable.
Java has this built-in class Properties which allow us to save and load multiple values from a file.
This makes the class extremely useful for accessing data related to configuration.
The Properties class used to store configuration values managed as key, value pairs.
In each pair, both key and value are String values. We can use the key to retrieve the value back when
needed.
The Properties class provides methods to get data from the properties file and store data into the properties
file.
It can also be used to get the properties of a system.
�The Properties class is child class of Hashtable class.
�The Properties class implements Map, Cloneable, and Serializable interfaces.
�The Properties class used to store configuration values.
�The Properties class stores the data as key, value pairs.
� In Properties class both key and value are String data type.
�Using Properties class, we can load key, value pairs into a Properties object from a stream.
�Using Properties class, we can save the Properties object to a stream.
The Properties class in java has the following constructors.
S. No. Constructor with Description
1 Properties( )
2 Properties(Properties defaults)
It creates an empty property list with the specified defaults.
1 void load(Reader r)
8 Enumeration propertyNames())
It returns an enumeration of all the keys from the property list.
9 Set stringPropertyNames()
Returns a set view of the keys of the Properties.
It is used to print the property list out to the specified output stream.
Let's consider an example program to illustrate methods of Properties class to store a user configuration details to
a properties file.
Example
Let's consider another example program to illustrate methods of Properties class using console.
Example
In java, the package java.util contains a class called Stack which is a child class of Vector class.
It implements the standard principle Last-In-First-Out of stack data structure.
The Stack has push method for inesrtion and pop method for deletion. It also has other utility methods.
� In Stack, the elements are added to the top of the stack and removed from the top of the stack.
The Stack class in java has the following constructor.
1 Stack( )
It pushes the element onto the stack and returns the same.
2 Object pop( )
It returns the element on the top of the stack and removes the same.
4 Object peek( )
It returns the element on the top of the stack.
5 boolean empty()
It returns true if the stack is empty, otherwise returns false.
In java, the package java.util contains a class called Vector which implements the List interface.
The Vector is similar to an ArrayList. Like ArrayList Vector also maintains the insertion order.
But Vector is synchronized, due to this reason, it is rarly used in the non-thread application. It also lead to
poor performance.
�The Vector is a class in the java.util package.
�The Vector implements List interface.
�The Vector is a legacy class.
�The Vector is synchronized.
The Vector class in java has the following constructor.
1 Vector( )
2 Vector(int initialSize)
It creates an empty Vector with specified initail capacity.
4 Vector(Collection c)
It creates a vector that contains the elements of collection c.
1 boolean add(Object o)
4 boolean addAll(Collection c)
S.No. Methods with Description
It appends all of the elements in the specified Collection to the end of the Vector.
9 boolean remove(Object o)
It removes the first occurrence of the specified element in the vector.
13 boolean removeAll(Collection c)
It removes from the vector all of its elements that are contained in the specified Collection.
14 void removeAllElements()
It removes all the elements from the vector.
15 boolean retainAll(Collection c)
It removes all the elements from the vector except elements those are in the given collection.
18 Enumeration elements()
It returns the Enumeration of all the elements of the Vector.
19 Object firstElement()
It returns the first element of the Vector.
20 Object lastElement()
It returns the last element of the Vector.
25 int capacity()
It returns the current capacity of the Vector.
26 void clear()
It removes all the elements from the Vector.
27 Object clone()
It returns a clone of the Vector.
29 boolean containsAll(Collection c)
It returns true if all the elements of geven collection found in the Vector, otherwise returns false.
31 boolean equals(Object o)
It compares the specified Object with this vector for equality.
32 int hashCode()
It returns the hash code of the Vector.
33 boolean isEmpty()
It returns true if Vector has no elements, otherwise returns false.
35 int size()
It returns total number of elements in the vector.
36 Object[] toArray()
It returns an array containing all the elements of the Vector.
37 String toString()
It returns a string representation of the Vector.
38 void trimToSize()
It trims the capacity of the vector to be the vector's current size.
The StringTokenizer is a built-in class in java used to break a string into tokens.
The StringTokenizer class is available inside the java.util package.
The StringTokenizer class object internally maintains a current position within the string to be tokenized.
�A token is returned by taking a substring of the string that was used to create the StringTokenizer object.
The StringTokenizer class in java has the following constructor.
1 StringTokenizer(String str)
It creates StringTokenizer object for the specified string str with default delimeter.
1 String nextToken()
3 Object nextElement()
It returns the next token from the StringTokenizer object.
4 boolean hasMoreTokens()
It returns true if there are more tokens in the StringTokenizer object. otherwise returns false.
5 boolean hasMoreElements()
It returns true if there are more tokens in the StringTokenizer object. otherwise returns false.
6 int countTokens()
It returns total number of tokens in the StringTokenizer object.
The BitSet is a built-in class in java used to create a dynamic array of bits represented by boolean values.
The BitSet class is available inside the java.util package.
The BitSet array can increase in size as needed. This feature makes the BitSet similar to a Vector of bits.
�The bit values can be accessed by non-negative integers as an index.
�The size of the array is flexible and can grow to accommodate additional bit as needed.
�The default value of the BitSet is boolean false with a representation as 0 (off).
�BitSet uses 1 bit of memory per each boolean value.
The BitSet class in java has the following constructor.
1 BitSet( )
2 BitSet(int noOfBits)
It creates a BitSet object with number of bits that it can hold. All bits are initialized to zero.
It performs AND operation on the contents of the invoking BitSet object with those specified by bitSet.
7 int cardinality( )
It returns the number of bits set to true in the invoking BitSet.
8 void clear( )
It sets all the bits to zeros of the invoking BitSet.
11 Object clone( )
It duplicates the invoking BitSet object.
S.No. Methods with Description
15 int hashCode( )
It returns the hash code of the invoking BitSet.
17 boolean isEmpty( )
It returns true if all bits in the invoking object are zero, otherwise returns false.
17 int length( )
It returns the total number of bits in the invoking BitSet.
24 int size( )
S.No. Methods with Description
25 String toString( )
It returns the string equivalent of the invoking BitSet object.
The Date is a built-in class in java used to work with date and time in java.
The Date class is available inside the java.util package.
The Date class represents the date and time with millisecond precision.
The Date class implements Serializable, Cloneable and Comparable interface.
�Most of the constructors and methods of Date class has been deprecated after Calendar class introduced.
The Date class in java has the following constructor.
S.
No. Constructor with Description
1 Date( )
2 Date(long milliseconds)
It creates a date object for the given milliseconds since January 1, 1970, 00:00:00 GMT.
4 Date(int year, int month, int date, int hrs, int min) - Depricated
It creates a date object with the specified year, month, date, hours, and minuts.
5 Date(int year, int month, int date, int hrs, int min, int sec) - Depricated
It creates a date object with the specified year, month, date, hours, minuts and seconds.
5 Date(String s) - Depricated
It creates a Date object and initializes it so that it represents the date and time indicated by the string s,
which is interpreted as if by the parse(java.lang.String) method.
1 long getTime()
6 Object clone( )
It duplicates the invoking Date object.
9 int hashCode()
It returns the hash code value of the invoking date object.
10 Instant toInstant()
It converts current date into Instant object.
11 String toString()
It converts this date into Instant object.
The Calendar is a built-in abstract class in java used to convert date between a specific instant in time and
a set of calendar fields such as MONTH, YEAR, HOUR, etc.
The Calendar class is available inside the java.util package.
The Calendar class implements Serializable, Cloneable and Comparable interface.
�As the Calendar class is an abstract class, we can not create an object using it.
�We will use the static method Calendar.getInstance() to instantiate and implement a sub-class.
The Calendar class in java has the following methods.
1 Calendar getInstance()
2 Date getTime()
It returns a Date object representing the invoking Calendar's time value.
3 TimeZone getTimeZone()
It returns the time zone object associated with the invoking calendar.
4 String getCalendarType()
It returns an instance of Date object from Instant date.
6 int getFirstDayOfWeek()
It returns the day of the week in integer form.
7 int getWeeksInWeekYear()
It retruns the total weeks in week year.
8 int getWeekYear()
It returns the week year represented by current Calendar.
13 Object clone()
It retruns the copy of the current object.
15 void complete()
It sets any unset fields in the calendar fields.
16 void computeFields()
It converts the current millisecond time value time to calendar field values in fields[].
17 void computeTime()
It converts the current calendar field values in fields[] to the millisecond time value time.
21 Set getAvailableCalendarTypes()
It returns a string set of all available calendar type supported by Java Runtime Environment.
22 Locale[] getAvailableLocales()
It returns an array of all locales available in java runtime environment.
28 int getMinimalDaysInFirstWeek()
It returns required minimum days in integer form.
30 long getTimeInMillis()
It returns the current time in millisecond.
31 int hashCode()
It returns the hash code of the invoking object.
33 boolean isLenient()
It returns true if the interpretation mode of this calendar is lenient; false otherwise.
35 boolean isWeekDateSupported()
It returns true if the calendar supports week date. The default value is false.
44 Instant toInstant()
It converts the current object to an instant.
45 String toString()
It returns a string representation of the current object.
The Random is a built-in class in java used to generate a stream of pseudo-random numbers in java
programming.
The Random class is available inside the java.util package.
The Random class implements Serializable, Cloneable and Comparable interface.
�The Random class is a part of java.util package.
� The Random class provides several methods to generate random numbers of type integer, double, long, float
etc.
�The Random class is thread-safe.
� Random number generation algorithm works on the seed value. If not provided, seed value is created from
system nano time.
The Random class in java has the following constructors.
1 Random()
2 Random(long seedValue)
It creates a new random number generator using a single long seedValue.
2 Boolean nextBoolean()
It generates the next uniformly distributed pseudo-random boolean value.
3 double nextDouble()
It generates the next pseudo-random double number between 0.0 and 1.0.
5 float nextFloat()
It generates the next pseudo-random float number between 0.0 and 1.0..
S.No. Methods with Description
6 int nextInt()
It generates the next pseudo-random int number.
7 int nextInt(int n)
It generates the next pseudo-random integer value between zero and n.
8 long nextLong()
It generates the next pseudo-random, uniformly distributed long value.
9 double nextGaussian()
It generates the next pseudo-random Gaussian distributed double number with mean 0.0 and standard
deviation 1.0.
11 DoubleStream doubles()
It returns a stream of pseudo-random double values, each conforming between 0.0 and 1.0.
15 IntStream ints()
It returns a stream of pseudo-random integer values.
19 LongStream longs()
It returns a stream of pseudo-random long values.
The Formatter is a built-in class in java used for layout justification and alignment, common formats for
numeric, string, and date/time data, and locale-specific output in java programming.
The Formatter class is defined as final class inside the java.util package.
The Formatter class implements Cloneable and Flushable interface.
The Formatter class in java has the following constructors.
1 Formatter()
2 Formatter(Appendable a)
It creates a new formatter with the specified destination.
3 Formatter(Appendable a, Locale l)
It creates a new formatter with the specified destination and locale.
4 Formatter(File file)
It creates a new formatter with the specified file.
7 Formatter(Locale l)
It creates a new formatter with the specified locale.
8 Formatter(OutputStream os)
It creates a new formatter with the specified output stream.
11 Formatter(PrintStream ps)
It creates a new formatter with the specified print stream.
S.No. Constructor with Description
12 Formatter(String fileName)
It creates a new formatter with the specified file name.
It writes a formatted string to the invoking object's destination using the specified locale, format string,
and arguments.
3 void flush()
It flushes the invoking formatter.
4 Appendable out()
It returns the destination for the output.
5 Locale locale()
It returns the locale set by the construction of the invoking formatter.
6 String toString()
It converts the invoking object to string.
7 IOException ioException()
It returns the IOException last thrown by the invoking formatter's Appendable.
8 void close()
It closes the invoking formatter.
The Scanner is a built-in class in java used for read the input from the user in java programming. The
Scanner class is defined inside the java.util package.
The Scanner class implements Iterator interface.
The Scanner class provides the easiest way to read input in a Java program.
�The Scanner object breaks its input into tokens using a delimiter pattern, the default delimiter is whitespace.
The Scanner class in java has the following constructors.
1 Scanner(InputStream source)
It creates a new Scanner that produces values read from the specified input stream.
3 Scanner(File source)
It creates a new Scanner that produces values scanned from the specified file.
5 Scanner(String source)
It creates a new Scanner that produces values scanned from the specified string.
6 Scanner(Readable source)
It creates a new Scanner that produces values scanned from the specified source.
7 Scanner(ReadableByteChannel source)
It creates a new Scanner that produces values scanned from the specified channel.
1 String next()
4 boolean nextBoolean()
It reads a boolean value from the user.
5 byte nextByte()
It reads a byte value from the user.
6 double nextDouble()
It reads a double value from the user.
7 float nextFloat()
It reads a floating-point value from the user.
8 int nextInt()
It reads an integer value from the user.
9 long nextLong()
It reads a long value from the user.
10 short nextShort()
It reads a short value from the user.
11 String nextLine()
It reads a string value from the user.
12 boolean hasNext()
It returns true if the invoking scanner has another token in its input.
13 void remove()
It is used when remove operation is not supported by this implementation of Iterator.
14 void close()
It closes the invoking scanner.
UNIT - V
GUI Programming with Swing – Introduction, limitations of AWT, MVC architecture, components,
containers. Understanding Layout Managers, Flow Layout, Border Layout, Grid Layout, Card Layout, Grid Bag
Layout.
Event Handling- The Delegation event model- Events, Event sources, Event Listeners, Event classes,
Handling mouse and keyboard events, Adapter classes, Inner classes, Anonymous Inner classes.
A Simple Swing Application, Applets – Applets and HTML, Security Issues, Applets and Applications, passing
parameters to applets. Creating a Swing Applet, Painting in Swing, A Paint example, Exploring Swing Controls-
JLabel and Image Icon, JText Field, The Swing Buttons- JButton, JToggle Button, JCheck Box, JRadio Button,
JTabbed Pane, JScroll Pane, JList, JCombo Box, Swing Menus, Dialogs.
Topics Covered:
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.
Applications of Java Applet
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.
ItemListener
3
This interface is used for receiving the item events.
4 KeyListener
This interface is used for receiving the key events.
MouseListener
5
This interface is used for receiving the mouse events.
TextListener
6
This interface is used for receiving the text events.
WindowListener
7
This interface is used for receiving the window events.
AdjustmentListener
8
This interface is used for receiving the adjusmtent events.
ContainerListener
9
This interface is used for receiving the container events.
MouseMotionListener
10
This interface is used for receiving the mouse motion events.
FocusListener
11
This interface is used for receiving the focus events.
Advantages of Applets
1. It takes very less response time as it works on the client side.
2. It can be run on any browser which has JVM running in it.
Applet class
Applet class provides all necessary support for applet execution, such as initializing and destroying of applet.
It also provide methods that load and display images and methods that load and play audio clips
import java.applet.Applet;
import java.awt.Graphics;
public class FirstApplet extends Applet{
Next:
Write the following program and save the file say with MyFirstApplet.html
<html>
<body>
<applet code="FirstApplet.class" width="500" height="300">
</applet>
</body>
</html>
package com.myPack;
jbBvritn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent le)
{
jl.setText("BVRITH was pressed.");
}
});
//Add action listener for Beta. jbBvrith.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent le) {jl.setText("BVRITN was pressed.");
}
});
Inside displayGUI( ), the two buttons and label are created, and the action listeners are added to the buttons.
Finally, the components are added to the content pane. Although this example is quite simple, this same
general approach must be used when building any Swing GUI that will be used by an applet.
GUI ( Graphical User Interface) , Here the user interact with any application by clicking on some images
or graphics.
Example: if the user wants to print a file, he can click on the printer images and the rest of the
things will be taken care of by the application.
Like magnifying glass symbol for searching, a briefcase symbol for a directory etc.
Hence, the environment where the user can interact with the application through graphics or
images is called GUI (Graphical User Interface)
TextField,
Label,
TextArea,
RadioButton,
CheckBox,
Choice,
List
Button
2
Components:
A component represents an object which is displayed pictorially on the screen. For example,
we create an object of Button class as:
Now, b is object of Button class, If we display this b on the screen, it displays a push button.
Therefore, the object b, on going to the screen is becoming a component called ‘Push
Button’.
In the same way any component is a graphical representation of an object. Push Buttons,
radio buttons, check boxes etc are all components
3
Container
The Container is a component in AWT that can contain another components like Buttons,
Textfields, labels etc. The classes that extend Container class are known as container such as
Frame, Dialog and Panel.
Window
The window is the container that have no borders and menu bars. You must use frame, dialog
or another window for creating a window.
Panel
The Panel is the container that doesn't contain title bar and menu bars. It can have other
components like button, textfield etc.
Frame
The Frame is the container that contain title bar and can have menu bars. It can have other
components like button, textfield etc.
Method Description
public void add(Component c) inserts a component on this component.
public void setSize (int width, int height) sets the size (width and height) of the
component.
public void setLayout(LayoutManager m) defines the layout manager for the component.
public void setVisible(boolean status) changes the visibility of the component, by
default false.
To create simple awt example, you need a frame. There are two ways to create a frame in
AWT.
import java.awt.Frame;
Output:
Let's see a simple example of AWT where we are creating instance of Frame class. Here, we
are showing Button component on the Frame.
import java.awt.*;
class First2{
First2(){
Frame f=new Frame();
Button b=new Button("BVRIT HYDERABAD");
b.setBounds(30,50,80,30);
f.add(b);
5
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[]){
First2 f=new First2();
}
}
After executing this program we observe that the frame can be minimized, maximized and
resized but cannot be closed. Even if we click on the close button of the frame, it will not
perform any closing action.
Closing a frame means attaching action to the component. To attach action to the frame
we need “EVENT DELIGATION MODEL”.
Clicking
Double Clicking
Typing data inside the component
Mouse over etc
When an event is generated on the component, the component will not know about it because
it cannot listen to the event. To let the component understand that an event occurred on it, we
should add some listeners to the components.
A listener will have some abstract methods which need to be implemented by the
programmer.
6
When an even is generated by the user on the component, the event is not handled by the
component; on the other hand, the component sends (delegate) the event to the listener
attached to it. The listener will not handle the event. It hands over (Delegates) the event to an
appropriate method. Finally, the method is executed and the event is handled. This is called
‘Event Delegation Model’
We know frame is also a component. We want to close the frame by clicking on its close
button. Let us follow these steps to see how to use event delegation model to do this.
We should attach a listener to the frame component. Remember, all listeners are available in
java.awt.event package.
The most suitable listener to the frame is ‘window listener’ it can be attached using add
WindowListener() method as;
f.addWindowListener(WindowListener obj);
Note that, the addWindowListerner() method has a parameter that is expecting object of
WindowListener interface. Since it is not possible to create an object to an interface, we
should create an object to the implemented class of the interface and pass it to the method.
Implement all the methods of the WindowListener interface. The following methods are
found in WindowListener interface.
So, when the frame is closed, the body of this method is executed and the application gets
closed. In this way we can handle the frame closing event.
Write a program to create a frame and then close it on clicking the close button
import java.awt.*;
import java.awt.event.*;
Output:
In the above example, we had to mention all the methods of WindowListener interface, just
for the sake of one method.
import java.awt.*;
import java.awt.event.*;
Output:
9
An adapter class is an implementation class of a listener interface which contains all methods
implemented with empty body. For example, WindowAdapter is an adapter class of
WindowListener interface.
In the above program, the code of MyClass can be copied directly into addWIndowListener()
method as
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
In this code, we cannot find the name of MyClass anywhere in the code. It means the name of
MyClass is hidden in MyFrame class and hence MyClass is an inner class in MyFrame class
whose name is not mentioned. Such inner class is called ‘anonymous inner class’;
Anonymous inner class is an inner class whose name is not mentioned, and for which only
one object is created.
import java.awt.*;
import java.awt.event.*;
Output:
import java.awt.*;
import java.awt.event.*;
m.setSize(400,250); m.setTitle("This is my
Text");m.setVisible(true);
}
}
Output:
11
Let's see a simple example of AWT where we are inheriting Frame class. Here, we are
showing Button component on the Frame.
import java.awt.Button;
import java.awt.Frame;
Output
The setBounds(int xaxis, int yaxis, int width, int height) method is used in the above
example that sets the position of the awt button.
Changing the state of an object is known as an event. For example, click on button,
dragging mouse etc.
The java.awt.event package provides many event classes and Listener interfaces for event
handling.
12
ActionEvent ActionListener
MouseWheelEvent MouseWheelListener
KeyEvent KeyListener
ItemEvent ItemListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener
FocusEvent FocusListener
Registration Methods
For registering the component with the Listener, many classes provide the registration
methods. For example:
o Button
o public void addActionListener(ActionListener a){}
o MenuItem
o public void addActionListener(ActionListener a){}
13
o TextField
o public void addActionListener(ActionListener a){}
o public void addTextListener(TextListener a){}
o TextArea
o public void addTextListener(TextListener a){}
o Checkbox
o public void addItemListener(ItemListener a){}
o Choice
o public void addItemListener(ItemListener a){}
o List
o public void addActionListener(ActionListener a){}
o public void addItemListener(ItemListener a){}
We can put the event handling code into one of the following places:
1. Within class
2. Other class
3. Anonymous class
import java.awt.*;
import java.awt.event.*;
class AEvent extends Frame implements ActionListener{
TextField tf;
AEvent(){
//create components
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);
//register listener
b.addActionListener(this);//passing current instance
Output:
public void setBounds(int xaxis, int yaxis, int width, int height); have been used in the
above example that sets the position of the component it may be button, textfield etc.
15
The button class is used to create a labeled button that has platform independent
implementation. The application result in some action when the button is pushed.
import java.awt.*;
import java.awt.event.*;
Output:
16
The object of Label class is a component for placing text in a container. It is used to display a
single line of read only text. The text can be changed by an application but a user cannot edit
it directly.
import java.awt.*;
import java.awt.event.*;
class LabelExample{
public static void main(String args[]){
Frame f= new Frame("Label Example");
Label l1,l2;
l1=new Label("User Name");
l1.setBounds(50,100, 100,30);
l2=new Label("Password");
l2.setBounds(50,150, 100,30);
f.add(l1); f.add(l2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
f.addWindowListener(new
WindowAdapter());
{ public void windowClosing(WindowEvent
e){System.exit(0);
}
} } }
Output:
17
Java AWT TextField
The object of a TextField class is a text component that allows the editing of a single line
text. It inherits TextComponent class.
import java.awt.*;
import java.awt.event.*;
class TextFieldExample{
public static void main(String args[]){
Frame f= new Frame("TextField Example");
TextField t1,t2;
t1=new TextField("Anil Kumar");
t1.setBounds(50,100, 200,30);
t2=new TextField("Hyderabad");
t2.setBounds(50,150, 200,30);
f.add(t1); f.add(t2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
}
Output:
18
The object of a TextArea class is a multi line region that displays text. It allows the editing of
multiple line text. It inherits TextComponent class.
import java.awt.*;
import java.awt.event.*;
Output:
19
Java AWT Checkbox
The Checkbox class is used to create a checkbox. It is used to turn an option on (true) or off
(false). Clicking on a Checkbox changes its state from "on" to "off" or from "off" to "on".
import java.awt.*;
import java.awt.event.*;
public class CheckboxExample
{
CheckboxExample(){
Frame f= new Frame("Checkbox Example");
Checkbox checkbox1 = new Checkbox("C++");
checkbox1.setBounds(100,100, 50,50);
Checkbox checkbox2 = new Checkbox("Java", true);
checkbox2.setBounds(100,150, 50,50);
Checkbox checkbox3 = new Checkbox("Python");
checkbox3.setBounds(100,200, 70,50);
Checkbox checkbox4 = new Checkbox("Haskell", true);
checkbox4.setBounds(100,250,70,50);
f.add(checkbox1);
f.add(checkbox2);
f.add(checkbox3);
f.add(checkbox4);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
public static void main(String args[])
{ new CheckboxExample();
} }
20
Output:
The object of CheckboxGroup class is used to group together a set of Checkbox. At a time
only one check box button is allowed to be in "on" state and remaining check box button in
"off" state. It inherits the object class.
Note: CheckboxGroup enables you to create radio buttons in AWT. There is no special
control for creating radio buttons in AWT.
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
public static void main(String args[])
{
new CheckboxGroupExample();
}
}
Output:
The object of Choice class is used to show popup menu of choices. Choice selected by user is
shown on the top of a menu. It inherits Component class.
import java.awt.*;
import java.awt.event.*;
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
public static void main(String args[])
{
new ChoiceExample();
}
}
Output:
23
The object of List class represents a list of text items. By the help of list, user can choose
either one item or multiple items. It inherits Component class.
import java.awt.*;
import java.awt.event.*;
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
public static void main(String args[])
{
new ListExample();
}
}
Output:
24
The Canvas control represents a blank rectangular area where the application can draw or trap
input events from the user. It inherits the Component class.
import java.awt.*;
import java.awt.event.*;
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
public static void main(String args[])
{
new CanvasExample();
}
}
Output:
25
Java AWT Scrollbar
The object of Scrollbar class is used to add horizontal and vertical scrollbar. Scrollbar is
a GUI component allows us to see invisible number of rows and columns.
import java.awt.*;
import java.awt.event.*;
class ScrollbarExample{
ScrollbarExample(){
Frame f= new Frame("Scrollbar Example");
Scrollbar s=new Scrollbar();
s.setBounds(100,100, 50,100);
f.add(s);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
public static void main(String args[])
{
new ScrollbarExample();
}
}
Output:
26
The object of MenuItem class adds a simple labeled menu item on menu. The items used in a
menu must belong to the MenuItem or any of its subclass.
The object of Menu class is a pull down menu component which is displayed on the menu
bar. It inherits the MenuItem class.
import java.awt.*;
import java.awt.event.*;
class MenuExample
{
MenuExample(){
Frame f= new Frame("Menu and MenuItem Example");
MenuBar mb=new MenuBar();
Menu menu=new Menu("File");
Menu submenu=new Menu("Save As");
MenuItem i1=new MenuItem("New");
MenuItem i2=new MenuItem("Open");
MenuItem i3=new MenuItem("Save");
MenuItem i4=new MenuItem("Text File");
MenuItem i5=new MenuItem("Word Document");
menu.add(i1);
menu.add(i2);
menu.add(i3);
submenu.add(i4);
submenu.add(i5);
menu.add(submenu);
mb.add(menu);
f.setMenuBar(mb);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
public static void main(String args[])
{
new MenuExample();
}
}
27
Java AWT PopupMenu
import java.awt.*;
import java.awt.event.*;
class PopupMenuExample
{
PopupMenuExample(){
final Frame f= new Frame("PopupMenu Example");
final PopupMenu popupmenu = new PopupMenu("Edit");
MenuItem cut = new MenuItem("Cut");
cut.setActionCommand("Cut");
MenuItem copy = new MenuItem("Copy");
copy.setActionCommand("Copy");
MenuItem paste = new MenuItem("Paste");
paste.setActionCommand("Paste");
popupmenu.add(cut);
popupmenu.add(copy);
popupmenu.add(paste);
f.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
popupmenu.show(f , e.getX(), e.getY());
}
});
f.add(popupmenu);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
public static void main(String args[])
{
new PopupMenuExample();
}
}
28
The Panel is a simplest container class. It provides space in which an application can attach
any other component. It inherits the Container class.
b2.setBackground(Color.green);
panel.add(b1); panel.add(b2);
f.add(panel);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
public static void main(String args[])
{
new PanelExample();
}
}
Output:
29
Java AWT Dialog
The Dialog control represents a top level window with a border and a title used to take some
form of input from the user. It inherits the Window class.
Frame vs Dialog
Frame and Dialog both inherits Window class. Frame has maximize and minimize buttons
but Dialog doesn't have.
Output:
Handling Keyboard Events
A user interacts with the application by pressing either keys on the keyboard or by using
mouse. A programmer should know which key the user has pressed on the keyboard or
whether the mouse is moved, pressed, or released. These are also called „events‟. Knowing
these events will enable the programmer to write his code according to the key pressed or
mouse event.
2. Public void keyTyped(keyEvent ke) : This method is called when a key is typed on
the keyboard. This is same as keyPressed() method but this method is called when
general keys like A to Z or 1 to 9 etc are typed. It cannot work with special keys.
3. Public void keyReleased(KeyEvent ke): this method is called when a key is release.
KeyEvent class has the following methods to know which key is typed by the user.
1. Char getKeyChar(): this method returns the key name (or character) related to the key
pressed or released.
2. Int getKeyCode(): this method returns an integer number which is the value of the
key presed by the user.
The follwing are the key codes for the keys on the keyboard. They are defined as
constants in KeyEvent class. Remember VK represents Virtual Key.
To represent keys from a to z : VK_A to VK_Z.
To represent keys from 1 to 9: VK_0 to VK_9.
To represent keys from F1 to F12: VK_F1 to VK_F12.
To represent home, end : VK_HOME, VK_END.
To represent PageUp, PageDown: VK_PAGE_UP, VK_PAGE_DOWN
To represent Insert, Delete: VK_INSERT, VK_DELETE
To represent caps lock: VK_CAPS_LOCK
To represent alter key: VK_ALT
To represent Control Key: VK_CONTROL
To represent shift: VK_SHIFT
To represent tab key: VK_TAB
To represent arrow keys: VK_LEFT, VK_RIGHT, VK_UP, VK_DOWN
To represent Escape key: VK_ESCAPE
Static String getKeyText(int keyCode); this method returns a string describing the
keyCode such as HOME, F1 or A.
Program: to trap a key which is pressed on the keyboard and display its name in the
text area.
package com.myPack;
Output:
Handling Mouse Events
The user may click, release, drag, or move a mouse while interacting with athe
application. If the programmer knows what the user has done, he can write the code
according to the mouse events. To trap the mouse events, MouseListener and
MouseMotionListener interfaces of java.awt.event package are use.
Program to create a text area and display the mouse event when the button on the
mouse is clicke, when mouse is moved, etc. is done by user.
package com.myPack;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class MouseEvents extends JFrame implements MouseListener, MouseMotionListener
{
String str =" ";
JTextArea ta;
Container c;
int x, y;
MouseEvents()
{
c=getContentPane();
c.setLayout(new FlowLayout());
ta.addMouseListener(this);
ta.addMouseMotionListener(this);
}
Output:
3
5
Layout Managers
We Create several components like push buttons, checkboxes, radio buttons etc. in GUI.
After creating these components, they should be placed in the fram (in AWT) or container (in
Swing). While arranging them in the frame or container, they can be arranged in a perticular
manner by using layout mangers. We have LayoutManger interface in java.awt package
which is implemented in various classes which provides various layouts to arrange the
components.
The following classes represents the layout managers in java
1. FlowLayout
2. BorderLayout
3. CardLayout
4. GridLayout
5. GridBaglayout
6. BoxLayout
To set a perticular layout, we should first create an object to the layout class and pass the
object to setLayout() method. For example to set FlowLayout to the container that holds the
components, we can write:
FlowLayout
Program:
import java.awt.*;
import javax.swing.*;
class FlowLayoutDemo extends JFrame
{
FlowLayoutDemo()
{
Container c = getContentPane();
FlowLayout obj = new FlowLayout(FlowLayout.RIGHT, 10,10);
c.setLayout(obj);
JButton b1,b2,b3,b4;
b1 = new JButton("Button1");
b2 = new JButton("Button2");
b3 = new JButton("Button3");
b4 = new JButton("Button4");
c.add(b1);
c.add(b2);
c.add(b3);
c.add(b4);
}
public static void main (String args[])
{
FlowLayoutDemo demo = new FlowLayoutDemo();
demo.setSize(500,300);
demo.setTitle("Flow Layout");
demo.setVisible(true);
demo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
3
6
Output:
Border Layout
import java.awt.*;
import javax.swing.*;
class BorderLayoutDemo extends JFrame
{
BorderLayoutDemo()
{
Container c = getContentPane();
BorderLayout obj = new BorderLayout(10,10);
c.setLayout(obj);
JButton b1,b2,b3,b4;
b1 = new JButton("Button1");
b2 = new JButton("Button2");
b3 = new JButton("Button3");
b4 = new JButton("Button4");
c.add("North" , b1);
c.add("East" , b2);
c.add("South" , b3);
c.add("Center" , b4);
c.add(b1, BorderLayout.NORTH);
c.add(b2, BorderLayout.EAST);
c.add(b3, BorderLayout.SOUTH);
c.add(b4,BorderLayout.CENTER);
}
public static void main (String args[])
{
BorderLayoutDemo demo = new BorderLayoutDemo();
demo.setSize(500,300);
demo.setTitle("Flow Layout");
demo.setVisible(true);
demo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
3
7
output
Card Layout
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
CardLayoutDemo()
{
c = getContentPane();
card = new CardLayout(50,10);
c.setLayout(card);
b1 = new JButton("Button1");
b2 = new JButton("Button2");
b3 = new JButton("Button3");
b4 = new JButton("Button4");
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
}
3
8
public void actionPerformed(ActionEvent ae)
{
card.next(c);
//card.show(c,"Third Card")
}
4
3
9
Grid Layout
import java.awt.*;
import javax.swing.*;
class GridLayoutDemo extends JFrame
{
GridLayoutDemo()
{
Container c = getContentPane();
GridLayout grid = new GridLayout(2,3,50,50);
c.setLayout(grid);
//JButton b1,b2,b3,b4, b5, b6;
JButton b1 = new JButton("Button1");
JButton b2 = new JButton("Button2");
JButton b3 = new JButton("Button3");
JButton b4 = new JButton("Button4");
JButton b5 = new JButton("Button5");
JButton b6 = new JButton("Button6");
c.add(b1);
c.add(b2);
c.add(b3);
c.add(b4);
c.add(b5);
c.add(b6);
}
public static void main (String args[])
{
GridLayoutDemo demo = new GridLayoutDemo();
demo.setSize(500,300);
demo.setTitle("Grid Layout");
demo.setVisible(true);
demo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Output
5
4
0
GridBag Layout
import java.awt.*;
import javax.swing.*;
class GridBagLayoutDemo extends JFrame
{
GridBagLayout gbag;
GridBagConstraints cons;
GridBagLayoutDemo()
{
Container c = getContentPane();
gbag = new GridBagLayout();
c.setLayout(gbag);
cons.fill = GridBagConstraints.HORIZONTAL;
cons.gridx =0;
cons.gridy =0;
cons.weightx = 0.7;
cons.weighty = 0.7;
gbag.setConstraints(b1,cons);
c.add(b1);
cons.gridx =1;
cons.gridy =0;
gbag.setConstraints(b2,cons);
c.add(b2);
cons.gridx =2;
cons.gridy =0;
gbag.setConstraints(b3,cons);
c.add(b3);
cons.gridx =0;
cons.gridy =1;
cons.ipady = 100;
cons.gridwidth = 3;
6
4
1
gbag.setConstraints(b4,cons);
c.add(b4);
cons.gridx = 1;
cons.gridy = 2;
cons.ipady = 0;
cons.weighty = 0.8;
cons.anchor = GridBagConstraints.PAGE_END;
cons.insets = new Insets (0,0, 50,0);
cons.gridwidth =2;
gbag.setConstraints(b5,cons);
c.add(b5);
}
public static void main (String args[])
{
GridBagLayoutDemo demo = new GridBagLayoutDemo();
demo.setSize(500,300);
demo.setTitle("Grid Layout");
demo.setVisible(true);
demo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Output:
7
4
2
BoxLayout
import java.awt.*;
import javax.swing.*;
add(b1);
add(b2);
add(b3);
}
}
8
4
3
{
BoxLayout box2 = new BoxLayout(this, BoxLayout.X_AXIS);
setLayout(box2);
add(b1);
add(b2);
add(b3);
}
}
Output:
9
Swing Controls
Jframe
import javax.swing.JFrame;
Output:
Jlabel
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
lb1.setVerticalAlignment(JLabel.TOP);
lb1.setToolTipText("Enter UserName");
getContentPane().add(lb1);
getContentPane().add(lb2);
getContentPane().add(lb3);
}
Output:
JtextField
import javax.swing.*;
class TextFieldExample
{
public static void main(String args[])
{
JFrame f= new JFrame("TextField Demo");
JTextField t1,t2;
t1=new JTextField("Welcome to BVRIT - IT.");
t1.setBounds(50,100, 200,30);
t2=new JTextField("Swing Text Field");
t2.setBounds(50,150, 200,30);
f.add(t1); f.add(t2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Output:
Jbutton
import javax.swing.*;
import java.awt.event.*;
f.setSize(500,300);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
JToggleButton
import java.awt.FlowLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JFrame;
import javax.swing.JToggleButton;
Output:
JCheckBox
import javax.swing.*;
public class CheckBoxExample
{
CheckBoxExample(){
JFrame f= new JFrame("CheckBox Example");
JCheckBox checkBox1 = new JCheckBox("DSC++");
checkBox1.setBounds(100,100, 100,50);
JCheckBox checkBox2 = new JCheckBox("Java", true);
checkBox2.setBounds(100,150, 100,50);
f.add(checkBox1);
f.add(checkBox2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String args[])
{
new CheckBoxExample();
}
}
Output:
JRadioButton
JRadioButton
import javax.swing.*;
public class RadioButtonExample {
JFrame f;
RadioButtonExample(){
f=new JFrame();
JRadioButton r1=new JRadioButton(" Male");
JRadioButton r2=new JRadioButton(" Female");
r1.setBounds(75,50,100,30);
r2.setBounds(75,100,100,30);
ButtonGroup bg=new ButtonGroup();
bg.add(r1);bg.add(r2);
f.add(r1);f.add(r2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new RadioButtonExample();
}
}
Output:
JTabbedPane
JTabbedPane
import javax.swing.*;
public class TabbedPaneExample {
JFrame f;
TabbedPaneExample(){
f=new JFrame();
JTextArea ta=new JTextArea(200,200);
JPanel p1=new JPanel();
p1.add(ta);
JPanel p2=new JPanel();
JPanel p3=new JPanel();
JTabbedPane tp=new JTabbedPane();
tp.setBounds(50,50,200,200);
tp.add("Java",p1);
tp.add("C",p2);
tp.add("C++",p3);
f.add(tp);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new TabbedPaneExample();
}
}
Output:
JsScrollPane
JsScrollPane
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.*;
scrollableTextArea.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBA
R_ALWAYS);
scrollableTextArea.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AL
WAYS);
frame.getContentPane().add(scrollableTextArea);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
import javax.swing.*;
public class ListExample
{
ListExample(){
JFrame f= new JFrame();
DefaultListModel<String> l1 = new DefaultListModel<>();
l1.addElement("Java");
l1.addElement("C");
l1.addElement("C++");
l1.addElement("Python");
JList<String> list = new JList<>(l1);
list.setBounds(100,100, 75,75);
f.add(list);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String args[])
{
new ListExample();
}
}
Output:
JComboBox
JComboBox
import javax.swing.*;
public class ComboBoxExample {
JFrame f;
ComboBoxExample(){
f=new JFrame("ComboBox Example");
String name[]={"Anil","Akshara","Gabber","Geetha","Govind"};
JComboBox cb=new JComboBox(name);
cb.setBounds(50, 50,90,20);
f.add(cb);
f.setLayout(null);
f.setSize(400,500);
f.setVisible(true);
//f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new ComboBoxExample();
}
}
Output:
Swing Menus
Swing Menus
import javax.swing.*;
class MenuExample
{
JMenu menu, submenu;
JMenuItem i1, i2, i3, i4, i5;
MenuExample(){
JFrame f= new JFrame("Menu and MenuItem Example");
JMenuBar mb=new JMenuBar();
menu=new JMenu("File");
submenu=new JMenu("Sub Menu");
i1=new JMenuItem("New");
i2=new JMenuItem("Open");
i3=new JMenuItem("Save");
i4=new JMenuItem("Save As");
i5=new JMenuItem("Print");
menu.add(i1); menu.add(i2); menu.add(i3);
submenu.add(i4); submenu.add(i5);
menu.add(submenu);
mb.add(menu);
f.setJMenuBar(mb);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String args[])
{
new MenuExample();
}
}
Output:
Dialogs
Dialogs
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class DialogExample {
private static JDialog d;
DialogExample() {
JFrame f= new JFrame();
d = new JDialog(f , "Dialog Example", true);
d.setLayout( new FlowLayout() );
JButton b = new JButton ("OK");
b.addActionListener ( new ActionListener()
{
public void actionPerformed( ActionEvent e )
{
DialogExample.d.setVisible(false);
}
});
d.add( new JLabel ("Click button to continue."));
d.add(b);
d.setSize(300,300);
d.setVisible(true);
}
public static void main(String args[])
{
new DialogExample();
}
}
Output: