Module 1 - Notes
Module 1 - Notes
Module 1 - Notes
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.
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.
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.
InputStream Hierarchy
InputStream Abstract byte stream superclass which
describes this type of input stream.
FileOutputStream
• 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.
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.
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.
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 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.
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:
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
Key Iterator
Basic In Iterator, we can read and remove element while traversing
element in the collections.
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.
• 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).
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.
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.
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.
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.
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' };
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));
}
}
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);
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);
}
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.
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")
@Target(ElementType.TYPE)
@interface MyAnnotation{
int value1();
String value2();
}
@Retention
@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{}
@Documented
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.
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);
}
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"));
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
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.
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.
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.
• 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
Driver class: The driver class for the mysql database is com.mysql.jdbc.Driver.
Class.forName("com.mysql.jdbc.Driver");
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
Statement stmt=con.createStatement();
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.
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
con.close();
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();
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();
}
}
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");
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.