MainMenu

Home Java Overview Maven Tutorials

Monday 29 April 2019

JDBC in Java

JDBC in java



JDBC Introducton
JDBC stands for Java Database connectivity
The Java JDBC API enables Java applications to connect to relational database via standard API, so your Java applications become independent of the database the application uses.

Java application using JDBC to connect to a database.
JDBC standardizes how to connect to a database, how to execute queries against it, how to navigate the result of such a query, and how to execute updates in the database. JDBC does not standardize the SQL sent to the database. This may still vary from database to database.

The JDBC library includes APIs for each of the tasks mentioned below that are commonly associated with database usage.
1). Making a connection to a database.
2). Creating SQL or MySQL statements.
3). Executing SQL or MySQL queries in the database.
4). Viewing & modifying the resulting records.

JDBC Overview
1). Core JDBC Components.
2). Common JDBC use cases.
3). A JDBC Component Interaction Diagram.

The JDBC API consists of the following core parts :-
1). JDBC Drivers
2). Connections
3). Statements
4). Result Sets

There are four basic JDBC use cases around which most JDBC work evolves :-
1). Query the database(read data from it).
One of the most common use cases is to read data from a database. Reading data from a database is called querying the database.
2). Query the database meta data.
Another common use case is to query the database meta data. The database meta data contains information about the database itself. For instance, information about the tables defines, the column in each table, the data type etc.
3). Update the database.
Another very commong JDBC use case is to update the database. Updating the database means writing data to it. In other words, adding new records or modifying(updating) exiting records.
4). Perform transactions.

Transaction is another common use case. An transaction groups multiple updates and possible queries into a single action. Either all of the actions are executed, or none of them are.

Core JDBC Components
JDBC Driver
A JDBC driver is a collection of Java classes that enables you to connect to a certain database. For instance, MySQL will have its own JDBC driver. A JDBC driver implements a lot of JDBC interfaces. When your code uses a given JDBC driver, it actually just uses the standard JDBC interfaces. The concrete JDBC driver used in hidden behind the JDBC interfaces. Thus you can plugin a new JDBC driver without your code noticing it.
Of course, the JDBC drivers may vary a little in the features they support.

Connection
Once a JDBC driver is loaded and initialized, you need to connect to the database. You do so by obtaining a connection to the database via the JDBC API and the loaded driver. All Communication with the database happens via a connection.
An Application can have more than one connection open to a database at a time. This is actually very common when you have web application.
Statement
A statement is what you use to execte queries and updates against the database. There are a few different types of statements you can use in JDBC.
ResultSet
When you perform a query against the database you get back a ResultSet. You can then traverse this ResultSet to read the result of the query.
What is JDBC Driver in JAVA ?
A driver is nothing but software required to connect to a database from java program. JDBC is just an API, which java has designed and to implementation of these APIs lies on different vendor because different database works in a different way, they internally use different protocols.

So mySQL gives its own implementation of JDBC, we call it MySQL JDBC driver and we use it when we want to cennect to MySQL database from Java Program.
Similarly Oracle, SQL Server, Sybase and postgreSQL have provided their own implementation of JDBC API to connect them.
Since Java Program uses JDBC API, they are portable across different database, all you need to do is change the JDBC driver, which is just a JAR file if you are using type 4 JDBC driver.

Type of JDBC Driver :- There are four types of JDBC drivers :- 1). JDBC-ODBC Bride Driver
2). JDBC-Native Driver
3). JDBC-Net pure Java or Network Protocol driver
4). All Java driver or Thin driver

Why many types of JDBC Drivers
The different types of JDBC driver comes from the fact how they work, which is basically driven by two factors, portability and performance. Type 1 JDBC driver is the poorest in terms of portability and performance while type 4 JDBC drivers are highly portable and gives the best performance.
Since the database is very important and almost all java application uses the database is some form or other, it's important to learn JDBC well.

What is type 1 driver in JDBC?
This is the oldest JDBC driver, mostly used to connect databaase like MS Access from Microsoft Windows operation System. Type 1 JDBC driver actually translate JDBC calls into ODBC(Object Database connectivity) calls, which in turn connects to the database. Since it acts as bridge between JDBC and ODBC, it is also know as JDBC ODBC bridge driver. This driver had very poor performance because of several layers of translation which took place before your program connects to database. It has also less portable because it relies on ODBC driver to connect to database which is platform dependent, It is now obsolete and ubly used for developmenet and testing, Java 8 even removed this driver from JDK.

What is type 2 driver in JDBC?
This was the second JDBC driver introduced by Java after Type 1, hence it known as type 2. In this driver, performance was improved by reducing communication layer. Instead of talking of ODBC driver, JDBC driver directly talks to DB client using native API. That's why it's also known as native API or partly Java driver. Since it required native API to connect to DB client it is also less portable and platform dependent. Performance of type 2 driver is slightly better than type 1 JDBC driver.
What is type 3 driver in JDBC?
This was the third JDBC driver introduced by Java, hence known as type 3. It was very different than type 1 and type 2 JDBC driver in sense that it was completely written in JAVA as opposed to previous two drivers which were not written in Java. That's why this is also knwon as all Java drivers. This driver uses 3 tier approach i.e. client, server and database. So you have a Java Client talking to a java server and Java Server talking to database. Java client and server talk to each other usiing net protocol hence this type of JDBC driver is also known as Net protocol JDBC driver. This driver never gained popularity because database vender was reluctant to rewrite their existing natve library which was mainly in C and C++.

What is type 4 driver in JDBC?
This is the driver you are most likely using to connect to modern database like Oracle, SQL Server, MySQL, SQLLite and postgreSQl etc. This driver is implemented in Java and directly talks to database using its native protocol. This driver includes all database call in one JAR file, which makes it very easy easy to use. All you need to do to connect a database from java program is to include JAR file of relevant JDBC driver, because of light weight this is also known as Thin JDBC driver. Since this driver is also written in pure Java, It's portable across all platforms, which means you can use same JAR file to connect to MySQL even if your Java program is running on Windows, Linux or Solaris.
Performance of this type of JDBC driver is also best among all of them because database vendor liked this type and all enhancement they make thay also port for type 4 drivers.


Thursday 11 April 2019

MultiThreading in java

MultiThreading in java







Multitasking and Multithreading


1). Multitasking refers to a computer's ability to perform multiple jobs concurrently. For Example :- more than one program are running concurrently.
2).A Thread is a single sequence of execution within a program.
MultiThreading in java is a process of executing multiple threads simultaneously.
Multithreading refers to multiple threads of control with in a single program.
Each program can run multiple threads of control within it.

A Thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing and multithreading both are used to acheive multitasking.
Threads use a shared memory area but processes are not.
A thread is a lightweight subprocess, the smallest unit of processing. It is a separate path of execution.
Threads are independent. If there occurs exception in one thread, it doesn't affect other threads. It uses a shared memory area.
Java Multithreading is mostly used in games, animation etc.



For Example : Web browser is a program and its tabs are single thread.

Process :- An execution instance of a program is called a process. A thread is a subset of the process.


Advantage of Thread

1). To maintain responsiveness of an application during a long running task.
2).To enable cancellation of separable tasks.
3).Some problems are intrinsically parallel.
4).To monitor status of some resource (DB)
5). Some APIs and Systems demand it : Swing.

Advantages of Java Multithreading

1) It doesn't block the user because threads are independent and you can perform multiple operations at the same time.
2) You can perform many operations together, so it saves time.
3) Threads are independent, so it doesn't affect other threads if an exception occurs in a single thread.

Application Thread

When we execute an application :-
The JVM creates a Thread object whose task is defined by the main() method.
It Starts the thread.
The thread executes the statements of the program one by one until the method returns and the thread dies.


Multiple Threads in an Application

Each thread has its private run-time stack
if two threads execute the same method, each will have its own copy of the local variables the methods uses.
However, all the threads see the same dynamic memory(heap)
Two different threads can act on the same object and same static fields concurrently.

Creating Thread

There are two ways to create our own Thread Object
1). By Extending Thread class OR Subclassing the Thread class and instantiating a new object of that class.
2). Implementing the Runnable interface.
In both the case the run() method should be implemented.

Life Cycle of a Thread

New Thread :- When a new thread is created, it is in new state. The thread has not yet started to run when thread is in this state.
Runnable State :- A thread that is ready to run is moved to runnable state. In this state, a thread might actually be running or int might be ready run at any instant of time. It is the responsibility of the thread scheduler to give the thread, time to run.
A multi-threaded program allocates a fixed amount of time to each individual thread.
Blocked/Waiting state: When a thread is temporarily inactive, then it’s in one of the following states:
Blocked
Waiting
For example, when a thread is waiting for I/O to complete, it lies in the blocked state. It’s the responsibility of the thread scheduler to reactivate and schedule a blocked/waiting thread. A thread in this state cannot continue its execution any further until it is moved to runnable state. Any thread in these states do not consume any CPU cycle.
A thread is in the blocked state when it tries to access a protected section of code that is currently locked by some other thread. When the protected section is unlocked, the schedule picks one of the thread which is blocked for that section and moves it to the runnable state.
Time waitingA thread lies in timed waiting state when it calls a method with a time out parameter. A thread lies in this state until the timeout is completed or until a notification is received.
Terminated State: A thread terminates because of either of the following reasons:
Because it exists normally. This happens when the code of thread has entirely executed by the program.
Because there occurred some unusual erroneous event, like segmentation fault or an unhandled exception.
A thread that lies in terminated state does no longer consumes any cycles of CPU.


------------------------------------------------------------------------------------------------------

Example of Thread :- extends Thread



import java.util.*;
class A extends Thread
{
public void run()
{
Scanner scn = new Scanner(System.in);
System.out.println("Enter your name");
String name = scn.nextLine();
System.out.println("Enter your surname");
String sname = scn.nextLine();
System.out.println("Your full Name is " + " " + name + " " + sname +" " + Thread.currentThread()) ;
}
}
public class ConsTest
{
public static void main(String args[])
{
A obj = new A();
obj.start();
}
}

Output :-
Enter your name
way2testing
Enter your surname
singh
Your full Name is way2testing singh Thread[Thread-0,5,main]

--------------------------------------------------------------------------------------------------------

Example of Thread :- implements Runnable



package com.lang.beginner; class A
{
public void test()
{
System.out.println("i am inside A class");
}
}
class B extends A implements Runnable
{
public void run()
{
Scanner scn = new Scanner(System.in);
System.out.println("Enter your name");
String name = scn.nextLine();
System.out.println("Enter your surname");
String sname = scn.nextLine();
System.out.println("Your full Name is " + " " + name + " " + sname +" " + Thread.currentThread()) ;
}
}
public class ConsTest
{
public static void main(String args[])
{
B obj = new B();
obj.test();
Thread th = new Thread(obj);
th.start();
}
}

Output :-
i am inside A class
Enter your name
way2testing
Enter your surname
.com
Your full Name is way2testing .com Thread[Thread-0,5,main]

---------------------------------------------------------------------------------------------------------

Example of Thread Synchronization


package com.lang.beginner;

import java.util.*;
class A implements Runnable
{
synchronized public void run()
{
Scanner scn = new Scanner(System.in);
System.out.println("Enter your name");
String name = scn.nextLine();
System.out.println("Enter your surname");
String sname = scn.nextLine();
System.out.println("Your full Name is " + " " + name + " " + sname +" " + Thread.currentThread()) ;
}
}
public class ConsTest
{
public static void main(String args[])
{
A obj = new A();
Thread th = new Thread(obj);
th.start();
A obj2 = new A();
Thread th2 = new Thread(obj);
th2.start();
}
}

Output :-
Enter your name
csc
Enter your surname
baji
Your full Name is csc baji Thread[Thread-0,5,main]
Enter your name
adhi
Enter your surname
raaj
Your full Name is adhi raaj Thread[Thread-1,5,main]

------------------------------------------------------------------------------------------------------------------

Example of Thread :-


package com.lang.Pages;
import org.testng.annotations.Test;

class parent
{
public void k()
{
System.out.println("i am inside parent class");
}
}
class test extends parent implements Runnable
{
public void run()
{
for(int i = 0; i<5; i++)
{
System.out.println("This is CSC" + " " + i);
}
}
public void run(int x)
{
for(int i = 0; i<x; i++)
{
System.out.println("This is run 2 CSC" + " " + i);
}
}
}
class test2 extends Thread
{
public void run()
{
for(int i = 0; i<5; i++)
{
System.out.println("This is way2testing" + " " + i);
}
}
}
public class ThreadPractice
{
@Test
public void k()
{
test obj = new test();
Thread td = new Thread(obj);
td.start();
test obj2 = new test();
obj2.run(7);
for(int i = 0; i<5; i++)
{
System.out.println("This is way2shayari" + " " + i);
}
test2 obj3 = new test2();
obj3.start();
}
@Test
public void l()
{
Thread t1 = new Thread(new Runnable()
{public void run()
{
for(int i = 0; i<5; i++)
{
System.out.println("i am thread 1 in same class");
}
}
}
);
Thread t2 = new Thread(new Runnable()
{public void run()
{
for(int i = 0; i<5; i++)
{
System.out.println("i am thread 2 in same class");
}
}
}
);
t1.start();
t2.start();
}
}
---------------------------------------------------------------------------------- Example of Threads

import java.util.Scanner;
class A implements Runnable
{
synchronized public void run()
{
for(int i = 1; i<11; i++)
{
System.out.println(i +" " +Thread.currentThread());
}
}
}
public class Oopstutorial
{
public static void main(String[] args)
{
A obj = new A();
Thread t1 = new Thread(obj);
Thread t2 = new Thread(obj);
t1.start();
t2.start();
}
}

Output :-
1 Thread[Thread-0,5,main]
2 Thread[Thread-0,5,main]
3 Thread[Thread-0,5,main]
4 Thread[Thread-0,5,main]
5 Thread[Thread-0,5,main]
6 Thread[Thread-0,5,main]
7 Thread[Thread-0,5,main]
8 Thread[Thread-0,5,main]
9 Thread[Thread-0,5,main]
10 Thread[Thread-0,5,main]
1 Thread[Thread-1,5,main]
2 Thread[Thread-1,5,main]
3 Thread[Thread-1,5,main]
4 Thread[Thread-1,5,main]
5 Thread[Thread-1,5,main]
6 Thread[Thread-1,5,main]
7 Thread[Thread-1,5,main]
8 Thread[Thread-1,5,main]
9 Thread[Thread-1,5,main]
10 Thread[Thread-1,5,main]

Dictionary and serialization in Java with Example

Dictionary and serialization in Java




Dictionary:- Dictionary is an abstract class that represents a key/value storage repository and operates much like Map.
With dictionaries, we can

1). INSERT
2). FIND
3). DELETE

public class DisctionaryPractice
{
public static void main(Striing[] args)
{
Map<String, String> stardictionary = new HashMap<String, String>();
stardictionary.put("Julia", "America");
stardictionary.put("Nicole", "USA");
stardictionary.put("Kiera", "UK");
stardictionary.put("Anne", "new york");
}
System.out.println(stardictionary.get("Julia"));
System.out.println(stardictionary.toString());
System.out.println(stardictionary.keySet());
System.out.println(stardictionary.values());
}

Serialization in Java



Serialization in java is a mechanism of writing the state of an object into a byte stream.
In other Word
Serialization is a mechanism of convertion the state of an object into a byte stream.
The reverse operation of serialization is called deserialization.
In other Word
Deserialization is the reverse process where the byte stream is used to recreate the actual Java object in memory.
The byte stream created is platform independent. So, the object serialized on one platform can be deserialized on a different platform.
To make a Java object serializable we implement the java.io.Serializable interface.
The ObjectOutputStream class contains writeObject() method for serializing an Object.

Advantage of Java Serialization


It is mainly used to travel object's state on the network(known as marshaling).

Example of Serialization:-

class Employee implements Serializable
{
int empid;
String empname;
public Employee(int empid, String empname)
{
this.empid = empid;
this.empname = empname;
}
}
public class Persist
{
public static void main(String[] args)
{
Employee emp = new Employee(308, "Chandan");
FileOutputStream fout = new FileOutputStream("file.text");
ObjectOutputStream Oout = new ObjectOutputStream(fout);
Oout.writeObject(emp);
Oout.flush();
System.out.println("Serialization Completed");
}
}



Example of Deserialization:-


class Employee implements Serializable
{
int empid;
String empname;
public Employee(int empid, String empname)
{
this.empid = empid;
this.empname = empname;
}
}
public class Depersist
{
public static void main(String[] args) throws Exception
{
FileInputStream fin = new FileInputStream("file.txt");
ObjectInputStream Oin = new ObjectInputStream(fin);
Employee emp = (Employee)Oin.readObject();
System.out.println(emp.empid+ " " + emp.empname);
Oin.close();
System.out.println("DeSerialization Completed");
}
}

Monday 8 April 2019

Data Structure in JAVA

Data Structure in Java, what is Enumeration, vector etc.?



VIDEO :-



The Enumeration

:- It is an Interface
It is available in Java utility package.
Enumeration is used to process the elements of the collection objects which are introduce in jdk 1.0 for example vector.

There are two types of methods declared by Enumeration :-
hasMoreElements :- It returns Boolean value like True or False
nextElement :- It returns the next object in the enumeration.

Here is the Example for Vector and Enumeration :-


import java.util.Vector;
import java.util.Enumeration;

public class ENUM
{
public static void main(String args[])
{
Enumeration name;
Vector starNames = new Vector(5,3); (here 5 and 3 are initial and incremental capacity)
starNames.add("Julia Robert");
starNames.add("keanu reeves");
starNames.add("Akshay");
starNames.add("Maria");
starNames.add("Keira");
starNames.add("Frida");
starNames.add("Will");
name = starNames.elements(); //It will return Enumeration object
while (name.hasMoreElements())
{
System.out.println(name.nextElement());
}
}
}


Output :-

Julia Robert
keanu reeves
Akshay
Maria
Keira
Frida
Will


Vector :- It is a Class
Vector implements a dynamic array.
Implements List Interface & extends AbstractList.
Vector v = new Vector() Creates default vector of capacity 10.
Vector v = new Vector(int size, int incre) defines vectors Initial size & incremental size.

Example of vector class :-

public class Vectortutorial
{
Enumeration enum;
public static void main(String[] args)
{
Vector v = new Vector();
v.add("way2testing");
v.add("chandan");
v.add("Testing Tutorials");
v.add(7);
Iterator itr = v.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
Vector<Integer> vec = new Vector<Integer>();
vec.add(1);
vec.add(2);
vec.add(4);
enum = vec.elements();
while (enum.hasMoreElements())
{
System.out.println(enum.nextElement());
}
}
}

Output :-

way2testing
chandan
Testing Tutorials
1
2
4


Difference between Vector and ArrayList In Java

1). java.util.Vector came along with the first version of java development kit(JDK).
java.util.ArrayList was introduced in java version 1.2 as part of Java collection framework.
2). Vector is synchronized but ArrayList is not or we can say also
"All the methods of vector is synchronized but the methods of ArrayList is not synchronized."
So ArrayList is fast because it is not synchronised & vector is slow because it is synchronized.
3). Vectors doubles(100%) the size of its when its size is increased and ArrayList increases by half(50%) of its size when its size is increased.
4). ArrayList uses Iterator Interface to traverse the elements but A vector can use Iterator interface or Enumeration interface to traverse the elements.