Module 1 - Notes

Download as pdf or txt
Download as pdf or txt
You are on page 1of 38

Module 1

Syllabus :

Review of Java; Advanced concepts of Java; Java generics; Java IO; New Features of
Java. Unit Testing tools.

Review of Java

Java IO

• Java I/O (Input and Output) is used to process the input and produce the output.

• Java uses the concept of a stream to make I/O operation fast. The java.io package
contains all the classes required for input and output operations.

• Perform file handling in Java by Java I/O API.

Stream

• stream is a sequence of data. In Java, a stream is composed of bytes. It's called a stream
because it is like a stream of water that continues to flow

• In Java, 3 streams are created for us automatically. All these streams are attached with the
console.

• 1) System.out: standard output stream

• 2) System.in: standard input stream

• 3) System.err: standard error stream

the code to print output and an error message to the console.


Input Stream and Output Stream

InputStream

• Java application uses an input stream to read data from a source; it may be a file, an
array, peripheral device or socket.

OutputStream

• Java application uses an output stream to write data to a destination; it may be a file, an
array, peripheral device or socket.

OutputStream Hierarchy
OutputStream Abstract byte stream superclass which
describes this type of output stream.

ByteArrayOutputStream Output byte stream that writes data to a byte


array.

FileOutputStream Output byte stream that writes bytes to a file in


a file system.

FilterOutputStream Output byte stream that


implements OutputStream.

BufferedOutputStream Output byte stream that writes bytes to a


buffered output stream.

DataOutputStream Output stream to write Java primitive data


types.

PrintStream Convenience output byte stream to add


functionality to another stream, an example
being to print to the console
using print() and println().

ObjectOutputStream Output stream to write and serialize objects for


reading using ObjectInputStream.

PipedOutputStream Piped Output stream that is connected to a


piped input stream to create a communication
pipe.

InputStream Hierarchy
InputStream Abstract byte stream superclass which
describes this type of input stream.

ByteArrayInputStream Input byte stream that reads bytes from an


internal byte array.

FileInputStream Input byte stream that reads bytes from a file in


a file system.

FilterInputStream Input byte stream that


implements InputStream.

BufferedInputStream Input byte stream that reads bytes into an


internal buffer before use.

DataInputStream Input stream to reads Java primitive data types.

PushbackInputStream Input byte stream containing functionality to


return bytes to the input stream.

ObjectInputStream Input stream to read and deserialize objects


output and serialized
using ObjectOutputStream.

PipedInputStream Piped input stream that is connected to a piped


output stream to create a communication pipe.
SequenceInputStream Concatenation of two or more input streams
read sequentially.

FileOutputStream

• Java FileOutputStream is an output stream used for writing data to a file.

• If you have to write primitive values into a file, use FileOutputStream class. You can
write byte-oriented as well as character-oriented data through FileOutputStream class.

Methods in FileOutputStream

Method Description
protected void finalize() It is used to clean up the connection with the
file output stream.
void write(byte[] ary) It is used to write ary.length bytes from the
byte array to the file output stream.
void write(byte[] ary, int off, int len) It is used to write len bytes from the byte array
starting at offset off to the file output stream.
void write(int b) It is used to write the specified byte to the file
output stream.
FileChannel getChannel() It is used to return the file channel object
associated with the file output stream.
FileDescriptor getFD() It is used to return the file descriptor associated
with the stream.
void close() It is used to closes the file output stream.

FileInputStream

Java FileInputStream class obtains input bytes from a file. It is used for reading byte-oriented
data (streams of raw bytes) such as image data, audio, video etc. You can also read character-
stream data. But, for reading streams of characters, it is recommended to use FileReader class.

FileInputStream class methods

Method Description
int available() It is used to return the estimated number of
bytes that can be read from the input stream.
int read() It is used to read the byte of data from the input
stream.
int read(byte[] b) It is used to read up to b.length bytes of data
from the input stream.
int read(byte[] b, int off, int len) It is used to read up to len bytes of data from
the input stream.
long skip(long x) It is used to skip over and discards x bytes of
data from the input stream.
void close() It is used to closes the stream.

Serialization and Deserialization

Serialization is a mechanism of converting the state of an object into a byte stream.


It is mainly used in Hibernate, RMI, JPA, EJB and JMS technologies.
Deserialization is the reverse process where the byte stream is used to recreate the actual Java
object in memory. This mechanism is used to persist the object.
The serialization and deserialization process is platform-independent, it means you can
serialize an object on one platform and deserialize it on a different platform.

Collection Framework
The Collections in Java provides an architecture to store and manipulate the group of objects,
interfaces and classes. This java collection is a framework. This framework has several useful
functions that have tons of useful functions, making a programmer task super easy.

This framework provides many interfaces (Queue, Set, List, Deque) and classes ( PriorityQueue,
HashSet, ArrayList, Vector, LinkedList, LinkedHashSet).

Java frameworks are the prewritten code used by developers to create applications in the java
language.

The Collection framework is a unified architecture for storing and manipulating a group of
objects.

The collection framework was designed to meet several goals, such as −

 The framework had to be high-performance and adapt a collection easy method.


 The implementations for the fundamental collections were to be highly efficient.
 The framework had to allow different types of collections to work in a similar manner.
 The framework had to extend and/or adapt a collection easily.

Collection Framework Hierarchy


Java Cursor

 used to iterate or traverse or retrieve a Collection or Stream object’s elements one by one

Iterator
Iterator in Java is an object used to cycle through arguments or elements present in a collection.
It is derived from the technical term “iterating,” which means looping through. Generally, an
iterator in Java is used to loop through any collection of objects. To apply the iterator, all you
need to do is import the java.util package and then use the iterator() method. You can then use
the iterator to perform multiple operations in the collection.

boolean hasNext() Checks for more elements and returns true, if found.

It returns the next object or element in the collection. If no more


Object next()
elements are present, it throws a NoSuchElementException error.

It can only be used after the next() method and removes the current
object where the iterator is present. If you try to call the remove()
void remove()
method without calling the next() method, it throws an
IlegalStateException error.

Limitations of Iterator in Java

Iterators are useful to perform many operations in a collection, but there are also some
drawbacks to it. The primary limitations of iterators in Java include:

 It does not support backward direction iteration

 It doesn’t enable you to add new elements to the collection

 It does not support update operations on the collection

Enumeration

The Enumeration interface defines the methods by which you can enumerate (obtain one at a
time) the elements in a collection of objects.

This legacy interface has been superceded by Iterator. Although not deprecated, Enumeration is
considered obsolete for new code. However, it is used by several methods defined by the legacy
classes such as Vector and Properties, is used by several other API classes, and is currently in
widespread use in application code.

Method Description
When implemented, it must return true while there are still
boolean hasMoreElements( )
more elements to extract, and false when all the elements
have been enumerated.
Object nextElement( ) This returns the next object in the enumeration as a generic
Object reference.

ListIterator

ListIterator is a Java Iterator, which is used to iterate elements one-by-one from a List
implemented object.

 Unlike Iterator, It supports all four operations: CRUD (CREATE, READ, UPDATE and
DELETE).
 Unlike Iterator, It supports both Forward Direction and Backward Direction iterations.
 It is a Bi-directional Iterator.
 It has no current element; its cursor position always lies between the element that would be
returned by a call to previous() and the element that would be returned by a call to next().
add(E e) This method inserts the specified element into the list.
hasNext(), This returns true if the list has more elements to traverse.
This returns true if the list iterator has more elements while traversing the
hasPrevious()
list in the backward direction.
This method returns the next element and increases the cursor by one
next()
position.
This method returns the index of the element which would be returned on
nextIndex()
calling the next() method.
This method returns the previous element of the list and shifts the cursor
previous()
one position backward
This method returns the index of the element which would be returned on
previousIndex()
calling the previous() method.
This method removes the last element from the list that was returned on
remove()
calling next() or previous() method element from.
This method replaces the last element that was returned on calling next() or
set(E e)
previous() method with the specified element.
add(E e) This method inserts the specified element into the list.
Method to access collection

• Using iterator() Method

• Using forEach() Method

• Using listIterator() Method

Distinguish between Iterator and Enumeration

Key Iterator
Basic In Iterator, we can read and remove element while traversing
element in the collections.

Access It can be used with any class of the collection framework.

Fail-Fast and Fail -Safe Any changes in the collection, such as removing element from
the collection during a thread is iterating collection then it throw
concurrent modification exception.

Limitation Only forward direction iterating is possible

Methods It has following methods −


*hasNext()
*next()
*remove()

Difference between ArrayList and Vector


Comparable interface

• Java Comparable interface is used to order the objects of the user-defined class.

• This interface is found in java.lang package and contains only one method named
compareTo(Object).

• It provides a single sorting sequence only

public int compareTo(Object obj): It is used to compare the current object with the specified
object. It returns

o positive integer, if the current object is greater than the specified object.
o negative integer, if the current object is less than the specified object.
o zero, if the current object is equal to the specified object.

Java Comparator interface

Java Comparator interface is used to order the objects of a user-defined class.

This interface is found in java.util package and contains 2 methods compare(Object obj1,Object
obj2) and equals(Object element).

It provides multiple sorting sequences, i.e., you can sort the elements on the basis of any data
member, for example, rollno, name, age or anything else.
Generic Programming

• The Java Generics programming is introduced in J2SE 5 to deal with type-safe objects.
It makes the code stable by detecting the bugs at compile time.
• Before generics, we can store any type of objects in the collection, i.e., non-generic.
• Now generics force the java programmer to store a specific type of objects.

Advantage of Java Generics

1. Type-safety: We can hold only a single type of objects in generics. It does not allow to
store other objects.
2. Type casting is not required: There is no need to typecast the object.
3. Compile-Time Checking: It is checked at compile time so problem will not occur at
runtime. The good programming strategy says it is far better to handle the problem at
compile time than runtime.

Types of Java Generics

1. Generic class
2. Generic Method

Generic class
• A class that can refer to any type is known as a generic class. Here, we are using the T
type parameter to create the generic class of specific type.
• Creating a generic class:
class MyGen<T>{
T obj;
void set(T obj) { this.obj=obj; }
T get(){ return obj; }
}
• The T type indicates that it can refer to any type (like String, Integer, and Employee). The
type you specify for the class will be used to store and retrieve the data.

• Using generic class

class TestGenerics3{
public static void main(String args[]){
MyGen<Integer> m=new MyGen<Integer>();
m.add(2);
//m.add("vivek");//Compile time error
System.out.println(m.get());
}
}
Example
class Pair<K, V> {
private K key;
private V value;
public void setKey(K key) {
this.key = key;
}
public void setValue(V value) {
this.value = value;
}
public K getKey() {
return key;
}
public V getValue() {
return value;
}
}
class HelloWorld {
public static void main(String[] args) {
Pair<Integer,String> p = new Pair<Integer,String>();
p.setKey(1);
p.setValue("abc");
System.out.println(p.getKey() + p.getValue());
}
}
Type Parameters

• The type parameters naming conventions are important to learn generics thoroughly. The
common type parameters are as follows:

• T - Type

• E - Element

• K - Key

• N - Number

• V - Value

Generic Method

• Like the generic class, we can create a generic method that can accept any type of
arguments. Here, the scope of arguments is limited to the method where it is declared. It
allows static as well as non-static methods.
• Let's see a simple example of java generic method to print array elements. We are using
here E to denote the element.
public class TestGenerics4{
public static < E > void printArray(E[] elements) {
for ( E element : elements){
System.out.println(element );
}
System.out.println();
}
public static void main( String args[] ) {
Integer[] intArray = { 10, 20, 30, 40, 50 };
Character[] charArray = { 'J', 'A', 'V', 'A', 'T','P','O','I','N','T' };

System.out.println( "Printing Integer Array" );


printArray( intArray );
System.out.println( "Printing Character Array" );
printArray( charArray );
}
}
Wildcard in Java Generics
• In generic code, the question mark (?), called the wildcard, represents an unknown type.
• The wildcard can be used in a variety of situations: as the type of a parameter, field, or
local variable; sometimes as a return type (though it is better programming practice to be
more specific).
Types of wildcards
• Upper bound Wildcard − ? extends Type.
• Lower bound Wildcard − ? super Type.
• Unbounded Wildcard − ?

Upper Bounded Wildcards


• The purpose of upper bounded wildcards is to decrease the restrictions on a variable. It
restricts the unknown type to be a specific type or a subtype of that type. It is used by
declaring wildcard character ("?") followed by the extends (in case of, class) or
implements (in case of, interface) keyword, followed by its upper bound.
• Syntax
• List<? extends Number>
• ? is a wildcard character.
• extends, is a keyword.
• Number, is a class present in java.lang package
• Suppose, we want to write the method for the list of Number and its subtypes (like
Integer, Double). Using List<? extends Number> is suitable for a list of type Number or
any of its subclasses whereas List<Number> works with the list of type Number only.
So, List<? extends Number> is less restrictive than List<Number>.

Example
import java.util.ArrayList;
public class UpperBoundWildcard {
private static Double add(ArrayList<? extends Number> num) {
double sum=0.0;
for(Number n:num) {
sum = sum+n.doubleValue();
}
return sum;
}
public static void main(String[] args) {
ArrayList<Integer> l1=new ArrayList<Integer>();
l1.add(10);
l1.add(20);
System.out.println("displaying the sum= "+add(l1));
ArrayList<Double> l2=new ArrayList<Double>();
l2.add(30.0);
l2.add(40.0);
System.out.println("displaying the sum= "+add(l2));
}
}

Lower Bounded Wildcards


• The purpose of lower bounded wildcards is to restrict the unknown type to be a specific
type or a super type of that type. It is used by declaring wildcard character ("?") followed
by the super keyword, followed by its lower bound.
• Syntax
• List<? super Integer>
• Here,
• ? is a wildcard character.
• super, is a keyword.
• Integer, is a wrapper class.
• Suppose, we want to write the method for the list of Integer and its supertype (like
Number, Object). Using List<? super Integer> is suitable for a list of type Integer or any
of its superclasses whereas List<Integer> works with the list of type Integer only.
So, List<? super Integer> is less restrictive than List<Integer>.

Example
import java.util.Arrays;
import java.util.List;

class WildcardDemo {
public static void main(String[] args)
{
// Lower Bounded Integer List
List<Integer> list1 = Arrays.asList(4, 5, 6, 7);

// Integer list object is being passed


printOnlyIntegerClassorSuperClass(list1);
// Number list
List<Number> list2 = Arrays.asList(4, 5, 6, 7);

// Integer list object is being passed


printOnlyIntegerClassorSuperClass(list2);
}

public static void printOnlyIntegerClassorSuperClass(


List<? super Integer> list)
{
System.out.println(list);
}
}
Unbounded Wildcard
• This wildcard type is specified using the wildcard character (?), for example, List. This is
called a list of unknown types. These are useful in the following cases –
• When writing a method that can be employed using functionality provided in Object
class.
• When the code is using methods in the generic class that doesn’t depend on the type
parameter
• The unbounded wildcard type represents the list of an unknown type such as List<?>.
This approach can be useful in the following scenarios: -
• When the given method is implemented by using the functionality provided in the Object
class.
• When the generic class contains the methods that don't depend on the type parameter.
Example
import java.util.Arrays;
import java.util.List;

class unboundedwildcardemo {
public static void main(String[] args)
{

// Integer List
List<Integer> list1 = Arrays.asList(1, 2, 3);

// Double list
List<Double> list2 = Arrays.asList(1.1, 2.2, 3.3);

printlist(list1);

printlist(list2);
}

private static void printlist(List<?> list)


{

System.out.println(list);
}
}

Annotation

• Java Annotation is a tag that represents the metadata i.e. attached with class, interface,
methods or fields to indicate some additional information which can be used by java
compiler and JVM.
• Annotations start with ‘@’.
• Annotations do not change the action of a compiled program.
• Annotations help to associate metadata (information) to the program elements i.e.
instance variables, constructors, methods, classes, etc.
• Annotations are not pure comments as they can change the way a program is treated by
the compiler.
• Annotations in Java are used to provide additional information, so it is an alternative
option for XML and Java marker interfaces.
Hiearchy of Annotations

Categories of Annotations
• There are broadly 5 categories of annotations as listed:
• Marker Annotations
• Single value Annotations
• Full Annotations
• Type Annotations
• Repeating Annotations

@Override

• @Override annotation assures that the subclass method is overriding the parent class
method. If it is not so, compile time error occurs.

• Sometimes, we does the silly mistake such as spelling mistakes etc. So, it is better to
mark @Override annotation that provides assurity that method is overridden.

class A{
void m1() { System.out.println(“Method1"); }
}
class B extends A{
@Override
void m1() { System.out.println(“Override metod in B"); }//should be eatSomething
}
class TestAnnotation1{
public static void main(String args[]) {
A a=new B();
a.m1();
}
}
@SuppressWarnings
• @SuppressWarnings annotation: is used to suppress warnings issued by the compiler.

• If you remove the @SuppressWarnings("unchecked") annotation, it will show warning at


compile time because we are using non-generic collection.

import java.util.*;
class TestAnnotation2{
@SuppressWarnings("unchecked")
public static void main(String args[]){
ArrayList list=new ArrayList();
list.add("sonoo");
list.add("vimal");
list.add("ratan");
for(Object obj:list)
System.out.println(obj);
}
}
@Deprecated
@Deprecated annoation marks that this method is deprecated so compiler prints warning. It
informs user that it may be removed in the future versions. So, it is better not to use such
methods.
class A{
void m(){ System.out.println("hello m"); }
@Deprecated
void n(){System.out.println("hello n");}
}

class TestAnnotation3{
public static void main(String args[]){
A a=new A();
a.n();
}
}
Java Custom Annotations/ Java User-defined annotations
• are easy to create and use.
• The @interface element is used to declare an annotation. For example:
@interface MyAnnotation{}
Here, MyAnnotation is the custom annotation name.
• There are few points that should be remembered by the programmer.
1. Method should not have any throws clauses
2. Method should return one of the following: primitive data types, String, Class, enum or
array of these data types.
3. Method should not have any parameter.
4. We should attach @ just before interface keyword to define annotation.
5. It may assign a default value to the method.
Marker Annotation
• An annotation that has no method, is called marker annotation. For example:
• @interface MyAnnotation{}
• Ex : The @Override and @Deprecated are marker annotations.
Single-Value Annotation
• An annotation that has one method, is called single-value annotation. For example
@interface MyAnnotation{
int value();
}
• We can provide the default value also. For example:
@interface MyAnnotation{
int value() default 0;
}
• How to apply Single-Value Annotation
• Let's see the code to apply the single value annotation.
• @MyAnnotation(value=10)
• The value can be anything.
Multi-Value Annotation
An annotation that has more than one method, is called Multi-Value annotation. For example:
@interface MyAnnotation {
int value1();
String value2();
String value3();
}
We can provide the default value also. For example:
@interface MyAnnotation {
int value1() default 1;
String value2() default "";
String value3() default "xyz";
}
How to apply Multi-Value Annotation
Let's see the code to apply the multi-value annotation.
@MyAnnotation(value1=10,value2="Arun Kumar",value3="Ghaziabad")

Built-in Annotations used in custom annotations in java


o @Target
o @Retention
o @Inherited
o @Documented
@Target

@Target tag is used to specify at which type, the annotation is used.

The java.lang.annotation.ElementType enum declares many constants to specify the type of


element where annotation is to be applied such as TYPE, METHOD, FIELD etc. Let's see the
constants of ElementType enum:

@Target(ElementType.TYPE)
@interface MyAnnotation{
int value1();
String value2();
}

@Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD})


@interface MyAnnotation{
int value1();
String value2();
}

@Retention

@Retention annotation is used to specify to what level annotation will be available.

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@interface MyAnnotation{
int value1();
String value2();
}

@Inherited

By default, annotations are not inherited to subclasses. The @Inherited annotation marks the
annotation to be inherited to subclasses.

@Inherited
@interface ForEveryone { }//Now it will be available to subclass also

@interface ForEveryone { }
class Superclass{}

class Subclass extends Superclass{}

@Documented

The @Documented Marks the annotation for inclusion in the documentation.

Lambda Expression
• Lambda expression is a new and important feature of Java which was included in Java SE
8.
• A lambda expression is a short block of code which takes in parameters and returns a
value. Lambda expressions are similar to methods, but they do not need a name and they
can be implemented right in the body of a method.
• It provides a clear and concise way to represent one method interface using an
expression.
• It is very useful in collection library. It helps to iterate, filter and extract data from
collection.
• The Lambda expression is used to provide the implementation of an interface which has
functional interface. It saves a lot of code.
• In case of lambda expression, we don't need to define the method again for providing the
implementation.
Java lambda expression is treated as a function, so compiler does not create .class file.

Why use Lambda Expression?


1. To provide the implementation of Functional interface.
2. Less coding.
Java Lambda Expression Syntax
(argument-list) -> {body}
• Java lambda expression is consisted of three components.
1) Argument-list: It can be empty or non-empty as well.
2) Arrow-token: It is used to link arguments-list and body of expression.
3) Body: It contains expressions and statements for lambda expression.
Parameter Syntax
• No Parameter Syntax
() -> {
//Body of no parameter lambda
}
• One Parameter Syntax
(p1) -> {
//Body of single parameter lambda
}
• Two Parameter Syntax
(p1,p2) -> {
//Body of multiple parameter lambda
}
Example
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<Integer>();
numbers.add(5);
numbers.add(9);
numbers.add(8);
numbers.add(1);
numbers.forEach( (n) -> { System.out.println(n); } );
}
}

Functional Interface
• Lambda expression provides implementation of functional interface.
• An interface which has only one abstract method is called functional interface.
• Java provides an anotation @FunctionalInterface, which is used to declare an interface as
functional interface.
@FunctionalInterface
interface Sayable{
String say(String message);
}

public class LambdaExpressionExample8{


public static void main(String[] args) {
// You can pass multiple statements in lambda expression
Sayable person = (message)-> {
String str1 = "I would like to say, ";
String str2 = str1 + message;
return str2;
};
System.out.println(person.say("time is precious."));
}
}

Single Parameter
interface Sayable{
public String say(String name);
}
public class LambdaExpressionExample4{
public static void main(String[] args) {
// Lambda expression with single parameter.
Sayable s1=(name)->{
return "Hello, "+name;
};
System.out.println(s1.say("Sonoo"));

// You can omit function parentheses


Sayable s2= name ->{
return "Hello, "+name;
};
System.out.println(s2.say("Sonoo"));
}
}
Java Lambda Expression Example: with or without return keyword
interface Addable{
int add(int a,int b);
}

public class LambdaExpressionExample6 {


public static void main(String[] args) {

// Lambda expression without return keyword.


Addable ad1=(a,b)->(a+b);
System.out.println(ad1.add(10,20));
// Lambda expression with return keyword.
Addable ad2=(int a,int b)->{
return (a+b);
};
System.out.println(ad2.add(100,200));
}
}

Java Lambda Expression Example: forEach Loop


import java.util.*;
public class LambdaExpressionExample7{
public static void main(String[] args) {

List<String> list=new ArrayList<String>();


list.add("ankit");
list.add("mayank");
list.add("irfan");
list.add("jai");

list.forEach(
(n)->System.out.println(n)
);
}
}

API
• API (Application programming interface) is a document that contains a description of all
the features of a product or software.
• In the context of APIs, the word Application refers to any software with a distinct
function. Interface can be thought of as a contract of service between two applications.
This contract defines how the two communicate with each other using requests and
responses.
• It represents classes and interfaces that software programs can follow to communicate
with each other. An API can be created for applications, libraries, operating systems, etc
JDBC
• JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and execute
the query with the database. It is a part of JavaSE (Java Standard Edition). JDBC API
uses JDBC drivers to connect with the database.

Applications of JDBC
 Java Applications
 Java Applets
 Java Servlets
 Java ServerPages (JSPs)
 Enterprise JavaBeans (EJBs).

JDBC Driver

There are four types of JDBC drivers:


• JDBC-ODBC Bridge Driver,
• Native Driver,
• Network Protocol Driver, and
• Thin Driver
• use JDBC API to access tabular data stored in any relational database. By the help of
JDBC API, we can save, update, delete and fetch data from the database. It is like Open
Database Connectivity (ODBC) provided by Microsoft.
The current version of JDBC is 4.3. It is the stable release since 21st September, 2017. It is
based on the X/Open SQL Call Level Interface. The java.sql package contains classes and
interfaces for JDBC API.
Type 1 − JDBC-ODBC Bridge Driver

In a Type 1 driver, a JDBC bridge is used to access ODBC drivers installed on each client
machine. Using ODBC, requires configuring on your system a Data Source Name (DSN) that
represents the target database.

When Java first came out, this was a useful driver because most databases only supported ODBC
access but now this type of driver is recommended only for experimental use or when no other
alternative is available.

The JDBC-ODBC Bridge that comes with JDK 1.2 is a good example of this kind of driver.
Type 2 − JDBC-Native API

In a Type 2 driver, JDBC API calls are converted into native C/C++ API calls, which are unique
to the database. These drivers are typically provided by the database vendors and used in the
same manner as the JDBC-ODBC Bridge. The vendor-specific driver must be installed on each
client machine.

If we change the Database, we have to change the native API, as it is specific to a database and
they are mostly obsolete now, but you may realize some speed increase with a Type 2 driver,
because it eliminates ODBC's overhead.

The Oracle Call Interface (OCI) driver is an example of a Type 2 driver


Type 3 − JDBC-Net pure Java

In a Type 3 driver, a three-tier approach is used to access databases. The JDBC clients use
standard network sockets to communicate with a middleware application server. The socket
information is then translated by the middleware application server into the call format required
by the DBMS, and forwarded to the database server.

This kind of driver is extremely flexible, since it requires no code installed on the client and a
single driver can actually provide access to multiple databases.

You can think of the application server as a JDBC "proxy," meaning that it makes calls for the
client application. As a result, you need some knowledge of the application server's configuration
in order to effectively use this driver type.

Your application server might use a Type 1, 2, or 4 driver to communicate with the database,
understanding the nuances will prove helpful.

Type 4 − 100% Pure Java

In a Type 4 driver, a pure Java-based driver communicates directly with the vendor's database
through socket connection. This is the highest performance driver available for the database and
is usually provided by the vendor itself.

This kind of driver is extremely flexible, you don't need to install special software on the client
or server. Further, these drivers can be downloaded dynamically.
Which Driver should be Used?

If you are accessing one type of database, such as Oracle, Sybase, or IBM, the preferred driver
type is 4.

If your Java application is accessing multiple types of databases at the same time, type 3 is the
preferred driver.

Type 2 drivers are useful in situations, where a type 3 or type 4 driver is not available yet for
your database.

The type 1 driver is not considered a deployment-level driver, and is typically used for
development and testing purposes only.

Database Connectivity with 5 Steps

• There are 5 steps to connect any java application with the database using JDBC. These
steps are as follows:
1) Register the driver class

The forName() method of Class class is used to register the driver class. This method is used
to dynamically load the driver class.Syntax of forName() method

public static void forName(String className)throws ClassNotFoundException

Driver class: The driver class for the mysql database is com.mysql.jdbc.Driver.

Class.forName("com.mysql.jdbc.Driver");

2) Create the connection object


• The getConnection() method of DriverManager class is used to establish connection
with the database.
• Syntax of getConnection() method
1) public static Connection getConnection(String url)throws SQLException
2) public static Connection getConnection(String url,String name,String password) thro
ws SQLException
• Connection URL: The connection URL for the mysql database
is jdbc:mysql://localhost:3306/god where jdbc is the API, mysql is the database,
localhost is the server name on which mysql is running, we may also use IP address, 3306
is the port number and god is the database name. We may use any database, in such case,
we need to replace the god with our database name.
• Connection con=DriverManager.getConnection( "jdbc:mysql://localhost:3306/god","root
","root");

3) Create the Statement object

The createStatement() method of Connection interface is used to create statement. The object of
statement is responsible to execute queries with the database.Syntax of createStatement() method

public Statement createStatement()throws SQLException

Example to create the statement object

Statement stmt=con.createStatement();

4) Execute the query

The executeQuery() method of Statement interface is used to execute queries to the database.
This method returns the object of ResultSet that can be used to get all the records of a table.

Syntax of executeQuery() method

public ResultSet executeQuery(String sql)throws SQLException


Example to execute query
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2) + “ “ + rs.getInt(3));
}

5) Close the connection object

By closing connection object statement and ResultSet will be closed automatically. The close()
method of Connection interface is used to close the connection.Syntax of close() method

public void close()throws SQLException

Example to close connection

con.close();

Java Database Connectivity with MySQL


• Driver class: The driver class for the oracle database is com.mysql.jdbc.Driver.
• Connection URL: The connection URL for the oracle10G database is
jdbc:mysql://localhost:3306/god where jdbc is the API, god is the database, thin is the
driver, localhost is the server name on which mysql is running, we may also use IP
address, 3306 is the port number.
• Username: The default username for the oracle database is root.
• Password: root is the password given by the user at the time of installing the oracle
database.
• Install MySQL
• Create database god;
• Use god;
• create table emp(rno int,name varchar(30),age int);

import java.sql.*;
class FetchRecord{
public static void main(String args[])throws Exception{
Class.forName(" com.mysql.jdbc.Driver ");
Connection con=DriverManager.getConnection("
jdbc:mysql://localhost:3306/god","root","root");
Statement stmt=con.createStatement();

stmt.executeUpdate("insert into emp values(1,'Irfan',50000)");

int result=stmt.executeUpdate("update emp set name='Vimal',salary=10000 where rno=1");


int result=stmt.executeUpdate("delete from emp where rno=1");
System.out.println(result+" records affected");
con.close();
}
}

Class.forName(" com.mysql.jdbc.Driver ");


Connection con=DriverManager.getConnection("
jdbc:mysql://localhost:3306/god","root","root");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from emp”);
while(rs.next()) {
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getInt(3));
}
con.close();

import java.sql.*;
class InsertPrepared{
public static void main(String args[]){
try{
Class.forName(" com.mysql.jdbc.Driver ");
Connection con=DriverManager.getConnection("
jdbc:mysql://localhost:3306/god","root","root");
PreparedStatement stmt=con.prepareStatement("insert into emp values(?,?,?)");
stmt.setInt(1,1);//1 specifies the first parameter in the query
stmt.setString(2,"Ratan");
stmt.setInt(3,100000);
int i=stmt.executeUpdate();
System.out.println(i+" records inserted");

con.close();

}catch(Exception e){ System.out.println(e);}

}
}
PreparedStatement stmt=con.prepareStatement("delete from emp where rno=?");
stmt.setInt(1,101);
int i=stmt.executeUpdate();
System.out.println(i+" records deleted");
PreparedStatement stmt=con.prepareStatement("select * from emp");
ResultSet rs=stmt.executeQuery();
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2) + “ “ + getInt(3));
}
import java.sql.*;
class Rsmd{
public static void main(String args[]){
try{
Class.forName(" com.mysql.jdbc.Driver ");
Connection con=DriverManager.getConnection("
jdbc:mysql://localhost:3306/god","root","root");

PreparedStatement ps=con.prepareStatement("select * from emp");


ResultSet rs=ps.executeQuery();
ResultSetMetaData rsmd=rs.getMetaData();

System.out.println("Total columns: "+rsmd.getColumnCount());


System.out.println("Column Name of 1st column: "+rsmd.getColumnName(1));
System.out.println("Column Type Name of 1st column: "+rsmd.getColumnTypeName(1));

con.close();
}catch(Exception e){ System.out.println(e);}
}
}
• To connect java application with the mysql database, mysqlconnector.jar file is required
to be loaded.
• download the jar file mysql-connector.jar
• Two ways to load the jar file:
• Paste the mysqlconnector.jar file in jre/lib/ext folder
• Set classpath
• 1) Paste the mysqlconnector.jar file in JRE/lib/ext folder:
• Download the mysqlconnector.jar file. Go to jre/lib/ext folder and paste the jar file
here.2) Set classpath:
• There are two ways to set the classpath:temporary
• permanent
• How to set the temporary classpath
• open command prompt and write:
• C:>set classpath=c:\folder\mysql-connector-java-5.0.8-bin.jar;.;
• How to set the permanent classpath
• Go to environment variable then click on new tab. In variable name write classpath and
in variable value paste the path to the mysqlconnector.jar file by appending
mysqlconnector.jar;.; as C:\folder\mysql-connector-java-5.0.8-bin.jar;.;

Question Bank

Part A
1 Define stream.
2 List three streams for java IO.
3 Review a java program to read/write a text file.
4 Define serialization and deserialization.
5 List the advantages of serialization and deserialization.
6 List advantages of generics.
7 Name methods to access the collection framework
8 Distinguish between ArrayList and Vector.
9 Difference and similarities between HashSet and TreeSet.
Name different types of wild cards in Generic
10 programming.
11 Distinguish between Iterator and Enumeration.

Part B
12 Describe the I/O classes in java.
13 Illustrate Serialization and Deserialization with an example
14 Explain different types of JDBC drivers.
15 Demonstrate Generic method and class with example.
16 Illustrate Collection and collection framework.
17 Describe about Annotations and its types with example.
18 Explain about Lambda expression and its uses

Part C
1 To implement the collection framework by develop a java console application.
2 To implement the collection framework, access the collection by using Lambda
Expression and demonstrate it with a java console application.
3 To develop a Java console application that demonstrates the connection with MySQL
database and perform various operations on it.

You might also like