Vous êtes sur la page 1sur 68

Module-I

Java is a true object oriented language Every o o


programming language must satisfy three important features
like Encapsulation inheritance and polymorphism.
Encapsulation: is the of binding the data and methods
together into a single unit called class. The purpose of the
feature is more security to data and methods.
Inheritance: is the process by which the objects of one class
acquire the prosperities of objects of another class. Its
purpose is the reusability of data and methods.
Polymorphism: is the ability to take more than one form. It
is the process in which an interface with different method
implementory will be done. Its purpose is to reduce the code.
Benefits of oops:
OOP offers several advantages to both the programmer
and the user. The principle advantages are:-
1 Through inheritance, redundant code can be innovated
and the use of existing classes can be extended.
2 The possibility of writing a body of cod once, and than
reusing that code over and over again. This leads to
saving of development time and higher productivity.

1
3 Based on the objects work in a project can be
partitioned into different modules.
4 The concept of data hiding helps to build secure
programs that can not be invaded by code in other parts
of the program.
5 Object oriented systems can be easily upgraded from
small to large systems.
6 Software complexity can be easily managed.

Dynamic Initialization of Variable:


Java allows variable to be initialized dynamically using any
expression valid at the time the variable in declared.
// dynamic initialization program.
Class dynamic
{ public static void main (String args [ ])
{ int a = 3, b = 4,
int c = math.sqrt(a*a + b*b); // dynamic
initialization.
System. out. println (“c is”+c) ;
}
}

2
Control Statements:-
Control flow statements are used to make decisions
about which statements to execute and to otherwise change
the flow of execution in a program.
These are broadly of three types.
1. Selection Statements: if and switch (if else, nested if
else, else if ladder, nested switch)
2. Iteration (Looping) Statements: for, while, do while.
3. Jumping Statements: break, continue, return.

Static: It is a keyword applied to both variables and method.


These are called class members since both static variables
and static methods are accessed by the class name itself
without creating an object of a class.
These static variables are common to whole class
instead of a single object. Hence all objects of the class have
same constant value for a static variable. A static variable
may change but it is constant for whole class. It is same for
different objects of the same class.
Static methods can also be accessed without creating an
object of a class. main() method is a static method.

3
They can not refer to this or super in any way.
final: final key word can be applied to variables, method
and classes. A final variable is one whose value does not
change during the execution of a program. A final class is
one, which cannot be extended; a final method is one, which
can not be overrided by its sub class.
this: It refers to the current object. “this” is used to avoid
hiding of instance variably by local variables.
Usage of super: The keyword super is used within methods
and usually in constructors of a derived class to refer to the
constructor of the class from which the new class was
derived .super refers to the super class.
Whenever a sub class needs to refer to its, immediate
super class, it can do so by the use of the key word super.
super has two general forms. The first call the super class
constructor. The second is used to access a members of the
super class that has been hidden by a members of sub class.
A sub class can call a constructor method defined by its super
class by use of the following form of super.
super (parameter list);

4
Here parameter list specifies any parameters needed by the
constructor in the super class .super ( ) must always be the
first statement executed inside a sub class constructor. super
refers to the super class of the sub class in which it is used.
This has the general form. Super. members, here member can
be either a variable or a method.
Method overriding: When a method in a sub class has the
same name, same parameters and same return type as a
method in its super class,then the method in the subclass is
said to override the method in the super class. when an
overridden method is called from within a subclass, it will
always refer to the method defined by the sub class.
Method overriding is done in different classes. It leads
to polymorphism. Since the appropriate method is called at
run time, it is also called late-binding.
Abstract class: it is a class which may or may not contain
abstract and non-abstract methods. We can’t create an object
of an abstract class.
When a class extends an abstract class it must
implement all the abstract methods or else the sub class it self
be declared as abstract.

5
final: A final class is one, which can not be extended. The
execution of a final class is very fast since there is no
inheritance for a final class and hence there is no overriding
of methods.
Dynamic method Dispatch: Method overriding forms the
basis for one of Java’s most powerful concept called
Dynamic method dispatch. Dynamic method dispatch is the
mechanism by which a call to an overridden method is
resolved at run time, rather than at compile time. This is
important because this is how Java implements run time
polymorphism.
Object class: It is the super class of all classes in Java.
Hence the methods in this class are overridden by its
subclasses. Some of the important methods in this class are
equals( ), finalize ( ), notify ( ), notify All ( ), to String (
), wait ( ) etc.,

********** E N D *********

6
Module – II
Packages and Interfaces
A Package in Java is one which contains classes and
interfaces.There are many packages used in Java.
Java.lang is the default package in Java.
Some of the important packages in Java are :
java.io
java.net
java.util
java.awt
java.awt.event
java.applet
java.sql
javax.swing
Access Specifiers:
A modifier assigns characteristics to the method.That is it
specifies the availability of the method to the other methods
or classes.Similarly you can have specifiers for packages and
interfaces.
They are :
private
public
protected
default

7
Importing a package :
A package in Java can be imported by using the key
word “import”
Eg:
import java.awt.*;
means all classes and interfaces in that package are available
to the given Java program

********************* E N D **********

Exception Handling

A Java exception is an object that describes an


exceptional condition that has occurred in a program.
Exceptions are the errors occurred at run time. By using
Exceptional handling we can make an abnormal program as a
normal program. Bu using exception handling we can predict
the flow of a program and can take necessary steps for its
normal flow.
The super class of all the exceptions is Throwable

8
class. It has two subclass namely Error and Exception
classes. Error is the class which we can’t avoid those errors
occurred at run time.
Exception is the class where we can handle those
errors.Exception has two sub classes namely Checked
exception and UncheckedException
Checked Exceptions: Those are the subclasses of the
Exception class. These are the errors occurred at run time
which can not be programmatically rectified.
Unchecked Exception: These are the errors occurred at run
time which can be programmatically rectified.
These are also called RunTimeExceptions.Most of the
exceptions are subclasses of RunTimeException class.
There are five key words used in Exception Handling of
Java. They are :
try
catch
finally
throw
throws
try:

9
A try block is used to encapsulate a piece of code where
we may be expecting some run time errors.If this try block
finds any run time error,it throws those errors to a suitable
catch block.
If there is no run time error in the try block, then the
execution of the program is normal.
A try block must always be associated with atleast one catch
block or a finally block or both.
A try block may have multiple catch blocks, only one of
those multiple catch blocks will be executed.
catch :
The error thrown by a try block is caught in this catch
block.A catch block is always followed by a try block.
A catch block takes one parameter of type Exception
class.
If there are multiple catch blocks for a given try block,
the catch block which contains Super class Exception should
come after all sub class Exception catch blocks.
finally :
This finally block is used to execute whether an
Exception is caught or uncaught.

10
This is followed by catch blocks or a simple try block.
This is mainly used to know the follow of execution of a
given program.
throw :
This is used to throw some predefined Exceptions
explicitly.It is mainly used to create User Defined
Exceptions.
throws :
This is used to throw Exceptions from methods.Most of
the checked exceptions use throws in Java programs.
Generally this is used while writing IO programs,JDBC
programs and other advanced Java Programs like Servlets,
RMI etc…
Java’s built in Exceptions :
There are many built in Exceptions in Java.These
are of type Exception and its sub class Exceptions.
Some of the important built in Exceptions in Exception
class are:
ArithmeticException
NumberFormatException

11
ArrayIndexOutOfBoundsException
IndexOutOfBoundsException
IOException
InterruptedException etc…
User Defined Exceptions :
In addition to built in Exceptions or predefined
Exceptions, we can create User Defined Exceptions also
depending upon the type of application.

User Defined Exception can be created by extending


Exception class.

Question: List out by an example the way to create user


defined exception (or) write a program to create user defined
exception.
Solution:
Generally user defined exceptions are used in practical
applications. All user defined exceptions extend Exception
class.
The following MyownException extends exception
class.

12
// program to create user defined exception class named
//MyownException
//Program solution
class MyownException extends Exception
{
MyownException ( )
{}
public String getMessage ( )
{
return “in sufficient funds”;
}
}
class Exceptiondemo
{
public static void main (String args [ ] )
{
try
{
int amount= Integer. parseInt(args [0]) ;
if (amount < 500)
{

13
throw new MyownException ( );
}
}
catch (MyownException m )
{
System.out. println (m. getMessage ( ) ) ;
}
}
}
In the above program, the amount is entered from the
command line and if the amount is less than 500, it will
throw an user defined exception

********* E N D *********

14
Multi Threading :
Multi Threading is the concept used in Java based
on Multi tasking.Multi Threading is the technique used to
perform many things simultaneously. By using multi
threading, we can make CPU more busy and hence reduce
the idle time of CPU.
Java Thread Model:
This model is also similar to process based multi
tasking. A Thread is a separate path of execution in a
program. In Multi Threading model of multi tasking all
thread have same address and are called light weight
components.
Thread Priorities : Thread priorities are used by thread
scheduler to decide when each thread should be allowed to
run.These are the integer values.
There are three types of Thread priorities:
They are :
MIN_PRIORITY
MAX_PRIORITY
NORM_PRIORITY
MIN_PRIORITY........VALUE IS 1
MAX_PRIORITY........VALUE IS 10
NORM_PRIORITY........VALUE IS 5
Synchronization :

When two or more threads need access to a shared


resource,they need some way to ensure that the resource will
be used by only one thread at a time.This is called
Synchronization.
By using this, the code is safe and the resource is not

15
corrupted. But the draw back is the execution is little bit
slow.
Creating a thread:
We can create our own thread by extending a Thread class or
implementing a Runnable interface.
Imp.methods in Thread class:
String getName(): Obtain thread's name
int getPriority(): Obtain a thread's priority.
boolean isAlive() : Determine if a thread is still running or
not
static void sleep(long milliseconds): suspend a thread for a
period of time.
public void start() : Start a thread by calling it's run method.
Imp.methods in Runnable interface;
public void run() :this method must be implemented by
any class that implements this interface.
Creating Multiple Threads :
We can create multiple threads either by using a
Thread class or a Runnable interface.

Eg:
Creating three user defined threads Thread1,Thread2
and Thread3 by extending a Thread class;
//creation of multiple threads
class Thread1 extends Thread
{}
class Thread2 extends Thread
{}
class Thread3 extends Thread
{}

16
class Threaddemo
{
public static void main(String args[])
{
Thread1 t1=new Thread1();
Thread1 t2=new Thread2();
Thread1 t3=new Thread3();
}
}
Life cycle of a thread: In multithreading a thread is a
separate path of execution in a program. Every thread has 5
life cycle stages. They are:-
1.New born state
2.Runnable state
3.Running state
4.Blocked state
5. Dead state
A thread is in one of these five states .It can move from one
state to other state.
New born state: When a thread object is created the thread
is born and is said to be in new born state.
Runnable state: in this state, the thread is ready for
execution and is waiting for the availability of the processor.

Running state: Running means that the processor has given

17
its time to the thread for its execution.
Blocked state: A thread is blocked when it is prevented from
entering into the runnable state and subsequently in the
running state. This happens when the thread is suspended,
sleeping or waiting in order to satisfy certain requirements.
Dead state: it is the last stage of a thread .A running thread
ends its life when it has completed executing its run ( )
method. It is a natural death.
Interthread Communication :
Inter thread communication in Java is done by means of three
methods.
They are wait(),notify() and notifyAll() methods.These
methods are called only from a synchronized method.

************** E N D **************

18
String Handling

String is an array of characters in many programming


languages.In Java String is also an array of characters.
But mainly a String is a class in Java.It is a predefined class
in java.lang package.
Java.lang package is a default package in Java.
There are two String Handling classes available in Java
namely
String
StringBuffer
Both String and StringBuffer are final classes.
Both these classes are available in java.lang package.
String :
It is a final class in java.lang package.
A String class is an object in Java.
A String is immutable, which means that it is fixed and the
contents of a String are always constant.
String constructors :
We can create an object of a String class by different ways
by using different types of constructors.
String s1=new String()
String s2=new String(“program”);
String s3=new String(s2);
String s4=”program”;
char name[]={‘J’,’I’,’T’,’M’};
String s5=new String(name);
There are many methods available in String class.

19
Some of the important methods are:
length():
This method is used to find the length or size of a
String.This method returns number of characters present in
the given String.
Syntax of the method:
int length()
Eg:
String s=”CoreJava”;
int i=s.length();
length() returns the length of the string and its length is
stored in i which is 8
concat():
This method is used to join or concat two strings.
The return type of this method is String.
This method takes one parameter which is also a String
String concat(String str)
Where str is the String joined to the given String.
Eg:
String s1=”Java”;
String s2=”Program”;
String s3=s1.concat(s2);
Where the output of s3 is JavaProgram
Concatenation operator(+):
The operator “+” is called a concatenation operator.
It is similar to concat() method.
In Java + is used to join any strings.
Eg:
String s1=”Java”;
String s2=”Program”;
String s3=s1+s2;

20
Where the output of s3 is JavaProgram
toLowerCase():
This method is used to convert upper case letters of a String
to lowercase.The return type of this method is String.
String toLowerCase()
Eg:
String s=”JAVA PROGRAM”;
The output of
s.toLowerCase() is java program
toUpperCase():
This method is used to convert lower case letters of a String
to uppercase.The return type of this method is String.
String toUpperCase()
Eg:
String s=” java”;
The output of
s.toLowerCase() is JAVA
trim():
This method is used to filter white spaces before and after a
given String.
This mehod is not used to filter white spaces between any
two words of a String.
The return type of this method is String
String trim()
String s=” Learn Java Basics “;
The output of
s.trim() is Learn JavaBasics
replace():
This method is used to replace a given character of a String
with another new character . The return type of this method
is String.

21
This method replaces the occurrence of the given character
through out the String by the new character.
String replace(char original,char new)
Eg:
String s=”Liver”;
The output of
s.replace(‘L’,’R’) is River
String Comparision Methods:
There are three types of String Comparision in Java.
They are :
(i)equals()
(ii)==
(iii)compareTo()
equals():
This method is used to compare actual contents of the two
strings.The return type of this method is a boolean value.
boolean equals(String s)
Eg:
String s1=new String(“rama”);
String s2=new String(“jaya”);
String s3=new String(“rama”);
String s4=new String(“RAMA”);

The output of
if(s1.equals(s2)) is false
if(s1.equals(s4)) is false

if(s1.equals(s3)) is true
equalsIgnoreCase():
This method is used to compare actual contents of the two
strings same as equals() except that it neglects case
sensitiveness of letters.

22
Eg:
String s1=new String(“rama”);
String s2=new String(“RAMA”);
The output of
if(s1.equals(s2)) is false
if(s1.equalsIgnoreCase(s3)) is true
compareTo():
This method is used to compare two strings depending on the
ASCII values of the characters of the string.
The return type of this method is int.
int compareTo(String s)
Eg:
String s1=”A123”;
String s2=”C123”;
String s3=”A123”;
It returns,
<0 if s1 is less than s2 and the output of
S1.compareTo(s2) is -2
>0 if s1 is greater than s2 and the output of
s2.compareTo(s1) is 2
=0 if s1 is equal to s2 and he output of
s1.compareTo(s3) is 0
Character Extraction:
The String class provides a number of ways in
which characters can be extracted from a String object.There
are many methods used to extract characters from a
String.The important method is charAt()
charAt():
This method is used to extract a single character from a
String.The return type of this method is char.
char charAt(int where)
Here, where is the index of the character.

23
Eg;
String s=”ABCDEF”;
s.charAt(2);
where the output is C,since at location 2 there is character C.
Modifying a String:
There are many ways of modifying a String.Mostly
used modifying method is substring().
substring():
This method is used to return a substring of the given String
starting from the startindex of the given method.
The return type of this method is also a String.
This method is overloaded.
(i)String substring(int startindex)
It returns a substring starting from startindex to the end of
the String.
Eg:
String s=”Learn from the Basic Concepts”;
012345---posions of characters in the String
The output of
s.substring(5) is from the Basic Concepts
(ii)String substring(int startindex,int endindex):
It returns a substring starting from startindex upto the end of
the end index without including endindex.
Eg:
String s=”Learn from the Basic Concepts”;
0123456789
s.substring(5,9) is from
In this character in the location of 9 will not be included.
StringBuffer:It is a final class in java.lang package.
A StringBuffer is mutable,which means that which means
that it is not fixed and the contents of a StringBuffer may

24
change.It is dynamic in nature,where we can insert any
character at any location.
A StringBuffer class stores an additional memory for 16
characters.
There are some methods which are available only in
StringBuffer class only.Some of the important methods are:
capacity():
This method is used to return than memory
capacity of a StringBuffer.The return type of this method is
int.

Eg:
StringBuffer sb1=new StringBuffer();
StringBuffer sb2=new StringBuffer(“ABCDE”);
Sb1.length() is 0 and sb2.length() is 5
sb1.capacity() is 16 where as
sb2.capacity is 21
append():
This method is similar to concat() method in
String class.This method is used to join any string to the
StringBuffer.
The return type of this method is StringBuffer.
StringBuffer append(String s)

Eg:
StringBuffer sb=new StringBuffer(“Learn”);
Sb.append(“Basics”);
Where the output is LearnBasics
reverse():
This method is used to reverse the characters of a
given StringBuffer.The return type of this method is again a
StringBuffer.

25
StringBuffer reverse()
Eg:
StringBuffer sb=new StringBuffer(“ABCDEF”);
sb.reverse();
Where the output is FEDCBA

******* E N D **********

26
Exploring java.lang
java.lang package is the default package in Java
and it is automatically imported into all Java programs.
There are many classes available in java.lang
package.Some of the important classes are :
Number
Math
Object
Runtime
String
StringBuffer
System
Thread
ThreadGroup
Throwable
Some of the important interfaces are :
Cloneable
Comparable
Runnable

Simple Type Wrappers :

27
Java uses simple data types like int,float,double,char etc…
But these simple types are not objects. Java provides
Wrapper classes to convert simple types to objects.
Wrapper classes:In java all are objects except the primitive
data types.If we want to access primitive data types as
objects we should wrap the primitive data types within a
class.
There are 6 Wrapper classes.They are the sub classes of
Number.They are...
Double,Float,Byte,Short,Integer and Long.
Double d=12.33;
Double dd=new Double(d);
Int i=555;
Integet ii=new Integer(i);
float f=12.33f;
Float ff=new Float(f);
Runtime :
The Runtime class encapsulates the run-time
environment.We cannot instantiate a Runtime object.we can
get an object of Runtime class by calling method
Runtime.getRuntime();

28
Memory Management:
Even though Java provides automatic garbage
collection,sometimes you will want to know how large the
object heap is and how much of it is left. To obtain these
values, use totalMemory() and freeMemory() methods
defined in Runtime class.
Object :
Object is the super class of all Java classes.
There are many methods available in Object class.
clone() method is used to create a duplicate copy of the
object on which it is called.Only classes that implements
Cloneable interface can be cloned. Cloneable interface
defines no members and it is a marker interface.
Thread :
A Thread is a predefined class in java.lang package. It is
a separate path of execution in a program.
Java uses Threads for implementing Multi Threading in
Java.By using a Thread we can create our own threads.

Runnable :

29
This is an interface that must be implemented by any
class that will initiate a separate thread of
execution.Runnable defines one abstract method called,run(),
which is the entry point to the thread.
ThreadGroup :
A ThreadGroup is a class, which creates a group of
threads.This offer a convenient way to manage groups of
threads as a unit.

************** E N D *********

30
Module-III

Java.util
It is the package which is mainly based on Collections.
A Collection is a group of objects.Collection Frame work
standardises the way in which groups of objects are handled
by ur programs.These are available in java.util package.
Some imp. classes in java.util package.
ArrayList
HashMap
HashSet
TreeSet
HashTable
LinkedList
StringTokenizer
Vector
Stack
Some imp. interfaces in java.util package are:
Collection
Enumeration
Iterator
List
Map
Set
Collection interface is the foundation upon which the
collections framework is built.
A collection can not directly store values of type
int,char,double etc..If you want to
store such objects,you have to use primitive wrapers.

31
List :The List interface extends Colletion and declares the
behavior of a collection that stores a sequence of elements.A
List may contain duplicate elements.
Set : A Set extends Collection and declares the behavior of a
collection that does not allow duplicate elements.
LinkedList:The LinkedList class extends
AbstractSequentialList and implements the List
interface.
ArrayList : ArrayList class extends AbstractList and
implements the List interface.ArrayList supports dynamic
arrays that can grow as needed.It can dynamically
increase or decrease in size.ArrayList are created with an
initial size.when this size is exceeded ,it is automatically
enlarged.When objects are removed,the array may be shrunk.
HashSet : HashSet extends AbstractSet and implements the
Set interface.In a HashSet the elements are not stored in a
sorted order.
TreeSet : TreeSet provides an information of the Set
interface that uses a tree for storage.
Objects are stored in sorted,ascending order.Access and
retrieval times are quite fast,which makes TreeSet an
excellent choice when storing large amounts of sorted
information that must be found quickly.
Iterator : An Iterator interface is used to cycle through the
elements in a collection.
This is also done by a ListIterator interface.Iterator enables
you to cycle through a collection,obtaining or removing
elements.

ListIterator:
ListIterator extends Iterator to allow bidirectional traversal of
a list.

32
Map : A Map interface is an object that stores associations
between keys and values or key/value pairs.Given a key we
can find its value.Both keys and values are objects.The
keysmust be unique,but the values may be duplicated.Some
may accept a null key and a null value.Map.Entry describes
an element(key/value pair)in a map.This is an inner class of
Map.
Enumeration : Enumeration interface defines the methods
by which you can enumerate(obtain one at a time)the
elements in a collection of objects.This is superceded by
Iterator.
Enumeration has two methods.
boolean hasMoreElements()
Object nextElement()
Vector : Vector implements a dynamic array.It is similar to
ArrayList, but Vector vector is synchronised.A Vector
extends AbstractList and implements the List interface.
Stack : Stack is a subclass of Vector that implements a Last-
In,First-Out(LIFO) stack.
There are two opearation in Stack.Push n Pop operation.Push
operation adds an object to the
stack n Pop operation deletes an object from stack.
Dictionary : It is an abstract class that represents a key/value
pair like a Map.
HashTable : HashTable class is similar to a HashMap,but
HashTable is synchronized.
HashTable stores key/value pairs in a hash table.When using
a HashTable,you specify an object that is used as a key,and
the value that you want linked to that key.
StringTokenizer:It is mainly used for parsing.To use a
StringTokenizer,you specify an input string and a string that
contains Delimiters.Delimiters are characters that seperate

33
tokens.Each character in the delimiters string is considered a
valid delimiter.For example ",;:"sets the delimiters to
comma,semicolon,and colon.
The Collection Algorithms:
The collections framework
Defines several algorithms that can be applied to collections
and maps.These algorithms are defined as static methods
within the Collections class.Several of the methods can throw
a ClassCastException,which occurs when an attempt is made
to compare incompatible types.
The Legacy classes and Interfaces:
Legacy classes and interfaces are sysnchronized.But
none of the collection classes are synchronized.The legacy
classes defined by java.util package are
Dictionary
Hashtable
Properties
Stack
Vector
There is only one legacy interface called Enumeration
Random:
Random class is a generator of pseudorandom numbers.

Observable:
The Observable class is used to create sub classes that
other parts of your program can observe.When an object of
such a sub class undergoes a change, observing classes are
notified.
Observing classes must implement the Observer
interface, which defines the update() method.

34
****** E N D ******

35
Java.io
java.io is a package in Java to perform input and output
operations.
Stream is an abstraction that either produces or consumes
information.A stream is linked to a physical device by the
java i/o system.
System class defines three predefined stream variables
namely in,out,err
System.out refers to the standard output stream.By default,
this is the console.System.err refers to the standard error
stream,which is also the console by default.System.in refers
to standard input,which is the keyboard by default.
Streams are two types.Byte streams and Character
streams.
(i)Byte Streams :
Byte streams provide a convenient means for handling
input and output of bytes. Byte streams are used when
reading or writing binary data.
Byte streams are defined by two classes namely
InputStream and OutputStream

(ii)Character Streams :
Character streams provide a convenient means for
handling input and output of characters.
Character streams are defined by two classes namely
Reader and Writer.

Serialization:
Serialization is the process of writing the state of an
object to a byte stream.This is useful when you want to save

36
the state of your program to a persistent storage area, such as
a file.
Serialization is mainly needed to implement
Remote Method Invocation (RMI)
Serializable :
A Serializable is an interface.This interface has no
variables or methods. It is also called as Marker interface.
A Serialazable interface is used to make a class as
serialized.If a class is serialazable,all of its subclasses are
also serializable.

****** E N D ******

37
Networking:
A network is a set of computers and peripherals, which are
physically connected together. Networking enables sharing
of resources and communication. Internet is a network of
networks.
Java applets can be downloaded from a website. Networking
in java is possible through the use of java.net package.
Protocols: Communication between computers in a network
or a different networks require a certain set of rules called
protocol. Java networking is done using TCP/IP protocol.
Some of the different kinds of protocols available are HTTP,
FTP, SMTP.
HTTP: hyper text transfer protocol enables interaction with
the internet. It is the underlying protocol of www
FTP: file transfer protocol enables transfer of files between
computers.
SMTP: SimpleMailTransferProtocol is used to send email
between machines.
Client /Server: A computer which requests for some service
from another computer is called client. The one that
processes the request is called a server.

38
Internet Address: Every computer connected to a network
has a unique IP address. An IP address is a 32- bit number
which has four numbers separated by period. A sample IP
address is given below.
80. 0 . 0 . 53
Domain Naming Service: it is very difficult to remember a
set of numbers (IP address) to connect to the internet .The
DomainNaming Service (DNS) is used to overcome this
problem. It maps one particular IP address to a string of
characters Eg: www.yahoo.com.
Port: It is a number given for a particular application
running in a system.
For a system there will be only one connection to
network, but there could be many applications running in the
system. So, for communicating with each of these
applications unique number is given. This number is known
as a port number.
Each port is identified by a number from 0 to 65, 535.
Each port can be allocated to a particular service port number
.7 is assigned for ECHO, 21 is assigned for FTP, 23 is for
Telnet, 25 is for e-mail, 80 for HTTP and 1099 for RMI

39
registry.
Networking classes and interfaces: All these classes and
interfaces are contained in java.net package.
DatagramPacket,DatagramSocket,InetAddress,Socket,
ServerSocket, URL, URLConnection etc., are some of the
important classes in networking.
FileNameMap,SocketImplFactory, SocketOptions are
important interfaces in this networking.
Whois: It is a simple directory service protocol. It was
originally designed to keep track of administrators
responsible for internet hosts and domains.
A Whois client connects to one of several central
servers and requests directory information for a person or
persons. It can usually give you a phone number and an
e-mail address.

SocketBasics:
A socket is a connection between two hosts. It can
perform seven basic operations.
1.Connect to a remote machine.
2.Send data

40
3.Receive data
4.Close a connection
5.Bind a port
6.Listen for incoming data
7.Accept connections from remote machines on the bound
port.
Java’s Socket class, which is used by both clients and
servers, has methods that correspond to the first four of these
operations. The last three are needed only by servers which
wait for clients to connect to them. They are implemented by
the ServerSocket class.
Socket class is used to perform client side TCP
operations.
ServerSocket class contain every thing you need to write
servers in Java.

URL: is called as Uniform Resource Locator and is a


reference or an address to a resource on the internet.
A URL has two main components.
1. Protocol Identifier 2. Resource name.
Eg: The following is an example of a URL which addresses

41
the java web site hosted by SunMicroSystem .
http://java.sun.com.
Protocol Identifier is http
Resource name is java.sun.com
URL Connection: it is a general purpose class for accessing
the attributes of a remote resource. Once you make a
connection to a remote server, you can use URLConnection
to inspect the prosperities of the remote object before
actually transporting it locally.
TCP (Transmission Control Protocol)
It is a connection based protocol that provides a reliable
flow of data between two computer, this is analogous to
making phone call. It provides point-to-point channel for
application that require reliable communication HTTP, FTP,
Telnet etc., are TCP protocols.

UDP (User Datagram protocol)


It is a connection less oriented protocol. It sends
independent packets of data from one computer to another
with no guarantees about arrival.This is analogous to sending
a letter through the postal service

42
DatagramPacket,DatagramSocket etc., are UDP type
connection less protocols.
Differencec Between TCP n UDP
TCP UDP
It is a connection oriented It is a connectionless oriented
protocol protocol
It is similar to Telephone It is similar to sending letter from
Post office
Overheads are high Overheads are low
HTTP,FTP,SMTP etc… DatagramPacket,DatagramSocket
are Connection oriented etc…are Connectionless oriented
protocols protocols
It is more reliable Less reliable
Order guaranteed Order of deliver not guaranteed

Delivery guaranteed Delivery not guaranteed

************ E N D **********

43
Applet
An Applet is a Java program which runs from a Java
enabled web browser.
It also runs by using an appletviewer which is a tool from
jdk(Java Development Kit)
Applet is a class in java.applet package.
Writing an Applet program:
• We have to import two packages to write an Applet
Program.Those packages are java.awt and java.applet
• There is no main() method in an Applet program.It has
an init() method where the execution of the Applet
begins.
• We have to write an <Applet> tag in order to see the
output of an Applet Program.
• <Applet> tag contains three mandatory attributes
namely code,width and height
• We can use an <Applet> tag in the same Java file where
your Applet program is written by commenting it.We
can also separately use this <Applet> tag in a html file.
Applet Architecture :
Applet is a window based program which runs by using
a Java compatible browser or an appletviewer. It’s
architecture is different from a console based application
programs.

Applets are event driven.That is why we have to import


java.awt package also to write Applet programming. All

44
Applets runs in a window. They have init() method instead of
main() as in console based programs.
Life cycle of an Applet:
There are four stages in the life cycle of an
Applet.These life cycle methods will be automatically
called by the container or browser where the Applet is
running.
The four life cycle methods are:
(i)init()
(ii)start()
(iii)stop()
(iv)destroy()
init():
This is the first method called when an Applet is
initialized.This method is called exactly once.During this
method initialization of the Applet will generally be done.
start():
This is the next method called immediately called after the
init() method.This method will be called one or more
number of times.
stop():
This method is called when an Applet moves from one
page to another page.This method will also be called one
or more number of times.

destroy():
This is the last method called by an Applet.This method is
used to relieve the memory resources used by the
Applet.This method will also be called exactly once.
Applet Skeleton :

45
There are five methods defiend in the skeleton of an
Applet. They are :
(i)init()
(ii)start()
(iii)stop()
(iv)destroy()
(v)paint()
The first four methods are also called life cycle methods
of an Applet.
paint() method is called when an Applet’s window must be
restored. In this method we can display any thing on the
Applet window.
This method is called when each time Applet’s output is
redrawn.
Note :
There are three interfaces in java.applet package.They
are AppletContext, AudioClip and AppletStub
AppletContext :
AppletContext is an interface that lets you get information
from the Applet’s execution environment.
The context of the currently executing Applet is obtained by

46
a call to the getAppletContext() method defined in Applet
class.
showDocument()
Within an Applet,once you have obtained the Applet’s
context,you can bring another document into view by calling
showDocument() method. This method has no return values
and throws no exception if it fails.
Writing a SimpleApplet Program:

/*Writing SimpleApplet Program which displays a


message on the Applet window*/
import java.awt.*;
import java.applet.*;
/*<Applet code=”SimpleApplet” width=300
height=400></Applet>*/
public class SimpleApplet extends Applet
{
public void paint(Graphics g)
{
g.drawString(“Welcome to Applets”,100,200);
}
}
Passing Parameters to Applets :
We can send parameters to Applet from a HTML file using
<Param> tag.A <Param> tag contains name and value as a
pair and by giving name we can get the value associated with

47
that name.
getParameter() of Applet class is used to retrieve the value of
a given name in the <Param> tag.
/*Program in which a HTML file passes parameters to an
Applet and those values are displayed in the Applet
Window.*/
import java.awt.*;
import java.applet.*;
/*<Applet code=”ParamApplet” width=400 height=600>
<param name=”Company1” value=”Infosys”></param>
</Applet> */
public class ParamApplet extends Applet
{
Public void paint(Graphics g)
{
String s=getParameter(“Company1”);
g.drawString(s,200,300);
}
}
Explanation:
The output of the above program in an Applet window

48
is Infosys
Note :
There are three interfaces in java.applet package.They
are AppletContext, AudioClip and AppletStub
AppletContext :
AppletContext is an interface that lets you get information
from the Applet’s execution environment.
The context of the currently executing Applet is obtained by
a call to the getAppletContext() method defined in Applet
class.
showDocument()
Within an Applet,once you have obtained the Applet’s
context,you can bring another document into view by calling
showDocument() method. This method has no return values
and throws no exception if it fails.

*********** E N D *********

49
Event Handling

In AWT except Label component all other


components have Listeners.
Event Handling is the technique in which a given component
registers with a Listener and this Listener Handles the event
fired by that Component.
Event Handling Models:
Event Handling models are of two types
They are :
Hierarchical Event Model
Delegation Event Model
Hierarchical Event Model:
In this type of model, the presentation logic and
business logic are not clearly separated from each other. This
method is now out dated.

Delegation Event Model :


In this type of model, the presentation logic and
business logic are clearly separated from each other.
Hence both presentation and Business logic are independent
of each other and the changes made in one logic has no effect
on other logic.
Event:
An event is an object that describes a state change in a
source.
An Action performed on a component is an Event.Some of
the activities that cause events to be generated are pressing

50
a button,entering a character in a text field,selecting an
item in a choice,double clicking an item in a list,clicking
the mouse etc..
Event Source:
The Component on which the event has occurred is called
the Event Source object.
Event class :
It is the class which is generated by the component
when Event Handling is done.
Suppose when a Button component is clicked,it generated
ActionEvent class.
There are many types of Event classes available in
java.awt.event package.Some of the Event classes are:
Event Classes
ActionEvent class is occurred
(i)When U click a button an Action Event occurs.
(ii)Double clicking a List Item.
(iii)When U click a Menu Item.
Adjustment Event class is occurred
When a Scrollbar is manipulated
TextEvent class is occurred
When U change the contents of the Text field or Text
area.
Item Event class is occurred
Generated when a check box or list item is clicked.It
also occurs when a choice selection is made.
ComponentEvent class is occurred
Generated when a component is
hidden,moved,resized,or becomes visible
ContainerEvent class is occurred

51
When U Add a Component or Remove a Component
from a Container
FocusEvent class is occurred
When a component is receiving the focus and losing
focus.
WindowEvent class is occurred
Generated when a window is
activated,closed,deactivated,deiconified,iconified,
opened,or quit
KeyEvent class is occurred
Generated when input is received from keyboard
MouseEvent class is occurred
Generated when the mouse is
dragged,moved,clicked,pressed,or released.It also
generated when the mouse enters or exits a
component
Event Listener interface :
It is the listener which is registered with a given
component when an event occurs.
Suppose when a Button is clicked, ActionListener is
registered with it and the corresponding method of this
ActionListener interface to be implemented is
actionPerformed() method
Adapter Class:
An Adapter Class is a class that already implement all the
methods in its corresponding interface.
An Adapter class provides an empty implementation of all
methods in an event listener interface.Adapter classes are
used when only some of the events are to be received and
processed that are handled by a particular listener interface.
For example,MouseMotionAdapter class has two
methods.mouseDragged() and mouseMoved().The signatures

52
of these empty methods are defined in the
MouseMotionListener interface.If only mouse dragged
events are to be performed then simply extend
MouseMotionAdapter and implement mouseDragged().The
empty implementation of mouseMoved() would handle the
mouse motion events.
Commonly used Adapter classes in java.awt.event package
and the interfaces are:
MouseAdapter class and the corresponding Listener
interface is MouseListener
MouseMotionAdapter class and the corresponding Listener
interface is MouseMotionListener
WindowAdapter class and the corresponding Listener
interface is WindowListener

********* E N D **********

53
Module – IV

AWT

AWT , Abstract Window Toolkit in Java is used to


write GUI programs.Today most of the front ends are
using Graphical User Interface(GUI) programming due to
many benefits such as user friendly,attractive,uses
different colors,uses many pictures,uses images,simulates
real world components etc…
Java provides powerful GUI programming by
using AWT.
The super class of all AWT components is Component.The
sub class of Component is Container.
Container has two sub classes namely Window and Panel
Window:
Window is the top level class which sits directly
on the desktop.It has again two sub classes namely Frame
and Dialog.
Frame:
It is the sub class of Window.A Frame contains
title,background,foreground,other controls like
minimize,maximize etc…
Most of the AWT Programs are using a Frame window as
their container.
The default Layout Manager of a Frame Window is a
BorderLayout.
The two important methods used in a Frame class are
void setSize(int width,int height)

54
where width and height are the dimensions of the Frame in
pixels.
void setVissible(boolen b)
where b is a boolean data type and the Frame window will
be visible if boolean value is true
Panel :
A Panel is a super class of Applet.
Generally a Panel is used as a subcontainer of
componenets.
The default Layout Manager of a Panel and Applet is a
FlowLayout
Creating a Frame Window:
We can create a Frame Window by importing java.awt
package and extending a Frame class.
//Sample Frame Window program
import java.awt.*;
class MyFrame extends Frame
{
public static void main(String args[])
{
MyFrame mf=new MyFrame();
Mf.setTitle(“Frame Window Example”);
mf.setSize(200,300);
mf.setVisible(true);
}
}
Explanation:
The above program creates a Frame Window with
title name as Frame Window Example with pixels as 200 and
300.
Working with Graphics:

55
Graphics is a class available in java.awt
package.There are many methods available in Graphics
class.This Graphics class is used to display anything on the
Frame or Applet Window by using the method called paint()
method.
Syntax of a paint() method:
public void paint(Graphics g)
There are many methods available in Graphics class.
void drawstring() is used to display any String or Message on
the Applet or Frame window.
We can use Color and Font classes in Graphics class.
Color and Font are also the predefined classes in java.awt
package.
Color:
It is class in java.awt package.
We can create an object of a Color class by using the
constructor
Color(int red,int green, int blue)
Where red,green and blue are the integer values lies
between 0 and 255.

Eg:
Color c1=new Color(0,0,0);
Color c2=new Color(255,255,255);
Color c3=new Color(100,50,200);
Color c4=new Color(20,100,240);
Where c1,c2,c3 and c4 are different Colors.
Font:
It is another class in java.awt package.
We can create an object of a Font class by using the
constructor

56
Font(String s,int style,int size)
Where s is the name of the Font like
TimesRoman,Sanserif,Monospaced etc…
Where style is BOLD,ITALIC,PLAIN or combination
of styles and size is the size of Font
Eg:
Font f1=new Font(“TimesRoman”,Font.BOLD,40);
Font f2=new Font(“Monospaced”,Font.ITALIC,70);
Where f1,f2 are different objects of class Font

//Program working with Graphics by using Color and


Font classes.

import java.awt.*;
import java.applet.*;
/*<Applet code=”NameApplet” width=300
height=500></Applet>*/
public class NameApplet extends Applet
{
public void paint(Graphics g)
{
Font f=new Font(“TimesRoman”,Font.BOLD,50);
g.setFont(f);
Color c=new Color(100,200,60);
g.setColor(c);
g.drawString(“Working with Graphics”,100,200);
}
}

Controls used in AWT:


There are many controls used in AWT.
Some of the important controls used in AWT are

57
Label
Button
Checkbox
Choice
List
TextField
TextArea
Except Label Component all other Components
have listeners.
Layout Managers :
It is essential to align the components properly in a
given Container.Alignment of Components is very
difficult .This difficulty is avoided by using a proper Layout
Manager.
There are many types of Layout managers used in
AWT.Some of the important Layout Managers are
(i)BorderLayout
(ii)FlowLayout
(iii)GridLayout
(iv)CardLayout
(v)GridbagLayout
Reflection:
Reflection is the ability of a program to analyze itself. The
java.lang.reflect package provides the ability to obtain
information about the fields,constructors,methods, and
modifiers of a class.
Reflection is used to determine dynamically the
characteristics of a component
Remote Method Invocation(RMI) :

58
Remote method invocation(RMI) is a distributed
application developed in Java.By using RMI, we can invoke
the method available in a remote machine.\
In RMI we have two machines where one machine acts
as a Server and another machine acts as a Client.
To run an RMI application, we have to start RMIRegistry
and we are using rmic compiler to create stubs and skeleton.

**************** E N D ********

59
Swing
Swing is an extension of AWT components in Java. Even
though Java is platform independent language AWT
components are platform dependent.Hence the look and feel
of AWT Components varies from one operating system to
other.
Swing components are platform independent and hence
look and feel of these components is same on all operating
systems.In addition Swing includes have more features such
as TabbedPanes,Trees,Tables etc…
In Swing the visible components starts with “J” and the
super class of all components is JComponent.
Some of the important Components in Swing are
JLabel
JButton
JCheckBox
JRadioButton
JCombobox
JList
JScrollPane
JTextField
JPassword
JTextArea
JOptionPane
JTable
JTree
JTabbedPane
NOTE:
We have to import java.awt and javax.swing package to write
Swing programs
All the above Swing Components extends JApplet.

60
The main difference between Applet and JApplet is,in Applet
we are directly adding components to the Applet where as in
JApplet we are adding components to the ContentPane.
JApplet:Swing version of Applet.All swing visible
components extends JApplet
Icons and Labels:
InSwing,icons are encapsulated by the ImageIcon class.Two
of its constructors are
ImageIcon(String filename) where filename is the name of
the image
ImageIcon(URL url) where url is the location of the image.
JLabel:
We can create an object of a JLabel component by using the
constructor
JLabel() which is an empty constructor
JLabel(String s) where s is the name of the label
JTextField :
We can create an object of a TextField in swing by using the
constrcuctors
JTextField(int width) where width is the width of the text
field
JTextField(String s) where s is a String displayed in the text

61
field.
JButton :
We can create an object of a Button in swing by using the
constructors
JButton() where it creates a button without any name
JButton(String s) where it creates a button where s is it’s
name
JComboBox :
It is similar to Choice in AWT.
We can create an object of a JComboBox by using it’s
default constructor.
JComboBox()
We can add item to the combo box by using
addItem(Object obj) method
TabbedPane :
It is a component that appears as a group of folders in a file
cabinet.Each folder has a title.When a user selects a folder,
its contents become visible.Only one of the folder is selected
at a time.Tabbed panes are generally used for configuration
options.
We can create an object of a Tabbed Pane by using the class

62
default constructor of JTabbedPane class
ScrollPane:
ScrollPane is a component that presents a rectangular area in
which a component may be viewed.Horizontal and /or
vertical scroll bars may be provided if necessary.
We can create aa object by using a default constructor
JScrollPane()
Tree:
A Tree is a component that presents a hierarchical view of
data.A user has the ability to expand or collapse individual
subtrees in this display.
A Tree in swing is obtained by extending JTree which
extends JComponent
Table :
Table is a component that displays rows and columns of
data.You can drag the cursor on column boundaries to resize
columns.
We can create a Table in swing by extending JTable which
extends JComponent.
************ E N D *********

63
JDBC(Java Data Base Connectivity)
Jdbc is a technology used to connect a Java program to any
data base.
We have to import java.sql package for writing JDBC
programs in Java
Types of Drivers used in JDBC :
There are four types of drivers supplied by Sun
Micro Systems to connect a Java Program to any data
base.
They are :
Type I:
JDBC-ODBC Bridge Driver
Type II
Native protocol partly Java Driver
Type III
Net protocol pure Java Driver
Type IV
Native protocol pure Java Driver
Above all Jdbc-Odbc Bridge Driver is the

64
simplest Driver used to connect to any data base.
Steps in writing a JDBC program:
The following steps are followed while writing a JDBC
program.
Step 1:
Loading the driver.The statement used for this step is
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
Step 2:
Getting the Connection object
Connection
con=DriverManager.getConnection(“jdbc:odbc:dsn”,”scott”,
”tiger”); which is used to connect to Oracle data base
Step 3:
Creating the Statement object
Statement st=con.createStatement();
Step 4:
Using the sql statements
int i=st.executeUpdate(“CREATE TABLE ECEStudent(rno
number,name varchar(10))”);

/*Writng a JDBC program which is used to create a table

65
ECEStudent and enter any two values */
import java.sql.*;
class Jdbcprogram
{
public static void main(String args[])
{
try
{
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
Connection
con=DriverManager.getConnection(“jdbc:odbc:dsn”,”scott”,
”tiger”);
Statement st=con.createStatement();
int i=st.executeUpdate(“CREATE table ECEStudent(rno
number,name varchar(10))”);
int j=st.executeUpdate(“INSERT into ECEStudent
values(111,’xyz’);
int k=st.executeUpdate(“INSERT into ECEStudent
values(222,’abc’);
System.out.println(“Your operation is successfully done”);
}

66
catch(Exception e)
{
System.out.println(“Error is “+e);
}
}
}

**************** E N D ***********

67
68