Java Programming PDF
Java Programming PDF
What isJava?
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.
Platform: Any hardware or software environment in which a program runs,
is known as a platform. Since Java has a runtime environment (JRE) and
Application
1. DesktopApplications such as acrobat reader, media player, antivirus,
etc.
2. Web Applications such as [Link], [Link], etc.
3. Enterprise Applications such as banking applications.
4. Mobile
5. Embedded System
6. Smart Card
7. Robotics
8. Games, etc.
Features of Java
Simple
Java is very easy to learn, and its syntax is simple, clean and easy to
understand. According to Sun Microsystem, Java language is a simple
programming language because:
o Java syntax is based on C++ (so easier for programmers to learn it after
C++).
2|Page
[Link]
oJava has removed many complicated and rarely-used features, for
example, explicit pointers, operator overloading, etc.
o There is no need to remove unreferenced objects because there is an
Object-oriented
Java is best known for its security. With Java, we can develop virus-free
systems. Java is secured because:
o No explicit pointer
o Java Programs run inside a virtual machine sandbox
Robust
3|Page
[Link]
o It uses strong memory management. There is a lack of pointers that
o avoids security problems. Java provides automatic garbage collection
o which runs on the Java
Virtual Machine to get rid of objects which are not being used by a Java
application anymore.
Architecture-natural
Java is portable because it facilitates you to carry the Java bytecode to any
platform. It doesn't require any implementation.
High-performance
distributed
Java is because it facilitates users to create distributed
applications in Java.
Multi-threaded
A thread is like a separate program, executing concurrently. We can write
Java programs that deal with many tasks at once by defining multiple
threads.
Dynamic
Java is a dynamic language. It supports the dynamic loading of classes. It
means classes are loaded on demand. It also supports functions from its
native languages, i.e., C and C++.
4|Page
[Link]
First Java Program
o classkeywordis used to declare a class in Java. public keyword is an
o access modifier that represents visibility. It
means it is visible to all.
o static is a keyword. If we declare any method as static, it is known as
the static method. The core advantage of the static method is that there
is no need to create an object to invoke the static method. The main()
method is executed by the JVM, so it doesn't require creating an object
to invoke the main() method. So, it saves memory.
o void is the return type of the method. It means it doesn't return any
value. main represents the starting point of the program. String[] args
o
or String args[] is used for command line argument.
o
[Link]() is used to print statement. Here, System is a
class, out is an object of the PrintStream class, println() is a method of
o
thePrintStream class.
5|Page
[Link]
Q) Can you save a Java source file by another name than the class name?
Yes, if the class is not public. It is explained in the figure given below:
6|Page
[Link]
JRE
JRE is an acronym for Java Runtime Environment. It is also written as Java
RTE. The Java Runtime Environment is a set of software tools which are
used for developing Java applications. It is used to provide the runtime
environment.
JDK
JDK is an acronym for Java Development Kit. The Java Development Kit
(JDK) is a software development environment which is used to develop
Java applications and applets. It physically exists. It contains JRE +
development tools.
Java Variables
A variable is a container which holds the value while the Java program is
executed. A variable is assigned with a data type.
Variable is a name of memory location. There are three types of variables in
java: local, instance and static.
1) Local Variable
A variable declared inside the body of the method is called local variable.
You can use this variable only within that method and the other methods in
the class aren't even aware that the variable exists.
A local variable cannot be defined with "static" keyword.
2) Instance Variable
A variable declared inside the class but outside the body of the method, is
called an instance variable. It is not declared as static.
3) Static variable
A variable that is declared as static is called a static variable. It cannot be
local. You can create a single copy of the static variable and share it among
all the instances of the class.
7|Page
[Link]
Data Types in Java
Datatypesspecify the different sizes and values that can be stored in the
variable. There are two types of data types in Java:
1. Primitive data types: The primitive data types include boolean, char,
byte, short, int, long, float and double.
2. Non-primitive data types: The non-primitive data types
includeClasses, Interfaces, and Arrays.
Unicode System
Unicode is a universal international standard character encoding that is
capable of representing most of the world's written languages.
Problem
This caused two problems:
1. A particular code value corresponds to different letters in the various
language standards.
2. The encodings for languages with large character sets have variable length.
3. Some common characters are encoded as single bytes, other require
8|Page
[Link]
Solution
Tosolve these problems, a new language standard was developed i.e. Unicode
System.
In unicode, character holds 2 byte, so java also uses 2 byte for characters.
lowest value:\u0000
highest value:\uFFFF
Operators in Java
Operator in Java is a symbol that is used to perform operations. For
example: +, -, *, / etc.
There are many types of operators in Java which are given below:
o Unary Operator,
o Arithmetic Operator,
o Shift Operator,
o Relational Operator,
o Bitwise Operator,
o Logical Operator,
o Ternary Operator and
o Assignment Operator.
Java Keywords
Java keywords are also known as reserved words. Keywords are particular
words that act as a key to a code. These are predefined words by Java so
they cannot be used as a variable or object name or class name.
9|Page
[Link]
Java Control Statements | Control Flow in Java
Javaprovides threetypes ofcontrol flowstatements.
Decision-Making statements:
10 | P a g e
[Link]
statements that create a decision tree where the program may enter in the
block of code where the condition is true.
4. Nested if-statement
1. for loop
2. while loop
3. do-while loop
Java for loop
In Java, for loop is similar to C and C++. It enables us to initialize the loop
variable, check the condition, and increment/decrement in a single line of
code. We use the for loop only when we exactly know the number of times,
we want to execute the block of code.
Java for-each loop
Java provides an enhanced for loop to traverse the data structures like array
or collection. In the for-each loop, we don't need to update the loop variable.
The syntax to use the for-each loop in java is given below.
11 | P a g e
[Link]
}
The while loop is also used to iterate over the number of statements multiple
times. However, if we don't know the number of iterations in advance, it is
recommended to use a while loop.
Java do-while loop
The do-while loop checks the condition at the end of the loop after executing
the loop statements. When the number of iteration is not known and we have
to execute the loop at least once, we can use do-while loop.
It is also known as the exit-controlled loop since the condition is not checked
in advance. The syntax of the do-while loop is given below.
do
{
//statements
} while (condition);
Jump Statements
Jump statements are used to transfer the control of the program to the specific
statements. In other words, jump statements transfer the execution control to
the other part of the program.
Java break statement
As the name suggests, the break statement is used to break the current flow
of the program and transfer the control to the next statement outside a loop
or switch statement.
Java continue statement
Unlike break statement, the continue statement doesn't break the loop,
whereas, it skips the specific part of the loop and jumps to the next iteration
of the loop immediately.
12 | P a g e
[Link]
Java Object Class
Any entity that has state and behaviour is known as an object. For
example, a chair, pen, table, keyboard, bike, etc. It can be physical or
logical.
Class
When one object acquires all the properties and behaviours of a parent
object, it is known as inheritance. It provides code reusability.
Polymorphism
13 | P a g e
[Link]
Coupling
Coupling refers to the knowledge or information or dependency of another
class. It arises when classes are aware of each other.
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.
Association
Association represents the relationship between the objects. Here, one object
can be associated with one object or many objects.
Aggregation
Aggregation is a way to achieve Association. Aggregation represents the
relationship where one object contains other objects as a part of its state.
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.
Constructors in Java
In Java, a constructor is a block of codes similar to the method. It is called
when an instance of the class is created. At the time of calling constructor,
memory for the object is allocated in the memory.
Constructor Overloading in Java
Constructor overloading in Java is a technique of having more than one
constructor with different parameter lists.
14 | P a g e
[Link]
Singleton design pattern in Java
Singleton Pattern says that just "define a class that has only one instance
and provides a global point of access to it".
In other words, a class must ensure that only single instance should be created
and single object can be used by all other classes.
There are two forms of singleton design pattern
15 | P a g e
[Link]
Use Cases of Private Constructor
The main purpose of using a private constructor is to restrict object
creation. We also use private constructors to implement the singleton design
pattern. The use-cases of the private constructor are as follows:
16 | P a g e
[Link]
classes. The static keyword belongs to the class than an instance of the
class.
1) Java static variable
If you declare any variable as static, it is known as a static variable.
o The static variable can be used to refer to the common property of all
objects (which is not unique for each object), for example, the company
name of employees, college name of students, etc.
o The static variable gets memory only once in the class area at the time
of class loading.
2) Java static method
If you apply static keyword with any method, it is known as static method.
o A static method belongs to the class rather than the object of a class.
o A static method can be invoked without the need for creating an
instance of a class.
o A static method can access static data member and can change the value
of it.
Ans) It is because the object is not required to call a static method. If it were a
non-static method, JVM creates an object first then call main() method that
will lead the problem of extra memory allocation.
3) Javastaticblock
o Is used to initialize the static data member.
17 | P a g e
[Link]
Q) Can we execute a program without main() method?
Ans) No, one of the ways was the static block, but it was possible till JDK
1.6. Since JDK 1.7, it is not possible to execute a Java class without the main
method.
this keyword in Java
There can be a lot of usage of Java this keyword. In Java, this is
a reference variable that refers to the current object.
Java Inheritance
Inheritance in Java
Inheritance in Java is a mechanism in which one object acquires all the
properties and behaviours of a parent object.
18 | P a g e
[Link]
o For Code Reusability.
19 | P a g e
[Link]
Q) Why Method Overloading is not possible by changing the
return type of method only?
In java, method overloading is not possible by changing the return type of
the method only because of ambiguity.
20 | P a g e
[Link]
Covariant Return Type
The covariant return type specifies that the return type may vary in the same
direction as the subclass.
Super Keyword in Java
The super keyword in Java is a reference variable which is used to refer
immediate parent class object.
1. variable
2. method
21 | P a g e
[Link]
3. class
If you make any variable as final, you cannot change the value of final
variable(It will be constant).
22 | P a g e
[Link]
Q) Can we declare a constructor final? No, because constructor is never
inherited.
Polymorphism in Java
Polymorphism in Java is a concept by which we can perform a single action
in different ways.
There are two types of polymorphism in Java: compile-time polymorphism
and runtime polymorphism. We can perform polymorphism in java by
method overloading and method overriding.
23 | P a g e
[Link]
static binding
Whentype ofthe object is determined at compiled time (by the compiler), it
isknownas static binding.
Dynamic binding
Whentypeoftheobjectisdetermined at run-time, it is known as dynamic
binding.
Java instanceof
Thejavainstanceofoperator is used to test whether the object is an instance
of the specified type (class or subclass or interface).
The instanceof in java is also known as type comparison operator because it
compares the instance with type. It returns either true or false.
Java Abstraction
Abstract class in Java
A class which is declared withthe abstract keyword is known as an abstract
class in Java. It can have abstract and non-abstract methods (method with
the body).
24 | P a g e
[Link]
Abstraction in Java
Abstraction is a process of hiding the implementation details and showing
only functionality to the user.
Ways to achieve Abstraction
There are two ways to achieve abstraction in java
Interface in Java
An interface in Java isablueprint of a class. It has static constants and
abstract methods.
25 | P a g e
[Link]
The interface in Java is a mechanism to achieve abstraction. There can be
only abstract methods in the Java interface, not method body. It is used to
achieve abstraction and multiple inheritance in Java.
Why use Java interface?
There are mainly three reasons to use interface. They are given below.
Syntax:
interface<interface_name>{
1) Abstract class can have abstract and Interface can have only abstract methods.
non-abstract methods. Since Java 8, it can have default and static
methods also.
26 | P a g e
[Link]
3) Abstract class can have final, non- Interface has only static and final variables.
final, static and non-static variables.
4) Abstract class can provide the Interface can't provide the implementation
implementation of interface. of abstract class.
5) The abstract keyword is used to The interface keyword is used to declare
declare abstract class. interface.
6) An abstract class can extend another An interface can extend another Java interface
Java Encapsulation
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.
27 | P a g e
[Link]
Sub package in java
Package inside the package is called the sub package. It should be created to
categorize the package further.
Access Modifiers in Java
There are two types of modifiers in Java: access modifiers and non-access
modifiers.
There are four types of Java access modifiers:
1. Private: The access level of a private modifier is only within the class.
It cannot be accessed from outside the class.
2. Default: The access level of a default modifier is only within the
package. It cannot be accessed from outside the package. If you do not
specify any access level, it will be the default.
3. Protected: The access level of a protected modifier is within the
package and outside the package through child class. If you do not
make the child class, it cannot be accessed from outside the package.
4. Public: The access level of a public modifier is everywhere. It can be
accessed from within the class, outside the class, within the package
and outside the package.
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
Encapsulation in Java
28 | P a g e
[Link]
Encapsulation in Java is a process of wrapping code and data together into a
single unit, for example, a capsule which is mixed of several medicines.
Advantage of Encapsulation in Java
By providing only a setter or getter method, you can make the class read-
only or write-only. In other words, you can skip the getter or setter
methods.
It provides you the control over the data. Suppose you want to set the value
of id which should be greater than 100 only, you can write the logic inside
the setter method.
It is a way to achieve data hiding in Java because other class will not be
able to access the data through the private data members.
Java Array Java Arrays
Java array is an object which contains elements of a similar data type.
Additionally, The elements of an array are stored in a contiguous
memory location. It is a data structure where we store similar elements.
We can store only a fixed set of elements in a Java array.
Array in Java is index-based, the first element of the array is stored at the 0th
index, 2nd element is stored on 1st index and so on.
Advantages
Disadvantages
o Size Limit: We can store only the fixed size of elements in the array. It
doesn't grow its size at runtime. To solve this problem, collection
framework is used in Java which grows automatically.
29 | P a g e
[Link]
Types of Array in java
There are two types of array.
30 | P a g e
[Link]
Advantage of Object cloning
o You don't need to write lengthy and repetitive codes. Just use an
abstract class with a 4- or 5-line long clone() method.
o It is the easiest and most efficient way for copying objects, especially
if we are applying it to an already developed or an old project.
o Clone() is the fastest way tocopy array.
Autoboxing
The automatic conversion of primitive data type into its corresponding
wrapper class is known as autoboxing, for example, byte to Byte, char to
31 | P a g e
[Link]
Character, int to Integer, long to Long, float to Float, boolean to Boolean,
double to Double, and short to Short.
Unboxing
The automatic conversion of wrapper type into its corresponding primitive
type is known as unboxing. It is the reverse process of autoboxing.
Java Strictfp Keyword
Java strictfp keyword ensures that you will get the same result on every
platform if you perform operations in the floating-point variable.
Difference between object and class
32 | P a g e
[Link]
Difference between method overloading and method
overriding in java
Java String
Java String
In Java, string is basically an object that represents sequence of char values.
An array of characters works same as Java string. For example:
33 | P a g e
[Link]
char[] ch={'j','a','v','a','t','p','o','i','n','t'};
String s=new String(ch);
1. By string literal
2. By new keyword
1) String Literal
Java String literal is created by using double quotes. For Example:
1. String s="welcome";
2) By new keyword
[Link] s= new String("Welcome");//creates two objects and one reference va
riable
34 | P a g e
[Link]
Java StringBuilder class is used to create mutable (modifiable) String. The
Java StringBuilder class is same as StringBuffer class except that it is non-
synchronized. It is available since JDK 1.5.
Difference between String and String Buffer
35 | P a g e
[Link]
StringBuffer Class StringBuilder Class
If you want to represent any object as a string, toString() method comes into
existence.
The toString() method returns the String representation of the object.
If you print any object, Java compiler internally invokes the toString()
method on the object.
Advantage of Java toString() method
By overriding the toString() method of the Object class, we can return values
of the object, so we don't need to write much code.
StringTokenizer in Java
36 | P a g e
[Link]
Exception Handling Exception Handling in Java
The Exception Handling in Java is one of the powerful mechanism to
handle the runtime errors so that the normal flow of the application can
be maintained.
1. Checked Exception
2. Unchecked Exception
3. Error
Difference Exceptions
between Checked and Unchecked
1)CheckedException
The classes that directly inherit the Throwable class except Runtime
Exception and Error are known as checked exceptions. For example, IO
Exception, SQL Exception, etc. Checked exceptions are checked at compile-
time.
2) Unchecked Exception
The classes that inherit the Runtime Exception are known as unchecked
exceptions. For example, Arithmetic Exception, NullPointerException,
37 | P a g e
[Link]
ArrayIndexOutOfBoundsException, etc. Unchecked exceptions are not
checked at compile-time, but they are checked at runtime.
3) Error
Error is irrecoverable. Some example of errors are OutOfMemoryError,
VirtualMachineError, AssertionError etc.
Java try-catch block
Java try block
Java try block is used to enclose the code that might throw an exception. It
must be used within the method.
SyntaxofJavatry-catch
try{
//code that may throw an exception
}catch(Exception_class_Name ref){}
A try block can be followed by one or more catch blocks. Each catch block
must contain a different exception handler. So, if you have to perform
different tasks at the occurrence of different exceptions, use java multi-catch
block.
Java Nested try block
38 | P a g e
[Link]
In Java, using a try block inside another try block is permitted. It is called as
nested try block.
Why use nested try block
Sometimes a situation may arise where a part of a block may cause one error
and the entire block itself may cause another error. In such cases, exception
handlers have to be nested.
Java finally block
Java finally block is a block used to execute important code such as closing
the connection, etc.
Java finally block is always executed whether an exception is handled or not.
block.
Let's see the different cases where Java finally block can be used.
Java throw keyword
The Java throw keyword is used to throw an exception explicitly.
We can throw either checked or unchecked exceptions in Java by throw
keyword. It is mainly used to throw a custom exception.
39 | P a g e
[Link]
Java throws keyword
The Java throws keyword is used to declare an exception. It gives an
information to the programmer that there may occur an exception.
40 | P a g e
[Link]
Difference between final, finally and finalize
41 | P a g e
[Link]
Java Multithreading
Multithreading in Java
Multithreading in Java is a process of executing multiple threads
simultaneously.
A thread is a lightweight sub-process, the smallest unit of processing.
Multiprocessingandmultithreading, both are used to achieve multitasking.
Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We use
multitasking to utilize the CPU. Multitasking can be achieved in two ways:
oA thread is lightweight.
42 | P a g e
[Link]
Threads are independent. If there occurs exception in one thread, it doesn't
affect other threads. It uses a shared memory area.
Life cycle of a Thread (Thread States)
In Java, a thread always exists in any one of the following states. These states
are:
1. New
2. Active
3. Blocked / Waiting
4. Timed Waiting
5. Terminated
When a thread invokes the start() method, it moves from the new
state to the active state. The active state contains two states within it: one
is runnable, and the other is running.
43 | P a g e
[Link]
o Abnormal termination: It occurs when some unusual events such as
an unhandled exception or segmentation fault.
Thread class:
Thread class provide constructors and methods to create and perform
operations on a [Link] class extends Object class and implements
Runnable interface.
Commonly used Constructors of Thread class:
o Thread()
o Thread(String name)
o Thread(Runnable r)
o Thread(Runnable r,String name)
44 | P a g e
[Link]
8. public String getName(): returns the name of the thread.
9. public void setName(String name): changes the name of the thread.
10. public Thread currentThread(): returns the reference of
currently executing thread.
11. public int getId(): returns the id of the thread.
12. public [Link] getState(): returns the state of the thread.
13. public boolean isAlive(): tests if the thread is alive.
14. public void yield(): causes the currently executing thread object
to temporarily pause and allow other threads to execute.
15. public void suspend(): is used to suspend the thread(depricated).
16. public void resume(): is used to resume the suspended
thread(depricated).
17. public void stop(): is used to stop the thread(depricated).
18. public boolean isDaemon(): tests if the thread is a daemon
thread.
19. public void setDaemon(boolean b): marks the thread as daemon
or user thread.
20. public void interrupt(): interrupts the thread.
21. public boolean isInterrupted(): tests if the thread has been
interrupted.
22. public static boolean interrupted(): tests if the current thread
has been interrupted.
Runnable interface:
Starting a thread:
The start() method of Thread class is used to start a newly created thread. It
performs the following tasks:
45 | P a g e
[Link]
o A new thread starts(with new callstack).
o The thread moves from New state to the Runnable state.
o When the thread gets a chance to execute, its target run() method will
run.
Time of Arrival: Suppose two threads of the same priority enter the
runnable state, then priority cannot be the factor to pick a thread from these
two threads. In such a case, arrival time of thread is considered by the
thread scheduler.
Thread Scheduler Algorithms
t1 0
t2 1
46 | P a g e
[Link]
t3 2
t4 3
In the above table, we can see that Thread t1 has arrived first, then Thread
t2, then t3, and at last t4, and the order in which the threads will be
processed is according to the time of arrival of threads.
Hence, Thread t1 will be processed first, and Thread t4 will be processed last.
Time-slicing scheduling:
Usually, the First Come First Serve algorithm is non-preemptive, which is
bad as it may lead to infinite blocking (also known as starvation). To avoid
that, some time-slices are provided to the threads so that after some time,
the running thread has to give up the CPU. Thus, the other waiting threads
also get time to run their job.
47 | P a g e
[Link]
In the above diagram, each thread is given a time slice of 2 seconds. Thus,
after 2 seconds, the first thread leaves the CPU, and the CPU is then
captured by Thread2. The same process repeats for the other threads too.
Preemptive-Priority Scheduling:
The name of the scheduling algorithm denotes that the algorithm is related
to the priority of the threads.
Suppose there are multiple threads available in the runnable state. The thread
scheduler picks that thread that has the highest priority.
Working of the Java Thread Scheduler
48 | P a g e
[Link]
Let's understand the working of the Java thread scheduler. Suppose, there are
five threads that have different arrival times and different priorities. Now, it is
the responsibility of the thread scheduler to decide which thread will get the
CPU first.
The thread scheduler selects the thread that has the highest priority, and the
thread begins the execution of the job. If a thread is already in runnable state
and another thread (that has higher priority) reaches in the runnable state,
then the current thread is pre-empted from the processor, and the arrived
thread with higher priority gets the CPU time.
When two threads (Thread 2 and Thread 3) having the same priorities and
arrival time, the scheduling will be decided on the basis of FCFS algorithm.
Thus, the thread that arrives first gets the opportunity to execute first.
49 | P a g e
[Link]
What if we call Java run() method directly instead start()
method?
o Each thread starts in a separate call stack.
o Invoking the run() method from the main thread, the run() method goes onto
the current call stack rather than at the beginning of a new call stack.
50 | P a g e
[Link]
1. public String getName(): is used to return the name of a thread.
2. publicvoid setName(String name): is used to change the name of a th
read.
Current Thread
The currentThread() method returns a reference of the currently executing
thread.
public
The final void setPriority(int newPriority):
[Link]() method updates or assign the priority of the
thread to newPriority. The method throws IllegalArgumentException if the
value newPriority goes out of the range, which is 1 (minimum) to 10
(maximum).
53 | P a g e
[Link]
Constructors of ThreadGroup class
There are only two constructors of ThreadGroup class.
2) ThreadGroup(ThreadGroup creates a
thread
parent, String name) group with a given
parent group and
name.
54 | P a g e
[Link]
The addShutdownHook (Thread hook) method
The addShutdownHook () method of the Runtime class is used to register the
thread with the Virtual Machine.
Syntax:
55 | P a g e
[Link]
How can an object be unreferenced?
There are many ways:
1) By nulling a reference:
1. Employee e= new Employee();
2. e= null;
2) By assigning a reference to another:
1. Employee e1= new Employee();
2. Employee e2= new Employee();
3. e1=e2;//now the first object referred by e1 is available for garbage col
lection
3) Byanonymousobject:
1. new Employee();
finalize() method
The finalize() method is invoked each time before the object is garbage
collected. This method can be used to perform cleanup processing. This
method is defined in Object class as:
gc() method
The gc() method is used to invoke the garbage collector to perform cleanup
processing. The gc() is found in System and Runtime classes.
56 | P a g e
[Link]
Java Runtime class
Java Runtime class is used to interact with java runtime environment. Java
Runtime class provides methods to execute a process, invoke GC, get total
and free memory etc. There is only one instance of [Link] class is
available for one java application.
Important methods of Java Runtime class
57 | P a g e
[Link]
Java Collections
Collections in Java
The Collection in Java is a framework that provides an architecture to store
and manipulate the group of objects.
Java Collections can achieve all the operations that you perform on a data
such as searching, sorting, insertion, manipulation, and deletion.
Java Collection means a single unit of objects. Java Collection framework
provides many interfaces (Set, List, Queue, Deque) and classes (ArrayList,
o It provides readymadearchitecture.
o It represents a set of classes and interfaces.
o It is optional.
1) Java ArrayList
Java ArrayList class uses a dynamic array for storing the
elements. It is like an array, but there is no size limit. We can add
or remove elements anytime. So, it is much more flexible than the
58 | P a g e
[Link]
traditional array. It is found in the [Link] package. It is like the
Vector in C++.
o We can not create an array list of the primitive types, such as int,
float, char, etc. It is required to use the required wrapper class in
such cases. For example:
59 | P a g e
[Link]
2) Java LinkedList class
Java LinkedList class uses a doubly linked list to store the elements. It
provides a linked-list data structure. It inherits the Abstract List class and
implements List and Deque interfaces.
The important points about Java LinkedList are:
60 | P a g e
[Link]
Doubly Linked List
In the case of a doubly linked list, we can add or remove elements from both
sides.
ArrayList LinkedList
61 | P a g e
[Link]
5) The memory location for the The location for the elements of a
elements of an ArrayList is linked list is not contagious.
contiguous.
6) Generally, when an ArrayList is There is no case of default
initialized, a default capacity of 10 capacity in a LinkedList. In
is assigned to
LinkedList, anthe ArrayList.
empty list is
created when a LinkedList is
initialized.
7) To be precise, an ArrayList is a
LinkedList the implements
resizable array. doubly linked list of the list
interface.
Java List
List in Java provides the facility to maintain the ordered collection. It
contains the index-based methods to insert, update, delete and search the
elements. It can have the duplicate elements also. We can also store the null
elements in the list.
The List interface is found in the [Link] package and inherits the Collection
interface. It is a factory of ListIterator interface. Through the ListIterator, we
can iterate the list in forward and backward directions. The implementation
classes of List interface are ArrayList, LinkedList, Stack and Vector. The
ArrayList and LinkedList are widely used in Java programming. The Vector
class is deprecated since Java 5.
Java HashSet
Java HashSet class is used to create a collection that uses a hash table for
storage. It inherits the AbstractSet class and implements Set interface.
62 | P a g e
[Link]
The important points about Java HashSet class are:
63 | P a g e
[Link]
Java LinkedHashSet class is a Hashtable and Linked list implementation of
the Set interface. It inherits the HashSet class and implements the Set
interface.
The important points about the Java LinkedHashSet class are:
64 | P a g e
[Link]
oJava TreeMap cannot have a null key but can have multiple null
values.
o Java TreeMap is non synchronized.
Java TreeSet class implements the Set interface that uses a tree for storage.
It inherits AbstractSet class and implements the NavigableSet interface.
The objects of the TreeSet class are stored in ascending order.
The important points about the Java TreeSet class are:
65 | P a g e
[Link]
Java Queue Interface
The interface Queue is available in the [Link] package and does extend the
Collection interface. It is used to keep the elements that are processed in the
First In First Out (FIFO) manner. It is an ordered list of objects, where
insertion of elements occurs at the end of the list, and removal of elements
occur at the beginning of the list.
Being an interface, the queue requires, for the declaration, a concrete class,
and the most common classes are the LinkedList and PriorityQueue in Java.
Implementations done by these classes are not thread safe. If it is required to
have a thread safe implementation, PriorityBlockingQueue is an available
option.
Features of a Queue
The following are some important features of a queue.
66 | P a g e
[Link]
PriorityQueue Class
PriorityQueue is also class that is defined in the collection framework that
gives us a way for processing the objects on the basis of priority. It is
already described that the insertion and deletion of objects follows FIFO
pattern in the Java queue. However, sometimes the elements of the queue
are needed to be processed according to the priority, that's where a
PriorityQueue comes into action.
Java Deque Interface
The interface called Deque is present in [Link] package. It is the subtype
of the interface queue. The Deque supports the addition as well as the
removal of elements from both ends of the data structure. Therefore, a
deque can be used as a stack or a queue. We know that the stack supports
the Last In First Out (LIFO) operation, and the operation First In First Out is
supported by a queue. As a deque supports both, either of the mentioned
operations can be performed on it. Deque is an acronym for "double ended
queue".
Points to remember
o A Hashtable is an array of a list. Each list is known as a bucket.
67 | P a g e
[Link]
The initial default loadFactor
capacity is
of0.75
Hashtable class is 11 whereas
Java Map Interface
Amapcontains values on the basis of key, i.e. key and value pair. Each key
and value pair is known as an entry. A Map contains unique keys.
A Map is useful if you have to search, update or delete elements on the basis
of a key.
Java Map Hierarchy
There are twointerfaces for implementing Map in java: Map and SortedMap,
and three classes: HashMap, LinkedHashMap, and TreeMap. A Map doesn't
allow duplicate keys, but you can have duplicate values. HashMap and
LinkedHashMap allow null keys and values, but TreeMap doesn't allow any
null key or value.
A Map can't be traversed, so you need to convert it into Set
using keySet() or entrySet() method.
Java HashMap
Java HashMap class implements the Map interface which allows us to store
key and value pair, where keys should be unique. If you try to insert the
duplicate key, it will replace the element of the corresponding key. It is easy
68 | P a g e
[Link]
to perform operations using the key index like updation, deletion, etc.
HashMap class is found in the [Link] package.
HashMap in Java is like the legacy Hashtable class, but it is not synchronized.
It allows us to store the null elements as well, but there should be only one
null key. Since Java 5, it is denoted as HashMap<K,V>, where K stands for
key and V for value. It inherits the AbstractMap class and implements the
Map interface.
Points to remember
o Java HashMap contains values based on the key.
o Java HashMap may have one null key and multiple null values.
factor of 0.75.
69 | P a g e
[Link]
Difference between HashMap and Hashtable
HashMap and Hashtable both are used to store data in key and value
form. Both are using hashing technique to store unique keys.
HashMap Hashtable
Hashtable
1) HashMap
is synchronized.
is It is
non
synchronized. It is not-thread thread-safe and can be shared with
safe and can't be shared many threads.
between many threads without
proper synchronization code.
2) HashMap allows one null Hashtable doesn't allow any null
key and multiple null values. key or value.
3) HashMap is a new class Hashtable is a legacy class.
introduced in JDK 1.2.
4) HashMap is fast. Hashtable is slow.
5) We can make the HashMap Hashtable is internally synchronized as
synchronized by calling this and can't be unsynchronized. code Map
m =
[Link](
hashMap);
6) HashMap is traversed by Hashtable is traversed by
Iterator. Enumerator and Iterator.
7) Iterator in HashMap is fail- Enumerator in Hashtable is not fail-
fast. fast.
8) HashMap Hashtable inherits Dictionary class.
inherits AbstractMap class.
70 | P a g e
[Link]
Java LinkedHashMap class
o Java LinkedHashMap may have one null key and multiple null
values.
o Java LinkedHashMap is non synchronized.
71 | P a g e
[Link]
Java Collections class
Javacollection class isusedexclusively with static methods that
operate on or return collections. It inherits Object class.
The important points about Java Collections class are:
Comparable Comparator
72 | P a g e
[Link]
3) Comparable provides compareTo() Comparator provides compare()
method to sort elements. method to sort elements.
4) Comparable is present A Comparator is present in
in [Link] package. the [Link] package.
5) We can sort the list elements of We can sort the list elements of
Comparable type Comparator type
by [Link](List) method. by [Link](List,
Comparator) method.
73 | P a g e
[Link]
Java Vector
Vectoris like the dynamic array which can grow or shrink its size.
Unlike array, we can store n-number of elements in it as there is no
size limit. It is a part of Java Collection framework since Java 1.2. It
is found in the [Link] package and implements the List interface,
so we can use all the methods of List interface here.
It is recommended to use the Vector class in the thread-safe
implementation only. If you don't need to use the thread-safe
implementation, you should use the ArrayList, the ArrayList will
perform better in such case.
The Iterators returned by the Vector class are fail-fast. In case of
the
concurrent modification, it fails and throws
ConcurrentModificationException.
Java Stack
The stack is a linear data structure that is used to store the collection
of objects. It is based on Last-In-First-Out (LIFO). Java collection
framework provides many interfaces and classes to store the
collection of objects. One of them is the Stack class that provides
different operations such as push, pop, search, etc.
Stack
In this section, we will discuss the Java
class,
its methods, and implement the stack data structure in a Java
program. But before moving to the Java Stack class have a quick
view of how the stack works.
The stack data structure has the two most important operations that
are push and pop. The push operation inserts an element into the
stack and pop operation removes an element from the top of the
stack. Let's see how they work on stack.
74 | P a g e
[Link]
Java JDBC
JDBCstands for Java Database Connectivity. JDBC is a Java API to connect
and execute the query with the database. It is a part of JavaSE (Java Standard
Edition). JDBC API uses JDBC drivers to connect with the database. There
are four types of JDBC drivers:
75 | P a g e
[Link]
A list of popular classes of JDBC API are given below:
o DriverManager class
o Blob class
o Clob class
o Types class
Before JDBC, ODBC API was the database API to connect and execute the
query with the database. But, ODBC API uses ODBC driver which is written
in C language (i.e. platform dependent and unsecured).
Java Reflection API
Java Reflection is a process of examining or modifying the run time
JDBC Driver
JDBC Driver is a software component that enables java application to
interact with the database. There are 4 types of JDBC drivers:
1. JDBC-ODBC bridge driver
2. Native-API driver (partially java driver)
3. Network Protocol driver (fully java driver)
4. Thin driver (fully java driver)
76 | P a g e
[Link]
1) JDBC-ODBC bridge driver
The JDBC-ODBC bridge driver uses ODBC driver to connect to the database.
The JDBC-ODBC bridge driver converts JDBC method calls into the ODBC
function calls.
Advantages:
o easy to use.
Disadvantages:
o Performance degraded because JDBC method call is converted into the
ODBC function calls.
o The ODBC driver needs to be installed on the client machine.
2) Native-API driver
TheNativeAPI driver uses the client-side libraries of the database. The driver
converts JDBC method calls into native calls of the database API. It is not
written entirely in java.
Advantage:
o performance upgraded than JDBC-ODBC bridge driver.
Disadvantage:
o The Native driver needs to be installed on the each client machine.
Advantage:
o Noclient side library is required because of application server that can
perform many tasks like auditing, load balancing, logging etc.
77 | P a g e
[Link]
Disadvantages:
o Network support is required on client machine.
Advantage:
o Betterperformance than all other drivers.
Disadvantage:
o Driversdepend on the Database.
78 | P a g e
[Link]
1) Register the driver class
The forName() methodofClass class is used to register the driver class. This
methodisusedtodynamically load the driver class.
Syntax of forName() method
1. public static void forName(String className)throws ClassNotFound
Exception
79 | P a g e
[Link]
5) Close the connection object
Byclosing connectionobjectstatement and ResultSet will be closed
automatically. The close() method of Connection interface is used to close the
connection.
80 | P a g e
[Link]