2. • Name of the Subject : Programming in Java
(Lab)
• Subject Code : CS 2015
• Schemes :
Teaching Scheme Evaluation Scheme
Lectures : 1 Hr/Week Term Work 50 Marks
Practical : 4 Hrs/Week Practical/Viva-voce 50 Marks
Total Credits 2
4. What is Java
• Java is a popular programming language, created
in 1995
• It is owned by Oracle, and more than 3
billion devices run Java.
• It is used for:
• Mobile applications (specially Android apps)
• Desktop applications
• Web applications
• Web servers and application servers
• Games
• Database connection
5. Why Use Java?
• Java works on different platforms (Windows,
Mac, Linux, Raspberry Pi, etc.)
• It is one of the most popular programming
language in the world
• It has a large demand in the current job
market
• It is easy to learn and simple to use
• It is open-source and free
• It is secure, fast and powerful
6. Why Use Java?
• It has a huge community support (tens of
millions of developers)
• Java is an object oriented language which
gives a clear structure to programs and allows
code to be reused, lowering development
costs
• As Java is close to C++ and C#, it makes it easy
for programmers to switch to Java or vice
versa
7. JAVA Syntax
• Consider the example :
Main.java
public class Main { public static void
main(String[] args) { System.out.println("Hello
World"); } }
8. EXAMPLE EXPLANATION
• Every line of code that runs in Java must be
inside a class. In our example, we named the
class Main. A class should always start with an
uppercase first letter.
• Note: Java is case-sensitive: "MyClass" and
"myclass" has different meaning.
• The name of the java file must match the class
name. When saving the file, save it using the
class name and add ".java" to the end of the
filename.
9. • The main() method :
–The main() method is required and
you will see it in every Java
program:
–public static void main(String[]
args)
–Any code inside the main() method
will be executed
EXAMPLE EXPLANATION
10. • System.out.println()
– Inside the main() method, we can use
the println() method to print a line of text to the
screen:
– public static void main(String[] args) {
System.out.println("Hello World"); }
– The curly braces {} marks the beginning and the
end of a block of code
– System is a built-in Java class that contains useful
members, such as out, which is short for "output"
EXAMPLE EXPLANATION
11. • System.out.println()
– The println() method, short for "print line", is used
to print a value to the screen (or a file).
– Each code statement must end with a semicolon
(;).
EXAMPLE EXPLANATION
12. Double Quotes
• Working with text, it must be wrapped
inside double quotations marks "“.
Otherwise an error occurs
• Example :
–System.out.println("This sentence will
work!");
–System.out.println(This sentence will
produce an error);
13. The Print() Method
• There is also a print() method, which is
similar to println().
• The only difference is that it does not
insert a new line at the end of the output
• Example :
–System.out.print("Hello World! ");
–System.out.print("I will print on the same
line.");
14. Print Numbers
• You can also use the println() method to
print numbers.
• However, unlike text, we don't put
numbers inside double quotes:
• Example
• System.out.println(3);
System.out.println(358);
System.out.println(50000);
16. Collection Class
– utility classes
– java.util
– used with the static methods that operate on the
collections or return the collection
– NullPointerException
• Syntax: Declaration
public class Collections
extends Object
• Remember: Object is the parent class of all the
classes
17. • Contains 3 fields used to return
entities.
–EMPTY_LIST
–EMPTY_SET
–EMPTY_MAP
Collection Class
18. Array List
• ArrayList class
• uses a dynamic array for storing the elements
• no size limit
• found in the java.util package
• can have the duplicate elements also
• ArrayList maintains the insertion order internally
• non synchronized
• allows random access because the array works on
an index basis
19. Array List
• ArrayList<Integer> al = new ArrayList<In
teger>();
• Java ArrayList gets initialized by the size.
The size is dynamic in the array list,
which varies according to the elements
getting added or removed from the list.
• Declaration for java.util.ArrayList class –
ArrayList<String> list=new ArrayList<String>
();
20. Linked List Classes
• LinkedList
• collection which can contain many objects of
the same type
• All operations same as ArrayList; because both
come under LIST interface
• Difference :
– Container approach
– ArrayList for storing and accessing data
and LinkedList to manipulate data
22. Inserting Elements in Linked List
• There are three different ways in which we
can insert a node in a linked list -:
• Insertion at beginning
• Insertion at end
• Insertion at nth position
23. • Insertion at beginning
• To perform insertion at beginning in singly
linked list we will use the following steps:-
1. We will create a space at beginning, before
head node.
2. In this space created we will built a new
node.
3. After that we will but the data in the new
node that we want to insert.
Inserting Elements in Linked List
24. • Insertion at end
• In the process of Insertion at the Last Position we’ll
begin by checking whether if the linked list is empty.
• If the head is equal to null, then the list is already
empty else the list already has an element.
• In Order to insert a node in the end we’ll first store the
current pointer address of null from the current last
node to a temporary variable.
• The value of that temporary variable will now be
stored in the address of the new node being inserted.
• Followed by which we’ll store the address of the new
node into the previous last node of the linked list.
Inserting Elements in Linked List
25. • Insertion at nth position
• First we will create a new node named
by newnode and put the position where
you want to insert the node.
• Now give the address of the new node in
previous node means link the new node
with previous node.
• After this, give the address of current
node in new node. Means link your new
node also with current node.
Inserting Elements in Linked List
26. Hash Set Class
• Used to create a collection that uses a hash
table for storage.
• HashSet stores the elements by using a
mechanism called hashing
• HashSet contains unique elements only
• HashSet allows null value
• HashSet class is non synchronized
• HashSet doesn't maintain the insertion order
27. • Elements are inserted on the basis of their
hashcode.
• HashSet class declaration :
public class HashSet<E> extends AbstractSet<E>
implements Set<E>, Cloneable, Serializable
Hash Set Class
28. • Constructors of Java HashSet class
Hash Set Class
Constructor Description
HashSet() It is used to construct a
default HashSet.
HashSet(int capacity) It is used to initialize the
capacity of the hash set to the
given integer value capacity.
HashSet(Collection<?
extends E> c)
It is used to initialize the hash
set by using the elements of
the collection c.
29. Tree Set Class
• Provides the functionality of a tree data
structure.
• To create a tree set, we must import
the java.util.TreeSet package
• Declaration :
TreeSet<Integer> numbers = new TreeSet<>();
• Here, we have created a TreeSet without any
arguments. In this case, the elements
in TreeSet are sorted naturally (ascending
order).
30. Methods of TreeSet
• add() - inserts the specified element to the
set
• addAll() - inserts all the elements of the
specified collection to the set
• remove() - removes the specified element
from the set
• removeAll() - removes all the elements from
the set
• first() - returns the first element of the set
• last() - returns the last element of the set
31. Assignment No - 01
Implement Collection Framework
Using Stack, ArrayList and Vector
33. 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)
• Provides different operations such as push,
pop, search, etc.
• The push operation inserts an element into
the stack and pop operation removes an
element from the top of the stack
39. • In Java, Stack is a class that falls under the
Collection framework that extends
the Vector class
• Before using the Stack class, we must import
the java.util package
JAVA STACK CLASS
40. STACK CLASS CONSTRUCTOR
• The Stack class contains only the default
constructor that creates an empty stack.
public Stack()
41. CREATING A STACK
• import the java.util package and create an
object of the Stack class
• Stack stk = new Stack();
Or
• Stack<type> stk = new Stack<>();
Where type denotes the type of stack like
Integer, String, etc
42. Methods of the Stack Class
Method Method Description
empty() The method checks the stack is empty or not.
push(E item) The method pushes (insert) an element onto the
top of the stack.
pop() The method removes an element from the top of
the stack and returns the same element as the
value of that function.
peek() The method looks at the top element of the stack
without removing it.
search(Object) The method searches the specified object and returns the
position of the object
44. import java.util.Stack;
public class StackEmptyMethodExample
{
public static void main(String[] args)
{
//creating an instance of Stack class
Stack<Integer> stk= new Stack<>();
// checking stack is empty or not
boolean result = stk.empty();
System.out.println("Is the stack empty? " + result);
// pushing elements into stack
stk.push(78);
stk.push(113);
stk.push(90);
stk.push(120);
//prints elements of the stack
System.out.println("Elements in Stack: " + stk);
result = stk.empty();
System.out.println("Is the stack empty? " + result);
}
}
45. • Output:
Is the stack empty? true
Elements in Stack: [78, 113, 90, 120]
Is the stack empty? false
StackEmptyMethodExample.java
47. import java.util.*;
public class StackPushPopExample
{
public static void main(String args[])
{
//creating an object of Stack class
Stack <Integer> stk = new Stack<>();
System.out.println("stack: " + stk);
48. //pushing elements into the stack
pushelmnt(stk, 20);
pushelmnt(stk, 13);
pushelmnt(stk, 89);
pushelmnt(stk, 90);
pushelmnt(stk, 11);
pushelmnt(stk, 45);
pushelmnt(stk, 18);
49. //popping elements from the stack
popelmnt(stk);
//throws exception if the stack is empty
try
{
popelmnt(stk);
}
catch (EmptyStackException e)
{
System.out.println("empty stack");
}
}
55. import java.util.Stack;
public class StackPeekMethodExample
{
public static void main(String[] args)
{
Stack<String> stk= new Stack<>();
// pushing elements into Stack
stk.push("Apple");
stk.push("Grapes");
stk.push("Mango");
stk.push("Orange");
System.out.println("Stack: " + stk);
56. // Access element from the top of the
stack
String fruits = stk.peek();
//prints stack
System.out.println("Element at top: "
+ fruits);
}
}
59. import java.util.Stack;
public class StackSearchMethodExample
{
public static void main(String[] args)
{
Stack<String> stk= new Stack<>();
//pushing elements into Stack
stk.push("Mac Book");
stk.push("HP");
stk.push("DELL");
stk.push("Asus");
System.out.println("Stack: " + stk);
// Search an element
int location = stk.search("HP");
System.out.println("Location of Dell: " + location);
}
}
61. import java.util.Stack;
public class StackSizeExample
{
public static void main (String[] args)
{
Stack stk = new Stack();
stk.push(22);
stk.push(33);
stk.push(44);
stk.push(55);
stk.push(66);
62. // Checks the Stack is empty or not
boolean rslt=stk.empty();
System.out.println("Is the stack empty or
not? " +rslt);
// Find the size of the Stack
int x=stk.size();
System.out.println("The stack size is: "+x);
}
}
64. ASSIGNMENT NO – 1 (C)
IMPLEMENT COLLECTION
FRAMEWORK USING
VECTOR
65. JAVA VECTOR
• Vector is 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 java.util package and
implements the List interface, so we can use
all the methods of List interface here.
66. • It is recommended to use the Vector class in
the thread-safe implementation only
• The Iterators returned by the Vector class
are fail-fast.
• In case of concurrent modification, it fails and
throws the ConcurrentModificationException.
• It is similar to the ArrayList, but with two
differences-
JAVA VECTOR
67. • Vector is synchronized.
• Java Vector contains many legacy
methods that are not the part of a
collections framework.
JAVA VECTOR
68. JAVA VECTOR CONSTRUCTORS
Constructor Description
vector() It constructs an empty vector
with the default size as 10.
vector(int initialCapacity) It constructs an empty vector
with the specified initial
capacity and with its capacity
increment equal to zero.
vector(int initialCapacity, int
capacityIncrement)
It constructs an empty vector
with the specified initial
capacity and capacity
increment.
69. JAVA VECTOR METHODS
Method Description
add() It is used to append the
specified element in the
given vector.
addAll() It is used to append all of the
elements in the specified
collection to the end of this
Vector.
addElement() It is used to append the
specified component to the
end of this vector. It
increases the vector size by
70. Method Description
capacity() It is used to get the
current capacity of this
vector.
clear() It is used to delete all of
the elements from this
vector.
clone() It returns a clone of this
vector.
JAVA VECTOR METHODS
71. Method Description
contains()
It returns true if the
vector contains the
specified element.
containsAll() It returns true if the
vector contains all of the
elements in the specified
collection.
copyInto() It is used to copy the
components of the
vector into the specified
JAVA VECTOR METHODS
72. Method Description
elementAt() It is used to get the
component at the specified
index.
elements() It returns an enumeration of
the components of a vector.
ensureCapacity() It is used to increase the
capacity of the vector which
is in use, if necessary. It
ensures that the vector can
hold at least the number of
components specified by the
JAVA VECTOR METHODS
73. Method Description
equals() It is used to compare the
specified object with the
vector for equality.
firstElement() It is used to get the first
component of the vector.
forEach() It is used to perform the
given action for each
element of the Iterable until
all elements have been
processed or the action
throws an exception.
JAVA VECTOR METHODS
74. Method Description
get() It is used to get an element
at the specified position in
the vector.
hashCode() It is used to get the hash
code value of a vector.
indexOf() It is used to get the index of
the first occurrence of the
specified element in the
vector. It returns -1 if the
vector does not contain the
element
JAVA VECTOR METHODS
75. Method Description
insertElementAt() It is used to insert the
specified object as a
component in the given
vector at the specified
index.
isEmpty() It is used to check if this
vector has no
components.
iterator() It is used to get an
iterator over the
JAVA VECTOR METHODS
76. Method Description
lastElement() It is used to get the last
component of the vector.
lastIndexOf() It is used to get the index of
the last occurrence of the
specified element in the
vector. It returns -1 if the
vector does not contain the
element.
listIterator() It is used to get a list iterator
over the elements in the list
in proper sequence.
JAVA VECTOR METHODS
77. Method Description
remove() It is used to remove the
specified element from the
vector. If the vector does not
contain the element, it is
unchanged.
removeAll() It is used to delete all the
elements from the vector that
are present in the specified
collection.
removeAllElements() It is used to remove all
elements from the vector and
JAVA VECTOR METHODS
78. Method Description
removeElement() It is used to remove the first
(lowest-indexed) occurrence
of the argument from the
vector.
removeElementAt() It is used to delete the
component at the specified
index.
removeIf() It is used to remove all of the
elements of the collection
that satisfy the given
predicate.
JAVA VECTOR METHODS
79. Method Description
removeRange() It is used to delete all of the
elements from the vector
whose index is between
fromIndex, inclusive and
toIndex, exclusive.
replaceAll() It is used to replace each
element of the list with the
result of applying the
operator to that element.
retainAll() It is used to retain only that
element in the vector which
JAVA VECTOR METHODS
80. Method Description
set() It is used to replace the
element at the specified
position in the vector with the
specified element.
setElementAt() It is used to set the
component at the specified
index of the vector to the
specified object.
setSize() It is used to set the size of
the given vector.
JAVA VECTOR METHODS
81. Method Description
size() It is used to get the number
of components in the given
vector.
sort() It is used to sort the list
according to the order
induced by the specified
Comparator.
spliterator() It is used to create a late-
binding and fail-fast
Spliterator over the elements
in the list.
JAVA VECTOR METHODS
82. Method Description
subList() It is used to get a view of
the portion of the list
between fromIndex,
inclusive, and toIndex,
exclusive.
toArray() It is used to get an array
containing all of the
elements in this vector in
correct order.
toString() It is used to get a string
JAVA VECTOR METHODS
84. JAVA VECTOR EXAMPLE
import java.util.*;
public class VectorExample {
public static void main(String args[]) {
//Create a vector
Vector<String> vec = new Vector<Strin
g>();
85. //Adding elements using add() method
of List
vec.add("Tiger");
vec.add("Lion");
vec.add("Dog");
vec.add("Elephant");
86. //Adding elements using addElement() met
hod of Vector
vec.addElement("Rat");
vec.addElement("Cat");
vec.addElement("Deer");
System.out.println("Elements are: "+v
ec);
}
}
89. JAVA VECTOR EXAMPLE 2
import java.util.*;
public class VectorExample1 {
public static void main(String args[]) {
//Create an empty vector with initial c
apacity 4
Vector<String> vec = new Vector<Strin
g>(4);
90. //Adding elements to a vector
vec.add("Tiger");
vec.add("Lion");
vec.add("Dog");
vec.add("Elephant");
91. //Check size and capacity
System.out.println("Size is: "+v
ec.size());
System.out.println("Defaul
t capacity is: "+vec.capacity());
93. //Again check size and capacity
System.out.println("Size after addit
ion: "+vec.size());
System.out.println("Capacity
after addition is: "+vec.capacity())
;
95. //Checking if Tiger is present or not in this vecto
r
if(vec.contains("Tiger"))
{
System.out.println("Tiger is present at t
he index " +vec.indexOf("Tiger"));
}
else
{
System.out.println("Tiger is not present
in the list.");
96. //Get the first element
System.out.println("The first
animal of the vector is = "+vec.firs
tElement());
97. //Get the last element
System.out.println("The last a
nimal of the vector is = "+vec.last
Element());
}
}
99. Size is: 4
Default capacity is: 4
Vector element is: [Tiger, Lion, Dog,
Elephant] Size after addition: 7
Capacity after addition is: 8
Elements are: [Tiger, Lion, Dog, Elephant,
Rat, Cat, Deer]
Tiger is present at the index 0
The first animal of the vector is = Tiger
The last animal of the vector is = Deer
100. JAVA VECTOR EXAMPLE 3
import java.util.*;
public class VectorExample2 {
public static void main(String args[
]) {
//Create an empty Vector
Vector<Integer> in = new Vector<
>();
101. //Add elements in the vector
in.add(100);
in.add(200);
in.add(300);
in.add(200);
in.add(400);
in.add(500);
in.add(600);
in.add(700);
103. //Remove the element at index 4
System.out.println("Remove el
ement at index 4: " +in.remove(4)
);
System.out.println("New Value
list in vector: " +in);
109. Values in vector: [100, 200, 300, 200,
400, 500, 600, 700]
Remove element at index 4: 500
New Value list in vector: [100, 300,
200, 400, 600, 700]
Vector element after removal: [100,
300, 200, 400, 600]
Hash code of this vector = 130123751
Element at index 1 is = 300
112. QUEUE
• The interface Queue is available in the
java.util package
• 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.
113. • Being an interface, the queue
requires, for the declaration, a
concrete class, and the most
common classes are the LinkedList
and PriorityQueue in Java
QUEUE
114. • Those Queues that are present in
the util package are known as Unbounded
Queues
• Those Queues that are present in
the util.concurrent package are known as
bounded Queues
FEATURES OF QUEUE
115. METHODS OF QUEUE
Method Description
add(object) It is used to insert the specified
element into this queue and
return true upon success
offer(object) It is used to insert the specified
element into this queue
remove() It is used to retrieves and
removes the head of this queue.
116. Method Description
poll() It is used to retrieves and removes
the head of this queue, or returns
null if this queue is empty.
element() It is used to retrieves, but does not
remove, the head of this queue
peek() It is used to retrieves, but does not
remove, the head of this queue, or
returns null if this queue is empty.
METHODS OF QUEUE
117. QUEUE PROGRAM
import java.util.LinkedList;
import java.util.Queue;
//Demonstrate Queue interface
methods with LinkedList
implementation
public class QueueExample {
public static void main(String[] args) {
118. // Create and initialize a Queue
using a LinkedList
Queue<String> elementQueue =
new LinkedList<>();
QUEUE PROGRAM
119. • // Adding new elements to the Queue
elementQueue.add("element1");
elementQueue.add("element2");
elementQueue.add("element3");
elementQueue.add("element4");
System.out.println("WaitingQueue : " +
elementQueue);
QUEUE PROGRAM
120. • // Removing an element from the
Queue using remove()
String name =
elementQueue.remove();
System.out.println("Removed from
WaitingQueue : " + name + " | New
WaitingQueue : " + elementQueue);
QUEUE PROGRAM
121. • // Removing an element from the
Queue using poll()
name = elementQueue.poll();
System.out.println("Removed from
WaitingQueue : " + name + " | New
WaitingQueue : " + elementQueue);
}
}
QUEUE PROGRAM
122. OUTPUT
WaitingQueue : [element1, element2,
element3, element4]
Removed from WaitingQueue : element1 |
New WaitingQueue : [element2,
element3, element4]
Removed from WaitingQueue : element2 |
New WaitingQueue : [element3,
element4]
123. Queue Interface Methods - isEmpty(),
size(), element(), peek()
import java.util.LinkedList;
import java.util.Queue;
// Demonstrate Queue interface methods
with LinkedList implementation.
public class QueueSizeSearchFrontExample
{
public static void main(String[] args) {
Queue<String> elementQueue = new
LinkedList<>();
125. • // Check is a Queue is empty
System.out.println("is waitingQueue
empty? : " + elementQueue.isEmpty());
// Find the size of the Queue
System.out.println("Size of
waitingQueue : " +
elementQueue.size());
Queue Interface Methods - isEmpty(),
size(), element(), peek()
126. • // Check if the Queue contains an element
String name = "Johnny";
if(elementQueue.contains(name)) {
System.out.println("WaitingQueue
contains " + name);
} else {
System.out.println("Waiting Queue doesn't
contain " + name);
}
Queue Interface Methods - isEmpty(),
size(), element(), peek()
127. // Get the element at the front of the
Queue without removing it using
element()
String firstElementInTheWaitingQueue =
elementQueue.element();
System.out.println("Waiting Queue
(element()) : " +
firstElementInTheWaitingQueue);
Queue Interface Methods - isEmpty(),
size(), element(), peek()
128. • // Get the element at the front of the
Queue without removing it using peek()
firstElementInTheWaitingQueue =
elementQueue.peek();
System.out.println("Waiting Queue : " +
firstElementInTheWaitingQueue);
}
}
Queue Interface Methods - isEmpty(),
size(), element(), peek()
131. DEQUEUE
• Deque interface present in java.util package is
a subtype of the queue interface
• Deque is related to the double-ended queue
that supports the addition or removal of
elements from either end of the data
structure.
• It can either be used as a queue(first-in-first-
out/FIFO) or as a stack(last-in-first-out/LIFO)
• Deque is the acronym for double-
ended queue
132. ADVANTAGES OF DEQUEUE
• Double-Ended: The main advantage of
the Deque interface is that it provides a
double-ended queue, which allows
elements to be added and removed from
both ends of the queue
• Flexibility: The Deque interface provides
a number of methods for adding,
removing, and retrieving elements from
both ends of the queue
133. • Performance: The performance of a Deque
can be slower than other data structures, such
as a linked list or an array, because it provides
more functionality
• Implementation Dependent: The behavior of a
Deque can depend on the implementation
you use. For example, some implementations
may provide thread-safe operations, while
others may not. It’s important to choose an
appropriate implementation and understand
its behavior before using a Deque.
DISADVANTAGES OF DEQUEUE
134. METHODS OF DEQUEUE
METHOD DESCRIPTION
add(element)
This method is used to add an element at the tail of
the queue. If the Deque is capacity restricted and no
space is left for insertion, it returns an
IllegalStateException. The function returns true on
successful insertion.
addFirst(element)
This method is used to add an element at the head
of the queue. If the Deque is capacity restricted and
no space is left for insertion, it returns an
IllegalStateException. The function returns true on
successful insertion.
addLast(element)
This method is used to add an element at the tail of
the queue. If the Deque is capacity restricted and no
space is left for insertion, it returns an
IllegalStateException. The function returns true on
135. Method Description
contains()
This method is used to check
whether the queue contains the
given object or not.
descendingIterat
or()
This method returns an iterator for
the deque. The elements will be
returned in order from last(tail) to
first(head).
element()
This method is used to retrieve, but
not remove, the head of the queue
represented by this deque.
METHODS OF DEQUEUE
136. Method Description
getFirst()
This method is used to retrieve, but
not remove, the first element of this
deque.
getLast()
This method is used to retrieve, but
not remove, the last element of this
deque
iterator()
This method returns an iterator for
the deque. The elements will be
returned in order from first (head) to
last (tail).
METHODS OF DEQUEUE
137. Method Description
offer(element)
This method is used to add an element at the tail of the queue.
This method is preferable to add() method since this method
does not throws an exception when the capacity of the
container is full since it returns false.
offerFirst(element)
This method is used to add an element at the
head of the queue. This method is preferable to
addFirst() method since this method does not
throws an exception when the capacity of the
container is full since it returns false.
offerLast(element)
This method is used to add an element at the
tail of the queue. This method is preferable to
add() method since this method does not
throws an exception when the capacity of the
container is full since it returns false.
METHODS OF DEQUEUE
138. Method Description
peek()
This method is used to retrieve the element at
the head of the deque but doesn’t remove the
element from the deque. This method returns
null if the deque is empty.
peekFirst()
This method is used to retrieve the element at
the head of the deque but doesn’t remove the
element from the deque. This method returns
null if the deque is empty.
peekLast()
This method is used to retrieve the element at
the tail of the deque but doesn’t remove the
element from the deque. This method returns
null if the deque is empty.
METHODS OF DEQUEUE
139. Method Description
poll()
This method is used to retrieve and remove
the element at the head of the deque. This
method returns null if the deque is empty.
pollFirst()
This method is used to retrieve and remove
the element at the head of the deque. This
method returns null if the deque is empty.
pollLast()
This method is used to retrieve and remove
the element at the tail of the deque. This
method returns null if the deque is empty.
METHODS OF DEQUEUE
140. Method Description
pop()
This method is used to remove an
element from the head and return
it.
push(element
)
This method is used to add an
element at the head of the queue.
removeFirst()
This method is used to remove an
element from the head of the
queue.
METHODS OF DEQUEUE
141. Method Description
removeLast(
)
This method is used to
remove an element from
the tail of the queue.
size()
This method is used to
find and return the size
of the deque.
METHODS OF DEQUEUE
142. Creating Deque Objects
• Since Deque is an interface, objects
cannot be created of the type deque
// Obj is the type of the object to be
stored in Deque
Deque<Obj> deque = new
ArrayDeque<Obj> ();
143. ADDING ELEMENTS
• In order to add an element in a deque,
we can use the add() method
• // Java program to demonstrate the
addition of elements in deque
import java.util.*;
public class ArrayDequeDemo {
public static void main(String[] args)
{
144. • // Initializing an deque
Deque<String> dq= new
ArrayDeque<String>();
145. import java.util.ArrayDeque;
import java.util.Deque;
public class Example {
public static void main(String[] args) {
Deque<Integer> deque = new ArrayDeque<>();
deque.addFirst(1);
deque.addLast(2);
int first = deque.removeFirst();
int last = deque.removeLast();
System.out.println("First: " + first + ", Last: " +
last);
}
147. • Java program to demonstrate the
working of a Deque in Java
148. import java.util.*;
public class DequeExample {
public static void main(String[] args)
{
Deque<String> deque= new
LinkedList<String>();
149. • // We can add elements to the
queue in various ways
• // Add at the last
deque.add("Element 1 (Tail)");
• // Add at the first
deque.addFirst("Element 2
(Head)");
• // Add at the last
deque.addLast("Element 3 (Tail)");
150. • // Add at the first
deque.push("Element 4 (Head)");
• // Add at the last
deque.offer("Element 5 (Tail)");
• // Add at the first
deque.offerFirst("Element 6
(Head)");
151. System.out.println(deque + "n");
• // We can remove the first element
or the last element.
deque.removeFirst();
deque.removeLast();
System.out.println("Deque after
removing "
+ "first and last: "+ deque);
}
}
153. JAVA TreeMap CLASS
• It provides an efficient means of storing
key-value pairs in sorted order.
• Java TreeMap contains values based on
the key.
• Java TreeMap contains only unique
elements
• Java TreeMap cannot have a null key but
can have multiple null values.
• Java TreeMap maintains ascending order
154. TreeMap CLASS PARAMETERS
• Let's see the Parameters for
java.util.TreeMap class.
–K: It is the type of keys maintained
by this map.
–V: It is the type of mapped values.
155. METHODS OF JAVA TreeMap
CLASS
Method Description
Map.Entry<
K,V>
It returns the key-value
pair
void clear() It removes all the key-
value pairs from a map.
Object
clone()
It returns a shallow copy
of TreeMap instance.
156. Method Description
comparator() It returns the comparator
that arranges the key in
order, or null if the map
uses the natural ordering.
descendingKeySet() It returns a reverse order
Set keySet() It returns the collection of
keys exist in the map.
METHODS OF JAVA TreeMap
CLASS
157. Method Description
replace(K key, V
value)
It replaces the specified
value for a specified key.
firstKey() It is used to return the first
(lowest) key currently in this
sorted map.
get(Object key) It is used to return the value
to which the map maps the
specified key.
METHODS OF JAVA TreeMap
CLASS
158. Method Description
lastKey() It is used to return the last
(highest) key currently in the
sorted map
remove(Object
key)
It removes the key-value pair
of the specified key from the
map.
int size() It returns the number of key-
value pairs exists in the
hashtable.
METHODS OF JAVA TreeMap
CLASS
172. //Maintains descending order
System.out.println("descendingMap: "+map.
descendingMap());
//Returns key-
value pairs whose keys are less than or equal t
o the specified key.
System.out.println("headMap: "+map.head
Map(102,true));
Java TreeMap Example:
NavigableMap
173. //Returns key-
value pairs whose keys are greater
than or equal to the specified key.
System.out.println("tailMap: "+ma
p.tailMap(102,true));
Java TreeMap Example:
NavigableMap
174. //Returns key-
value pairs exists in between the spe
cified key.
System.out.println("subMap: "+ma
p.subMap(100, false, 102, true));
}
}
Java TreeMap Example:
NavigableMap
177. ASSIGNMENT NO : 03 & 04
CONFIGURE JDBC DRIVER AND
EXECUTE PROGRAM FOR
INSERT,UPDATE,DELETE &
SELECT
178. WHAT ARE JDBC DRIVERS?
• JDBC drivers are Java library files with the
extension '.jar', used by Java applications
to connect to the database.
• Usually they are provided by the same
company which developed the database
software
• DbSchema is an Oracle Client which
already includes the Oracle JDBC driver
179. • DbSchema can configure the Oracle
JDBC URL and test the connectivity.
WHAT ARE JDBC DRIVERS?
180. WHAT IS THE JDBC URL?
• The URL is a string (text) with a
specific format containing
information about the host where
the database is running, the port,
username, database name, etc.
• The URL format is specific to each
driver
181. • Any wrong character in the URL
may make the database
connectivity fail
WHAT IS THE JDBC URL?
182. ORACLE JDBC DRIVER
• Required File(s): ojdbc15.jar (For Java
1.5), ojdbc16.jar (For Java 1.6)
• Java Driver Class:
oracle.jdbc.OracleDriver
• URL ( connect via SID ):
jdbc:oracle:thin:@HOST[:PORT]:DB
• URL ( connect via service name ):
jdbc:oracle:thin:@//HOST[:PORT]/DB
• Website: Oracle
183. • Download oracle JDBC Driver
https://dbschema.com/jdbc-
driver/Oracle.html
The driver files are compressed in a zip
file.
ORACLE JDBC DRIVER
184. Connect to Oracle using DbSchema
Client
• DbSchema is using JDBC Drivers to
connect to the database.
• DbSchema will build the JDBC URL
• Steps:
1. Download DbSchema DbSchema has a free
community edition. No email or registration
is required.
–https://dbschema.com/download.html
188. 3. At this point, DbSchema already
downloads the JDBC driver into this
folders:
C:UsersYourUser.DbSchemadrivers
Oracle (Windows) or
/Users/YourUser/.DbSchema/drivers/O
racle (Linux and MacOS).
Connect to Oracle using DbSchema
Client
189. • In the Connection Dialog, select the
driver and the JDBC URL template.
• For databases using multiple possibilities
to connect, may exists multiple
templates.
• Choose if the database is running on the
current machine or a different port.
• If is running on a different machine
(remote), you need to find the host
Connect to Oracle using DbSchema
Client
191. 4. Press the Ping button to test the
connectivity.
5. In the URL combo there is an option
to 'Manually Edit the URL'. Select this
option to see the generated JDBC
URL.
Connect to Oracle using DbSchema
Client
194. 1. Prerequisites
• To begin, make sure you have the following
pieces of software installed on your computer:
– JDK (download JDK 7).
– MySQL (download MySQL Community Server
5.6.12). You may also want to download MySQL
Workbench - a graphical tool for working with
MySQL databases.
– JDBC Driver for MySQL (download MySQL
Connector/J 5.1.25). Extract the zip archive and
put the mysql-connector-java-VERSION-bin.jar file into
classpath (in a same folder as your Java source
files).
196. main JDBC interfaces and classes
• They are all available under
the java.sql package
• DriverManager: this class is used to
register driver for a specific database
type (e.g. MySQL) and to establish a
database connection with the server
via its getConnection() method.
197. • Connection: this interface represents
an established database connection
(session) from which we can create
statements to execute queries and
retrieve results, get metadata about
the database, close connection, etc.
main JDBC interfaces and classes
198. Connecting to the database
• MySQL database server is listening
on the default port 3306 at localhost.
• String dbURL
= "jdbc:mysql://localhost:3306/samp
ledb";
• String username = "root";
• String password = “root";
199. try {
Connection conn =
DriverManager.getConnection(dbURL,
username, password);
if (conn != null) {
System.out.println("Connected");
}
}
Connecting to the database
209. RETRIEVE RECORDS
package TableDemo;
import java.sql.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class SelectRecord
210. {
static final String JDBC_DRIVER =
"com.mysql.jdbc.Driver";
static final String dburl =
"jdbc:mysql://localhost/STOREDB";
static final String dbuser = "root";
static final String dbpass = "root";
211. public static void main(String[] args)
{
Connection con = null;
Statement stmt = null;
try
{
212. //Step 1 : Connecting to server and
database
con =
DriverManager.getConnection(dburl,
dbuser, dbpass);
//Step 2 : Initialize Statement
stmt=con.createStatement();