SlideShare a Scribd company logo
1 of 216
Java Programming
• 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
INTRODUCTION TO JAVA
PROGRAMMING
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
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
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
JAVA Syntax
• Consider the example :
Main.java
public class Main { public static void
main(String[] args) { System.out.println("Hello
World"); } }
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.
• 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
• 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
• 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
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);
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.");
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);
Java Programming
The Collection Framework in Java
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
• Contains 3 fields used to return
entities.
–EMPTY_LIST
–EMPTY_SET
–EMPTY_MAP
Collection Class
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
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>
();
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
• LinkedList Methods :
addFirst()
addLast()
removeFirst()
removeLast()
getFirst()
getLast()
Linked List Classes
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
• 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
• 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
• 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
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
• 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
• 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.
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).
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
Assignment No - 01
Implement Collection Framework
Using Stack, ArrayList and Vector
Implement Collection Framework
Using Stack
Assignment No – 01(A)
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
JAVA STACK
• Let's push 20, 13, 89, 90, 11, 45, 18,
respectively into the stack.
JAVA STACK
• Let's remove (pop) 18, 45, and 11 from the
stack
JAVA STACK
• Empty Stack: If the stack has no element is
known as an empty stack. When the stack is
empty the value of the top variable is -1.
•
JAVA STACK
JAVA STACK
• 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
STACK CLASS CONSTRUCTOR
• The Stack class contains only the default
constructor that creates an empty stack.
public Stack()
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
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
StackEmptyMethodExample.java
Stack Class empty() Method
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);
}
}
• Output:
Is the stack empty? true
Elements in Stack: [78, 113, 90, 120]
Is the stack empty? false
StackEmptyMethodExample.java
StackPushPopExample.java
Stack Class push() Method
And
Stack Class pop() Method
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);
//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);
//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");
}
}
//performing push operation
static void pushelmnt(Stack stk, int x)
{
//invoking push() method
stk.push(new Integer(x));
System.out.println("push -> " + x);
//prints modified stack
System.out.println("stack: " + stk);
}
//performing pop operation
static void popelmnt(Stack stk)
{
System.out.print("pop -> ");
//invoking pop() method
Integer x = (Integer) stk.pop();
System.out.println(x);
//prints modified stack
System.out.println("stack: " + stk);
}
}
OUTPUT
stack: []
push -> 20
stack: [20]
push -> 13
stack: [20, 13]
push -> 89
stack: [20, 13, 89]
push -> 90
stack: [20, 13, 89, 90]
push -> 11
stack: [20, 13, 89, 90, 11]
push -> 45
stack: [20, 13, 89, 90, 11, 45]
push -> 18
stack: [20, 13, 89, 90, 11, 45, 18]
pop -> 18
stack: [20, 13, 89, 90, 11, 45]
pop -> 45
stack: [20, 13, 89, 90, 11]
pop -> 11
stack: [20, 13, 89, 90]
StackPeekMethodExample.java
Stack Class peek() Method
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);
// Access element from the top of the
stack
String fruits = stk.peek();
//prints stack
System.out.println("Element at top: "
+ fruits);
}
}
OUTPUT
Stack: [Apple, Grapes, Mango, Orange]
Element at the top of the stack:
Orange
StackSearchMethodExample.java
Stack Class search() Method
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);
}
}
SIZE OF THE STACK
StackSizeExample.java
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);
// 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);
}
}
OUTPUT
Is the stack empty or not? false
The stack size is: 5
ASSIGNMENT NO – 1 (C)
IMPLEMENT COLLECTION
FRAMEWORK USING
VECTOR
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.
• 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
• Vector is synchronized.
• Java Vector contains many legacy
methods that are not the part of a
collections framework.
JAVA VECTOR
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.
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
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
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
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
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
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
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
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
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
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
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
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
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
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
Method Description
trimToSize() It is used to trim the
capacity of the vector to
the vector's current size.
JAVA VECTOR METHODS
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>();
//Adding elements using add() method
of List
vec.add("Tiger");
vec.add("Lion");
vec.add("Dog");
vec.add("Elephant");
//Adding elements using addElement() met
hod of Vector
vec.addElement("Rat");
vec.addElement("Cat");
vec.addElement("Deer");
System.out.println("Elements are: "+v
ec);
}
}
OUTPUT
OUTPUT
Elements are: [Tiger, Lion, Dog,
Elephant, Rat, Cat, Deer]
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);
//Adding elements to a vector
vec.add("Tiger");
vec.add("Lion");
vec.add("Dog");
vec.add("Elephant");
//Check size and capacity
System.out.println("Size is: "+v
ec.size());
System.out.println("Defaul
t capacity is: "+vec.capacity());
//Display Vector elements
System.out.println("Vector element is:
"+vec);
vec.addElement("Rat");
vec.addElement("Cat");
vec.addElement("Deer");
//Again check size and capacity
System.out.println("Size after addit
ion: "+vec.size());
System.out.println("Capacity
after addition is: "+vec.capacity())
;
//Display Vector elements again
System.out.println("Elements ar
e: "+vec);
//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.");
//Get the first element
System.out.println("The first
animal of the vector is = "+vec.firs
tElement());
//Get the last element
System.out.println("The last a
nimal of the vector is = "+vec.last
Element());
}
}
OUTPUT
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
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<
>();
//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);
//Display the vector elements
System.out.println("Values i
n vector: " +in);
//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);
//Remove an element
in.removeElementAt(5);
//Checking vector and displays the
element
System.out.println("Vector ele
ment after removal: " +in);
//Get the hashcode for this v
ector
System.out.println("Has
h code of this vector = "+in.
hashCode());
//Get the element at specified ind
ex
System.out.println("Element a
t index 1 is = "+in.get(1));
}
}
OUTPUT
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
ASSIGNMENT : 02
IMPLEMENT COLLECTION
FRAMEWORK USING QUEUE,
DEQUEUE AND TREE MAP
IMPLEMENT COLLECTION
FRAMEWORK USING QUEUE
ASSIGNMENT : 02(A)
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.
• 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
• 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
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.
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
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) {
// Create and initialize a Queue
using a LinkedList
Queue<String> elementQueue =
new LinkedList<>();
QUEUE PROGRAM
• // 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
• // Removing an element from the
Queue using remove()
String name =
elementQueue.remove();
System.out.println("Removed from
WaitingQueue : " + name + " | New
WaitingQueue : " + elementQueue);
QUEUE PROGRAM
• // Removing an element from the
Queue using poll()
name = elementQueue.poll();
System.out.println("Removed from
WaitingQueue : " + name + " | New
WaitingQueue : " + elementQueue);
}
}
QUEUE PROGRAM
OUTPUT
WaitingQueue : [element1, element2,
element3, element4]
Removed from WaitingQueue : element1 |
New WaitingQueue : [element2,
element3, element4]
Removed from WaitingQueue : element2 |
New WaitingQueue : [element3,
element4]
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<>();
elementQueue.add("element1");
elementQueue.add("element2");
elementQueue.add("element3");
elementQueue.add("element4");
System.out.println("WaitingQueue : "
+ elementQueue);
Queue Interface Methods - isEmpty(),
size(), element(), peek()
• // 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()
• // 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()
// 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()
• // 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()
OUTPUT
WaitingQueue : [element1, element2,
element3, element4]
is waitingQueue empty? : false
Size of waitingQueue : 4
Waiting Queue doesn't contain Johnny
Waiting Queue (element()) : element1
Waiting Queue : element1
ASSIGNMENT : 02(B)
IMPLEMENT COLLECTION
FRAMEWORK USING DEQUEUE
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
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
• 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
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
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
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
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
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
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
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
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
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> ();
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)
{
• // Initializing an deque
Deque<String> dq= new
ArrayDeque<String>();
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);
}
OUTPUT
First: 1, Last: 2
• Java program to demonstrate the
working of a Deque in Java
import java.util.*;
public class DequeExample {
public static void main(String[] args)
{
Deque<String> deque= new
LinkedList<String>();
• // 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)");
• // 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)");
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);
}
}
IMPLEMENT COLLECTION
FRAMEWORK USING TREEMAP
ASSIGNMENT : 02(C)
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
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.
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.
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
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
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
JAVA TreeMap
EXAMPLE
JAVA TreeMap EXAMPLE
import java.util.*;
class TreeMap1{
public static void main(String args[]){
TreeMap<Integer,String> map=new TreeMap
<Integer,String>();
map.put(100,"Amit");
map.put(102,"Ravi");
map.put(101,"Vijay");
map.put(103,"Rahul");
for(Map.Entry m:map.entrySet()){
System.out.println(m.getKey()+" "
+m.getValue());
}
}
}
JAVA TreeMap EXAMPLE
OUTPUT
100 Amit
101 Vijay
102 Ravi
103 Rahul
OUTPUT
Java TreeMap
Example: remove()
Java TreeMap Example: remove()
import java.util.*;
public class TreeMap2 {
public static void main(String args[]) {
TreeMap<Integer,String> map=new TreeMap<In
teger,String>();
map.put(100,"Amit");
map.put(102,"Ravi");
map.put(101,"Vijay");
map.put(103,"Rahul");
System.out.println("Before invoking re
move() method");
for(Map.Entry m:map.entrySet())
{
System.out.println(m.getKey()+"
"+m.getValue());
}
Java TreeMap Example: remove()
map.remove(102);
System.out.println("After invoking remove() met
hod");
for(Map.Entry m:map.entrySet())
{
System.out.println(m.getKey()+" "+m.getV
alue());
}
}
}
Java TreeMap Example: remove()
OUTPUT
• Before invoking remove() method
• 100 Amit
• 101 Vijay
• 102 Ravi
• 103 Rahul
• After invoking remove() method
• 100 Amit
• 101 Vijay
• 103 Rahul
Java TreeMap Example: remove()
Java TreeMap
Example:
NavigableMap
Java TreeMap Example:
NavigableMap
import java.util.*;
class TreeMap3{
public static void main(String args[]){
NavigableMap<Integer,String> map=new TreeM
ap<Integer,String>();
map.put(100,"Amit");
map.put(102,"Ravi");
map.put(101,"Vijay");
map.put(103,"Rahul");
//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
//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
//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
OUTPUT
descendingMap: {103=Rahul,
102=Ravi, 101=Vijay, 100=Amit}
headMap: {100=Amit, 101=Vijay,
102=Ravi}
tailMap: {102=Ravi, 103=Rahul}
subMap: {101=Vijay, 102=Ravi}
OUTPUT
ASSIGNMENT NO : 03 & 04
CONFIGURE JDBC DRIVER AND
EXECUTE PROGRAM FOR
INSERT,UPDATE,DELETE &
SELECT
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
• DbSchema can configure the Oracle
JDBC URL and test the connectivity.
WHAT ARE JDBC DRIVERS?
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
• Any wrong character in the URL
may make the database
connectivity fail
WHAT IS THE JDBC URL?
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
• Download oracle JDBC Driver
https://dbschema.com/jdbc-
driver/Oracle.html
The driver files are compressed in a zip
file.
ORACLE JDBC DRIVER
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
Connect to Oracle using DbSchema
Client
2. Choose to connect to the database,
and choose Oracle.
Connect to Oracle using DbSchema
Client
Connect to Oracle using DbSchema
Client
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
• 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
Connect to Oracle using DbSchema
Client
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
Connect to Oracle using DbSchema
Client
OR
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).
1. Prerequisites
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.
• 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
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";
try {
Connection conn =
DriverManager.getConnection(dbURL,
username, password);
if (conn != null) {
System.out.println("Connected");
}
}
Connecting to the database
catch (SQLException ex)
{
ex.printStackTrace();
}
Connecting to the database
PROGRAM
package TableDemo;
import java.sql.*;
public class InsertRecord
{
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";
public static void main(String[] args)
{
Connection con = null;
Statement stmt = null;
try
{
//Step 1 : Connecting to server and
database
con =
DriverManager.getConnection(dburl,
dbuser, dbpass);
//Step 2 : Initialize Statement
stmt=con.createStatement();
//Step 3 : SQL Query
String query="INSERT INTO
ITEM(PRICE,PRODUCT)
VALUES(190,'MousePad')";
String query1="INSERT INTO
ITEM(PRICE,PRODUCT)
VALUES(2870,'Stationary')";
String query2="INSERT INTO
ITEM(PRICE,PRODUCT)
VALUES(765,'Books')";
String query3="INSERT INTO
ITEM(PRICE,PRODUCT)
VALUES(3887,'HardDisk')";
//Step 4 : Run Query
stmt.executeUpdate(query);
stmt.executeUpdate(query1);
stmt.executeUpdate(query2);
stmt.executeUpdate(query3);
System.out.println("Record Inserted
Successfully");
}
catch (SQLException e)
{
System.err.println("Cannot connect
! ");
e.printStackTrace();
}
finally {
System.out.println("Closing the connection.");
if (con != null)
try
{
con.close();
}
catch (SQLException ignore) {}
}
}
}
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
{
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";
public static void main(String[] args)
{
Connection con = null;
Statement stmt = null;
try
{
//Step 1 : Connecting to server and
database
con =
DriverManager.getConnection(dburl,
dbuser, dbpass);
//Step 2 : Initialize Statement
stmt=con.createStatement();
//Step 3 : SQL Query
String query="SELECT * FROM ITEM";
//Step 4 : Run Query In ResultSet
ResultSet rset = stmt.executeQuery(query);
while(rset.next())
{
System.out.print("ID: " + rset.getInt(1));
System.out.print(" Product :
"+rset.getString(2));
System.out.println(" Price :
"+rset.getString(3));
}
}
catch (SQLException e)
{
System.err.println("Cannot connect !
"); e.printStackTrace();
}
finally {
System.out.println("Closing the
connection.");
if (con != null) try { con.close(); }
catch (SQLException ignore) {}
}
}
}

More Related Content

Similar to Java Programming Comprehensive Guide.pptx

Collections lecture 35 40
Collections lecture 35 40Collections lecture 35 40
Collections lecture 35 40bhawna sharma
 
Week10 packages using objects in objects
Week10 packages using objects in objectsWeek10 packages using objects in objects
Week10 packages using objects in objectskjkleindorfer
 
Standard Template Library
Standard Template LibraryStandard Template Library
Standard Template LibraryGauravPatil318
 
Week_2_Lec_6-10_with_watermarking_(1).pdf
Week_2_Lec_6-10_with_watermarking_(1).pdfWeek_2_Lec_6-10_with_watermarking_(1).pdf
Week_2_Lec_6-10_with_watermarking_(1).pdfPrabhaK22
 
Java Unit 2 (Part 2)
Java Unit 2 (Part 2)Java Unit 2 (Part 2)
Java Unit 2 (Part 2)SURBHI SAROHA
 
java02.ppt
java02.pptjava02.ppt
java02.pptMENACE4
 
lecture-a-java-review.ppt
lecture-a-java-review.pptlecture-a-java-review.ppt
lecture-a-java-review.pptkavitamittal18
 
Java basics with datatypes, object oriented programming
Java basics with datatypes, object oriented programmingJava basics with datatypes, object oriented programming
Java basics with datatypes, object oriented programmingkalirajonline
 
lecture-a-java-review.ppt
lecture-a-java-review.pptlecture-a-java-review.ppt
lecture-a-java-review.pptNadiSarj2
 
lecture-a-java-review.ppt
lecture-a-java-review.pptlecture-a-java-review.ppt
lecture-a-java-review.pptJemarManatad1
 
lecture-a-java-review.ppt
lecture-a-java-review.pptlecture-a-java-review.ppt
lecture-a-java-review.pptSquidTurbo
 
Collection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshanCollection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshanZeeshan Khan
 

Similar to Java Programming Comprehensive Guide.pptx (20)

Collections lecture 35 40
Collections lecture 35 40Collections lecture 35 40
Collections lecture 35 40
 
Week10 packages using objects in objects
Week10 packages using objects in objectsWeek10 packages using objects in objects
Week10 packages using objects in objects
 
Standard Template Library
Standard Template LibraryStandard Template Library
Standard Template Library
 
Java Collections
Java  Collections Java  Collections
Java Collections
 
Week_2_Lec_6-10_with_watermarking_(1).pdf
Week_2_Lec_6-10_with_watermarking_(1).pdfWeek_2_Lec_6-10_with_watermarking_(1).pdf
Week_2_Lec_6-10_with_watermarking_(1).pdf
 
LectureNotes-06-DSA
LectureNotes-06-DSALectureNotes-06-DSA
LectureNotes-06-DSA
 
Java Unit 2 (Part 2)
Java Unit 2 (Part 2)Java Unit 2 (Part 2)
Java Unit 2 (Part 2)
 
java02.ppt
java02.pptjava02.ppt
java02.ppt
 
lecture-a-java-review.ppt
lecture-a-java-review.pptlecture-a-java-review.ppt
lecture-a-java-review.ppt
 
lecture-a-java-review.ppt
lecture-a-java-review.pptlecture-a-java-review.ppt
lecture-a-java-review.ppt
 
lecture-a-java-review.ppt
lecture-a-java-review.pptlecture-a-java-review.ppt
lecture-a-java-review.ppt
 
Java basics with datatypes, object oriented programming
Java basics with datatypes, object oriented programmingJava basics with datatypes, object oriented programming
Java basics with datatypes, object oriented programming
 
lecture-a-java-review.ppt
lecture-a-java-review.pptlecture-a-java-review.ppt
lecture-a-java-review.ppt
 
lecture-a-java-review.ppt
lecture-a-java-review.pptlecture-a-java-review.ppt
lecture-a-java-review.ppt
 
lecture-a-java-review.ppt
lecture-a-java-review.pptlecture-a-java-review.ppt
lecture-a-java-review.ppt
 
Collections framework in java
Collections framework in javaCollections framework in java
Collections framework in java
 
STACK.pptx
STACK.pptxSTACK.pptx
STACK.pptx
 
Collection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshanCollection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshan
 
Java Collections Tutorials
Java Collections TutorialsJava Collections Tutorials
Java Collections Tutorials
 
Lecture 9
Lecture 9Lecture 9
Lecture 9
 

Recently uploaded

CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordAsst.prof M.Gokilavani
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escortsranjana rawat
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxupamatechverse
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escortsranjana rawat
 
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).pptssuser5c9d4b1
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...ranjana rawat
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdfankushspencer015
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Dr.Costas Sachpazis
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...ranjana rawat
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)Suman Mia
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...ranjana rawat
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxpurnimasatapathy1234
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlysanyuktamishra911
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxupamatechverse
 

Recently uploaded (20)

CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptx
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
 
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
 
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
 
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINEDJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptx
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptx
 

Java Programming Comprehensive Guide.pptx

  • 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);
  • 15. Java Programming The Collection Framework in Java
  • 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
  • 21. • LinkedList Methods : addFirst() addLast() removeFirst() removeLast() getFirst() getLast() Linked List Classes
  • 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
  • 32. Implement Collection Framework Using Stack Assignment No – 01(A)
  • 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
  • 35. • Let's push 20, 13, 89, 90, 11, 45, 18, respectively into the stack. JAVA STACK
  • 36. • Let's remove (pop) 18, 45, and 11 from the stack JAVA STACK
  • 37. • Empty Stack: If the stack has no element is known as an empty stack. When the stack is empty the value of the top variable is -1. • JAVA 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
  • 46. StackPushPopExample.java Stack Class push() Method And Stack Class pop() Method
  • 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"); } }
  • 50. //performing push operation static void pushelmnt(Stack stk, int x) { //invoking push() method stk.push(new Integer(x)); System.out.println("push -> " + x); //prints modified stack System.out.println("stack: " + stk); }
  • 51. //performing pop operation static void popelmnt(Stack stk) { System.out.print("pop -> "); //invoking pop() method Integer x = (Integer) stk.pop(); System.out.println(x); //prints modified stack System.out.println("stack: " + stk); } }
  • 53. stack: [] push -> 20 stack: [20] push -> 13 stack: [20, 13] push -> 89 stack: [20, 13, 89] push -> 90 stack: [20, 13, 89, 90] push -> 11 stack: [20, 13, 89, 90, 11] push -> 45 stack: [20, 13, 89, 90, 11, 45] push -> 18 stack: [20, 13, 89, 90, 11, 45, 18] pop -> 18 stack: [20, 13, 89, 90, 11, 45] pop -> 45 stack: [20, 13, 89, 90, 11] pop -> 11 stack: [20, 13, 89, 90]
  • 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); } }
  • 57. OUTPUT Stack: [Apple, Grapes, Mango, Orange] Element at the top of the stack: Orange
  • 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); } }
  • 60. SIZE OF THE STACK StackSizeExample.java
  • 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); } }
  • 63. OUTPUT Is the stack empty or not? false The stack size is: 5
  • 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
  • 83. Method Description trimToSize() It is used to trim the capacity of the vector to the vector's current size. 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); } }
  • 88. OUTPUT Elements are: [Tiger, Lion, Dog, Elephant, Rat, Cat, Deer]
  • 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());
  • 92. //Display Vector elements System.out.println("Vector element is: "+vec); vec.addElement("Rat"); vec.addElement("Cat"); vec.addElement("Deer");
  • 93. //Again check size and capacity System.out.println("Size after addit ion: "+vec.size()); System.out.println("Capacity after addition is: "+vec.capacity()) ;
  • 94. //Display Vector elements again System.out.println("Elements ar e: "+vec);
  • 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);
  • 102. //Display the vector elements System.out.println("Values i n vector: " +in);
  • 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);
  • 105. //Checking vector and displays the element System.out.println("Vector ele ment after removal: " +in);
  • 106. //Get the hashcode for this v ector System.out.println("Has h code of this vector = "+in. hashCode());
  • 107. //Get the element at specified ind ex System.out.println("Element a t index 1 is = "+in.get(1)); } }
  • 108. OUTPUT
  • 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
  • 110. ASSIGNMENT : 02 IMPLEMENT COLLECTION FRAMEWORK USING QUEUE, DEQUEUE AND TREE MAP
  • 111. IMPLEMENT COLLECTION FRAMEWORK USING QUEUE ASSIGNMENT : 02(A)
  • 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()
  • 129. OUTPUT WaitingQueue : [element1, element2, element3, element4] is waitingQueue empty? : false Size of waitingQueue : 4 Waiting Queue doesn't contain Johnny Waiting Queue (element()) : element1 Waiting Queue : element1
  • 130. ASSIGNMENT : 02(B) IMPLEMENT COLLECTION FRAMEWORK USING DEQUEUE
  • 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); } }
  • 152. IMPLEMENT COLLECTION FRAMEWORK USING TREEMAP ASSIGNMENT : 02(C)
  • 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
  • 160. JAVA TreeMap EXAMPLE import java.util.*; class TreeMap1{ public static void main(String args[]){ TreeMap<Integer,String> map=new TreeMap <Integer,String>(); map.put(100,"Amit"); map.put(102,"Ravi"); map.put(101,"Vijay"); map.put(103,"Rahul");
  • 162. OUTPUT
  • 163. 100 Amit 101 Vijay 102 Ravi 103 Rahul OUTPUT
  • 165. Java TreeMap Example: remove() import java.util.*; public class TreeMap2 { public static void main(String args[]) { TreeMap<Integer,String> map=new TreeMap<In teger,String>(); map.put(100,"Amit"); map.put(102,"Ravi"); map.put(101,"Vijay"); map.put(103,"Rahul");
  • 166. System.out.println("Before invoking re move() method"); for(Map.Entry m:map.entrySet()) { System.out.println(m.getKey()+" "+m.getValue()); } Java TreeMap Example: remove()
  • 167. map.remove(102); System.out.println("After invoking remove() met hod"); for(Map.Entry m:map.entrySet()) { System.out.println(m.getKey()+" "+m.getV alue()); } } } Java TreeMap Example: remove()
  • 168. OUTPUT
  • 169. • Before invoking remove() method • 100 Amit • 101 Vijay • 102 Ravi • 103 Rahul • After invoking remove() method • 100 Amit • 101 Vijay • 103 Rahul Java TreeMap Example: remove()
  • 171. Java TreeMap Example: NavigableMap import java.util.*; class TreeMap3{ public static void main(String args[]){ NavigableMap<Integer,String> map=new TreeM ap<Integer,String>(); map.put(100,"Amit"); map.put(102,"Ravi"); map.put(101,"Vijay"); map.put(103,"Rahul");
  • 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
  • 175. OUTPUT
  • 176. descendingMap: {103=Rahul, 102=Ravi, 101=Vijay, 100=Amit} headMap: {100=Amit, 101=Vijay, 102=Ravi} tailMap: {102=Ravi, 103=Rahul} subMap: {101=Vijay, 102=Ravi} OUTPUT
  • 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
  • 185. Connect to Oracle using DbSchema Client
  • 186. 2. Choose to connect to the database, and choose Oracle. Connect to Oracle using DbSchema Client
  • 187. Connect to Oracle using DbSchema Client
  • 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
  • 190. 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
  • 192. Connect to Oracle using DbSchema Client
  • 193. OR
  • 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
  • 201. PROGRAM package TableDemo; import java.sql.*; public class InsertRecord { static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; static final String dburl = "jdbc:mysql://localhost/STOREDB";
  • 202. static final String dbuser = "root"; static final String dbpass = "root"; public static void main(String[] args) { Connection con = null; Statement stmt = null;
  • 203. try { //Step 1 : Connecting to server and database con = DriverManager.getConnection(dburl, dbuser, dbpass);
  • 204. //Step 2 : Initialize Statement stmt=con.createStatement(); //Step 3 : SQL Query String query="INSERT INTO ITEM(PRICE,PRODUCT) VALUES(190,'MousePad')";
  • 205. String query1="INSERT INTO ITEM(PRICE,PRODUCT) VALUES(2870,'Stationary')"; String query2="INSERT INTO ITEM(PRICE,PRODUCT) VALUES(765,'Books')"; String query3="INSERT INTO ITEM(PRICE,PRODUCT) VALUES(3887,'HardDisk')";
  • 206. //Step 4 : Run Query stmt.executeUpdate(query); stmt.executeUpdate(query1); stmt.executeUpdate(query2); stmt.executeUpdate(query3); System.out.println("Record Inserted Successfully"); }
  • 207. catch (SQLException e) { System.err.println("Cannot connect ! "); e.printStackTrace(); }
  • 208. finally { System.out.println("Closing the connection."); if (con != null) try { con.close(); } catch (SQLException ignore) {} } } }
  • 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();
  • 213. //Step 3 : SQL Query String query="SELECT * FROM ITEM";
  • 214. //Step 4 : Run Query In ResultSet ResultSet rset = stmt.executeQuery(query); while(rset.next()) { System.out.print("ID: " + rset.getInt(1)); System.out.print(" Product : "+rset.getString(2)); System.out.println(" Price : "+rset.getString(3));
  • 215. } } catch (SQLException e) { System.err.println("Cannot connect ! "); e.printStackTrace(); }
  • 216. finally { System.out.println("Closing the connection."); if (con != null) try { con.close(); } catch (SQLException ignore) {} } } }