Java Notes 1
Java Notes 1
HISTORY OF JAVA
Java is an object-oriented programming language developed by
Sun Microsystems in the early 1990s. Java applications are typically compiled to
bytecode, although compilation to native machine code is also possible. At runtime,
bytecode is usually either interpreted or compiled to native code for execution, although
direct hardware execution of bytecode by a Java processor is also possible.
The language itself derives much of its syntax from C and C++ but has a simpler object
model and fewer low-level facilities. JavaScript, a scripting language, shares a similar
name and has similar syntax, but is not directly related to Java.
Java is a Platform
There's another problem with distributing executable
programs from web pages. Computer programs are very closely tied to the specific
hardware and operating system they run. A Windows program will not run on a computer
that only runs DOS. A Mac application can't run on a Unix workstation. Java solves the
problem of platform-independence by using byte code. The Java compiler does not
produce native executable code for a particular machine like a C compiler would. Instead
it produces a special format called byte code. Java byte code written in hexadecimal, byte
by byte, looks like this:
CA FE BA BE 00 03 00 2D 00 3E 08 00 3B 08 00 01 08 00 20 08
Java programs that have been compiled into byte code still need an interpreter to execute
them on any given platform. The interpreter reads the byte code and translates it into the
native language of the host machine on the fly. The most common such interpreter is
Sun's program java (with a little j). Since the byte code is completely platform
independent, only the interpreter and a few native libraries need to be ported to get Java
to run on a new computer or operating system. The rest of the runtime environment
including the compiler and most of the class libraries are written in Java.
BYTE-CODE
Bytecode is a binary representation of an executable program
designed to be executed by a virtual machine rather than by dedicated hardware. Since it
is processed by software, it is usually more abstract than machine code. Different parts of
a program are often stored in separate files, similar to object modules. A bytecode
program is normally executed by parsing the instructions one at a time. This kind of
bytecode interpreter is very portable. Some systems, called dynamic translators, or "just-
in-time" (JIT) compilers, translate bytecode into machine language as necessary at
runtime: this makes the virtual machine unportable, but doesn't lose the portability of the
bytecode itself. For example, Java and C# code is typically stored in bytecoded format,
which then uses a JIT compiler to translate the bytecode to machine code before
execution.
Differences between the C++ and Java
The differences between the C++ and Java programming languages can be traced to their
heritage.
1
handling, scoped resource management, and generic programming, in particular.
It also added a standard library that includes generic containers and algorithms.
• C++ supports goto statements; Java enforces structured control flow, and relies
on labelled break and labelled continue statements to provide some goto-like
functionality.
• C++ provides low-level features which Java lacks. In C++, pointers can be used to
manipulate specific memory locations, a task necessary for writing low-level
operating system components. Similarly, many C++ compilers support inline
assembler. In Java, such code has to reside in external libraries, and can only be
accessed through the Java Native Interface with a significant overhead for each
call.
• In C++, pointers can be manipulated directly as memory address values. Java does
not have pointers — it only has object references and array references
• In C++ one can construct pointers to pointers, while Java references only access
objects.
• Java has generics, whose main purpose is to provide type-safe containers. C++
has templates, which provide more extensive support for generic programming
• In C++ it is possible to have uninitialized primitive objects, Java enforces default
initialization.
• C++ is normally compiled directly to machine code which is then executed
directly by the operating system. Java is normally compiled to byte-code which
the Java virtual machine (JVM) then either interprets or JIT compiles to machine
code and then executes. In theory, dynamic recompilation can be used for either
language, particularly Java, but at present, both languages are rarely, if ever
dynamically recompiled.
2
C++ Java
Standard C++ library has a limited scope Extensive language-specific library (also
(containers, algorithms, file and console allows GUI programming, networking,
I/O) etc)
3
public class WelcomeToOOP {
// main method begins execution of Java application
public static void main( String args[] )
{
System.out.println( "Welcome to OOP" );
}
}
• Save the program file in your java programs directory giving it the name
WelcomeToOOP.java (it's important that the file name is the same as the public
class name, with the extension .java added).
• Compile the program by giving the following command at the dos/shell prompt
(this assumes you are in the same directory as the program file):
javac WelcomeToOOP.java
• If you list the directory (e.g. use dir or ls command) you should see the file
WelcomeToOOP.class this file contains the compiled byte code corresponding to
the WelcomeToOOP class.
• Run the program by giving the following command at the dos/shell prompt:
java WelcomeToOOP
• Java programmers often use an Integrated Development Environment (IDE),
which is a software package that supports writing code and running programs. A
variety of packages exist, such as NetBeans, JBuilder, BlueJ. The MSc OOP
course does not support the use of any of these systems. Use of a standard editor
and command shell will be perfectly adequate.
CLASSPATH Problems
If you get any message like this,
$ java HelloWorld
Can't find class HelloWorld
it probably means your CLASSPATH environment variable isn't properly set up. Make
sure it includes the current directory as well as the location where the classes.zip file was
installed. Under Windows you set the CLASSPATH environment variable with a DOS
command like
C:\> SET
CLASSPATH=C:\JDK\JAVA\CLASSES;c:\java\lib\classes.zip
You can also add this to your autoexec.bat file (Windows ME and earlier) or set it in the
environment variables tab of the System control panel (Windows NT and later) You
should of course point it at whichever directories actually contain your classes.
Applet
An applet is a special kind of Java program that a browser enabled with Java
technology can download from the internet and run. An applet is typically embedded
inside a web-page and runs in the context of the browser. An applet must be a subclass of
the java.applet.Applet class, which provides the standard interface between the applet
and the browser environment.
Swing provides a special subclass of Applet, called
javax.swing.JApplet, which should be used for all applets that use Swing components
to construct their GUIs.
By calling certain methods, a browser manages an applet life cycle, if an applet is loaded
in a web page.
Life Cycle of an Applet
Basically, there are four methods in the Applet class on which
any applet is built.
4
• init: This method is intended for whatever initialization is needed for your applet. It is
called after the param attributes of the applet tag.
• start: This method is automatically called after init method. It is also called whenever
user returns to the page containing the applet after visiting other pages.
• stop: This method is automatically called whenever the user moves away from the
page containing applets. You can use this method to stop an animation.
• destroy: This method is only called when the browser shuts down normally.
Or
APPLETs
Applet are small java program that are primarily used in internet
computing. They can be transport over the internet from one computer to another and run
using the applet viewer are any web browser that supports java.
An Applet like any application program can do many thing for us it can perform
arithmetic operation display graphics, play sounds, accepts user input, create animation,
and play attractive games etc.
Types of Applet :-
There are two types of Applet :-
i) Local
ii) Remote
i) Local Applet :-
An Applet develop locally and stored in a local system is known
as local Applet. When a web page is trying to find a local Applet. It does not need to use
the internet and therefore it does not require internet connection.
ii) Remote Applet :-
A Remote Applet is that which is developed by someone else
and stored on a remote computer connected to a internet. If internet our system is
connected to the internet. We can download via internet and run it.
Local Applet
Local computer
Loading local applets
Internet
5
Local computer(client) Remote applets Remote computer (server)
Start( )
Stop( )
Display Running Idle
Paint( ) Start( ) destroy( )
Exit of Browser
An Applet transition diagram
The Applet life cycle has following state :-
i) Born state ii) Running state
iii) Idle state iv) Dead state or destroyed
i) Born state :-
In this state applet enters the initialization state when it is first loaded .
this is achieved by calling in it method of applet class. At this stage we may do the
following if require :-
a) create object
b) needed by applets
c) set fo initial values
d) load images or fonds
e) set up colors
this state occurs only once in the applets life cycle.
ii) Running state :-
Applets enter in the running state when the system calls the start( )
method of applet class. This occurs automatically after the applet is initialized. This
state can enter into idle state.
iii) Idle state or stop state :-
In Applets becomes idle when it stops running, stopping
occurs automatically when we leave the page containing the current running applet. We
can also do so by calling the stop method explicitly. If we use a thread to run applet then
we must use stop method to terminate the thread.
iv) Dead state :-
An Applet is said to be dead when it is removed from memory. This
occurs automatically by invoking the destroy method. When we quit the browser like
initialization destroying stage occurs only once in the applet life cycle.
v) Display state :-
Applet moves to the display state whenever it performs some output
operation in the screen. This happens immediately after the applet enters into the running
6
state. The paint method is called to perform this task. Almost every applet will have paint
method.
Data Types
CHARACTER/STRING
BOOLEAN
DATE
• the Date class measures the milliseconds since Jan 1, 1970 and provides
supporting functions to interpret and manipulate date/times
7
ARRAYS
5. Major Constructs
6. Methods (functions)
Major Operators
8
numbers and assign to or strings)
first
++ -- quick increment x++ is like x = x + 1
(decrement)
&& Logical and, (a && b) if a is false, b is not evaluated (or
executed)
|| Logical or respectively.
(a || b) if a is true, b is not evaluated (or
executed)
a?b:c Conditional operator if boolean expr. "a" is true, use expr. "b",
otherwise use expr. "c"
Automatic Conversion
In Java type conversions are performed automatically when the type of the expression on
the right hand side of an assignment operation can be safely promoted to the type of the
variable on the left hand side of the assignment. Thus we can safely assign:
byte short int long float double
The symbol used here should be interpreted as "to a". For example:
Code: Java
// 64 bit long integer
long myLongInteger;
myLongInteger = myInteger;
The extra storage associated with the long integer, in the above example, will simply be
padded with extra zeros.
Code: Java
myInteger = (int) myLongInteger
This tells the compiler that the type of myLongInteger must be temporarily changed to a
int when the given assignment statement is processed. Thus, the cast only lasts for the
duration of the assignment.
9
Decision Making Statements
If –Else Condition
• compiler flags a = b as a problem (helps when remembering to use ==)
• outer brackets are mandatory around the full IF expression (same for while, etc.)
• using && (instead of &) causes short-circuit evaluation (i.e. if left operand is true,
right operand is not evaluated)
• using || (instead of |) causes short-circuit evaluation (i.e. if left operand is false,
right operand is not evaluated)
• ^ is the operator for XOR evaluation
class Hello
{
public static void main (String args[])
{
/* Now let's say hello */
System.out.print("Hello ");
if (args.length > 0)
{
System.out.println(args[0]);
}
else
{
System.out.println("whoever you are");
}
}
}
SWITCH Statement
• if the break is omitted at the end of a case clause, execution continues in the next
case statement (until a break or the end of the switch statement is reached)
• Switch does not support strings operands (with strings, the only choice is to use
long IF/ELSE/IF sequences)
Arrays
Arrays are probably the oldest and still the most generally effective means of
storing groups of variables. An array is a group of variables that share the same name and
are ordered sequentially from zero to one less than the number of variables in the array.
The number of variables that can be stored in an array is called the array's dimension.
Each Creating Arrays
There are three steps to creating an array, declaring it, allocating it and initializing it.
Declaring Arrays
Like other variables in Java, an array must have a specific type like
byte, int, String or double. Only variables of the appropriate type can be stored in an
array. variable in the array is called an element of the array.
some examples:
int[] k;
float[] yt;
String[] names;
Allocating Arrays
When we create an array we need to tell the compiler how many
elements will be stored in it. Here's how we'd create the variables declared above:
10
k = new int[3];
names = new String[50];
The numbers in the brackets specify the dimension of the array; i.e. how many slots it has
to hold values. With the dimensions above k can hold three ints, yt can hold seven floats
and names can hold fifty Strings. Therefore this step is sometimes called dimensioning
the array.
Initializing Arrays
Individual elements of the array are referenced by the array name
and by an integer which represents their position in the array. The numbers we use to
identify them are called subscripts or indexes into the array. Subscripts are consecutive
integers beginning with 0. Thus the array k above has elements k[0], k[1], and k[2].
k[0] = 2;
k[1] = 5;
k[2] = -2;
yt[6] = 7.5f;
names[4] = "Fred";
Multidimensional Arrays
Java lets you have arrays of three, four or more
dimensions. If you need more than three dimensions in an array, you're probably using
the wrong data structure. Even three dimensional arrays are exceptionally rare outside of
scientific and engineering applications.
class Fill3DArray
{
public static void main (String args[])
{
int[][][] M;
M = new int[4][5][3];
for (int row=0; row < 4; row++)
{
for (int col=0; col < 5; col++)
{
for (int ver=0; ver < 3; ver++)
{
M[row][col][ver] = row+col+ver;
}
} } }
}
11
Garbage collection
When an object is no longer referred to by any variable, java
automatically reclaims memory used by that object. This is known as garbage collection.
System.gc() method may be used to call it explicitly.
Memory allocation
Object is an instance of a class and it is a software unit that
combines a structured set of data with a set of operations for inspecting and manipulating
that data. When an object is created using new operator, memory is allocated to it.
Classes
Java has nested classes that are declared within the body of another class or interface. A
class that is not a nested class is called a top level class. An inner class is a non-static
nested class.
Classes can be declared with the following modifiers:
abstract – cannot be instantiated. Only interfaces and abstract classes may contain
abstract methods. A concrete (non-abstract) subclass that extends an abstract class
must override any inherited abstract methods with non-abstract methods. Cannot be
final.
• final – cannot be subclassed. All methods in a final class are implicitly final.
Cannot be abstract.
• strictfp – all floating-point operations within the class and any enclosed nested
classes use strict floating-point semantics. Strict floating-point semantics
guarantee that floating-point operations produce the same results on all platforms.
Note that Java classes do not need to be terminated by a semicolon (";"), which is
required in C++ syntax.
Scope
Can be used in a subclass to access inherited methods that the subclass has overridden
or inherited fields that the subclass has hidden.
Top level class access
By default, Java classes are accessible only within their own
package. This enables a package of classes to provide an API which performs functions
behind the scenes. Hidden classes support the work of publicly accessible classes.
12
When overriding a method, the method access modifier can't be made more restrictive—
to do so would break the interface contract of the parent class. Thus when overridden, a
public method must be declared public and a protected method cannot be given default
access. However, it is permissible to override a method to make it more accessible. Thus
when overriding, a default (package) access method can be declared as protected or
public and a protected method can be declared as public.
Example 1
public class Example1
{
// This is a Java class, it automatically extends the class Object
public static void main (String args[])
{
System.out.println("Hello world!");
}
}
Package
Encapsulation is a technique by which multiple related objects can be
grouped under one object. Java implements encapsulation by the use of Packages. A
package is a collection of classes and interfaces that provides a high-level layer of access
protection and name space management.
A Package is a group mechanism with two main purposes :-
Creating a Packages
A Java package can be created by simply using the package
identifier along with the package name as the first statement in any Java program file.
Syntax:-
Package packagename;
Constructors
The first method most classes need is a constructor. A constructor
creates a new instance of the class. It initializes all the variables and does any work
necessary to prepare the class to be used. In the line website x = new website();
website() is a constructor. If no constructor exists Java provides a default one, but it's
better to make sure you have your own. You make a constructor by writing a public
method that has the same name as the class. Thus our website constructor is called
website(). Here's a revised website class with a constructor that initializes all the
members to null Strings.
class website
{
String name;
String url;
String description;
public website()
{
name = "";
url = "";
description = "";
}
}
13
This is called method overloading or polymorphism. Polymorphism is a feature of object
oriented languages that lets one name refer to different methods depending on context.
The important context is typically the number and type of arguments to the method. In
this case we use the first version of the method if we have three String arguments and the
second version if we don't have any arguments.
If you have one or two or four String arguments to the constructor, or arguments that
aren't Strings, then the compiler generates an error because it doesn't have a method
whose signature matches the requested method call.
toString Methods
Print methods are common in some languages but most Java programs
operate differently. You can use System.out.println() to print any object. However
for good results your class should have a toString() method that formats the objects
data in a sensible way and returns a String.
class website
{
String name;
String url;
String description;
public website(String n, String u, String d)
{
name = n;
url = u;
description = d;
}
public website()
{
name = "";
url = "";
description = "";
}
public String toString()
{
return (name + " at " + url + " is " + description);
}
}
Que : What is final, finalize( ) and finally?
Ans: final
final keyword can be used for class, method and variables. A final class
cannot be subclassed and it prevents other programmers from subclassing a secure class
to invoke insecure methods. A final method can' t be overridden. A final variable can't
change from its initialized value.
finalize( )
finalize( ) method is used just before an object is destroyed and can be
called just prior to garbage collection.
finally
finally, a key word used in exception handling, creates a block of code that
will be executed after a try/catch block has completed and before the code following the
try/catch block. The finally block will execute whether or not an exception is thrown.
For example, if a method opens a file upon exit, then you will not want the code that
closes the file to be bypassed by the exception-handling mechanism. This finally
keyword is designed to address this contingency.
Inheritance
Inheritance is the mechanism that enables one class to have all of the
behavior and attribute of another class. Through inheritance, a class immediately has all
the functionality of an existing class. As a result, the new class can have methods added
14
to increase its functionality over the existing class. If a class needs to be inherited, the
extends keyword is used to indicate the ‘Parent’ class from which the new class inherits
its functionality. The new class will automatically inherit all the properties and methods
of the parent class.
Different kinds of objects often have a certain amount in common with each other.
Mountain bikes, road bikes, and tandem bikes, Object-oriented programming allows
classes to inherit commonly used state and behavior from other classes. In this example,
Bicycle now becomes the superclass of MountainBike, RoadBike, and TandemBike. In the Java
programming language, each class is allowed to have one direct superclass, and each
superclass has the potential for an unlimited number of subclasses:
The syntax for creating a subclass is simple. At the beginning of your class declaration,
use the extends keyword, followed by the name of the class to inherit from:
This gives MountainBike all the same fields and methods as Bicycle, yetallows its code
to focus exclusively on the features that make it unique. This makes code for your
subclasses easy to read. However, you must take care to properly document thestate and
behavior that each superclass defines, since that code will not appear in thesource file of
each subclass.
Advantages of Inheritance
It saves development time because the starting point for a new class is another
class that exitsts.
Maintenance time is reduced since changes have to be done only once i.e. in the
superclass class. These changes will be reflected in all the subclasses after
compiling the superclass.
Inheritance leads to standardization. All common methods and attributes remain
the same.
Since the new class is created from an existing class. The code in the superclass
is referenced and not copied to the new class. Thus the size of the new class file
will be relatively small.
15
Overriding methods in Java
In a derived class, if you include a method definition that has the same name and exactly the same number an
parameters as a method already defined in the base class, this new definition replaces the old definition of the
Explanation
A subclass inherits methods from a superclass. Sometimes, it is necessary for the subclass to
modify the methods defined in the superclass. This is referred to as method overriding. The
following example demonstrates method overriding.
Step 1
In this example we will define a base class called Circle
class Circle
{
//declaring the instance variable
protected double radius;
When the getArea method is invoked from an instance of the Circle class, the method returns the area of the c
Step 2
The next step is to define a subclass to override the getArea() method in the Circle class.
The derived class will be the Cylinder class. The getArea() method in the Circle class
computes the area of a circle, while the getArea method in the Cylinder class computes the
surface area of a cylinder.
16
public double getArea() { // method overriden here
return 2*super.getArea()+2*Math.PI*radius*length;
}//this method returns the cylinder surface area
}// end of class Cylinder
When the overriden method (getArea) is invoked for an object of the Cylinder class, the
new definition of the method is called and not the old definition from the
superclass(Circle).
Abstract Classes
An abstract class is a class designed with implementation gaps for subclasses to fill in
and is deliberately incomplete. Abstract class must have at least one abstract method and
others may be concrete or abstract. In abstract class, key word abstract must be used for
the methods. Abstract class must have subclasses.
Unit - II
Interfaces
Java does not support multiple inheritance , however it solves the
problem of multiple inheritance (shared behavior) by using interface.
An Interface is a collection of methods that indicate a class has some behavior in addition
to what it inherit from its superclass. Interface like abstract classes and methods, provide
template of behavior that other classes are expected to implement.
Defining an interface
Defining an interface is just like defining a class, except the class keyword is replaced
with the interface keyword.
Syntax :-
interface<interfacename>
{
// interface method declaration
}
class Shape interface Fill
Interface Fill
Class Shape {
{ drawFill( )
draw( ) {
{ //method without signature
//method signature }
} }
class Rectangle
Class Rectangle extends Shape
Implements Fill
{
draw( )
{
//method signature
}
drawFill( )
{
//method signature
} }
17
The class Rectangle inherits the functionality of the class Shape and implements the
interface Fill. Only constants and abstract methods are allowed in an interface. Every
interface is by default abstract. All methods declared in an interface are by default
abstract and public. An interface has a list of abstract method declarations. Interfaces can
form hierarchies just like classes. An interface uses the extend clause to inherit the
methods and constant defined in the super interface. However an interface can never
extend a normal class. Multiple inheritance can be implemented through interfaces by
creating a list interfaces separated by commas in the exteds clause.
Ex :-
Interface Operable exteds Openable, closeable
{
void open( );
void close( );
} Or
This means interface does not specify any code to implement these method and data
fields contain constants. These syntax of defining an interface is similar for defining a
class.
Interface Interface name
{
variable declaration;
method declaration;
}
Ex:- Interface item
{
static final int code = 1001;
static final string name = “fan”;
void display( );
}
Extending Interface
Interface can be extended like classes that is an interface can be
set interface from the other interface and the members of super interface is the member
similar to the subclass.
Syntax :- A Super interface
Interface B extends A
{
………….
...……….. B Sub interface
}
Implementing Interface :-
Interface are used as “Superclass” whose properties are
inherited by classes. It is necessary to create a class that inherits the given interface.
Syntax :-
Class class_name implements interfacename
18
{ Super
…………. A interface
………….
}
B C
class class
interface A
{
…………….
……………
}
class B implements A
{
……………..
……………...
}
class C implements A
{
……………..
……………...
}
Multithreading
A thread (or thread of control ) is often defined as a single
sequential flow of control within a program. A multithreaded program contain two or
more parts that can run concurrently. Each part of such program is called a thread and
each thread defines a separate path of execution. Thus, multithreading is a specilized
form of multitasking. A single program can perform two or more tasks simultaneously.
19
For instance, a text editor can format text at the same time that it is printing, as long as
these two actions are being performed by two separate threads. Threads are
lightweighted. They share the same address space and cooperatively share the same
heavyweight process. Interthread communication is inexpensive and context switching
from one thread to the next is low cost.
Advantages:-
Programs with multiple threads will in general result in better utilization of
system resources, including the CPU because another process can grab the CPU
when one process is waiting or blocked.
There are lots of problem better solved by multiple threads
Creating a Thread
A thread is created by instantiating an object of the type
Thread.Java defines two ways in which this can be accomplished.
• Implement the Runnable interface.
• Extend the Thread class, itself.
Thread Synchonization
Synchonization is the way to avoid data corruption caused by
simultaneous access to the same data by multiple threads. Because all the thrads in a
program share the same memory space, it is possible for two threads to access the same
variabel or run the same method of the same object at the same time. Problems may occur
when multiple threads are accesing the same data concurrently. Threads may race each
other, and one thread may overwrite the data just written by another. Or one thread may
work on another thread’s intermediate result and bread consistency of the data. Some
mechnism is meneed to block one thread’s access to critical data, if the data is being
worked on by another thread. All this occurs because when a CPU is idle the next thread
queue will capture the CPU procesing time to handle the thread’s processing. There is no
ordered flow but pre-queue multitalking.
Or
Multithreading
Operating system can execute several programs simultaneously.
This ability is known an multitasking. In systems terminology it is called
“Multithreading”.
Multithreading is a conceptual programming paradigm where a program
is divided into two or more sub programs. Which can be implemented at the same time in
parallel. A thread is similar to a program that has a single flow of control. It has
beginning of body and an end and execute command sequentially.
Creating a Thread :-
Threads are implemented in the form of objects that contain a
method called run( ) . the run( ) method is the heart and soul of any thread. It makes the
entire body of thread and is the only method in which the threads behaviour can be
implemented. The run( ) method is as follows :-
Public void run( )
{
………….
………….
}
The run( ) method should be called by an object of the concerned thread. This can be
achieved by creating thread and initiating it with the help of another thread method called
start. A new thread can be created in two ways :-
1) By creating a thread class.
2) By converting a class to a thread.
21
Extending the main class :-
We can make our class runnable as thread by extending the
class java.lang.thread this gives does to access all methods directly. It includes following
steps :-
i) Declare the class as extending the thread class.
ii) Implement the run method.
iii) Create a thread object and call the start method to initiate the thread execution.
Ex:-
Class A extends thread
{
public void run( )
{
----------------
----------------
}
}
class B extends thread
{
public void run( )
{
---------------
---------------
}
}
class C extends thread
{
---------------
---------------
}
Ex:-
Class ABC
{
public static void main( )
{
A obj = new A( );
B obj = new B( );
C obj = new C( );
D obj = new D( );
E obj = new E( );
Obj1.start( );
Obj2.start( );
}
}
IdleThread Blocked
(Runnable)
State transition diagram of thread
i) New born state :-
When we create a thread object the thread is born and is set
said to be in new born state. A thread is not yet schedule for running. At this state.
We can do only one of the following thing :-
a) Schedule for it running using start method.
b) Kill it using stop method. The diagram is given below :-
New born
Start Stop
Yield
suspend
resume
Running Runnable suspended
b) It has been made to sleep. We can put a thread to sleep for a specified time
period using the method sleep (time). Its diagram as follows :-
sleep
after
Wait
Notify
Running Runnable waiting
Synchronization
We have seen threads that used their own data and method
provided inside their run( ) method. In this type of method the one thread may try to
read a record from a file while another is still writing from same file defining on the
situation we may get strange results java enable us to overcome this problem using a
technique known as synchronization.
The keyword synchronization helps to solve
such problem by keeping a watch on such locations for eg.- the method that will read
the information and that will update the same file may be declared as synchronized.
Syntax :- Synchronized void update( )
{ ……………
……………
}
when we declare a method synchronized java creates a monitor and hence its over to the
thread that calls the method first time.
24
Exception handling
An exception is a condition that caused by a runtime error in
the program. This most common runtime error are as follows :-
i) Dividing an integer by zero.
ii) Accessing an element i.e. out of the bound of an array.
iii) Accessing a character i.e. out of bound of or string.
iv) Converting invalid string to a number.
v) Attempting to use a negative size for an array.
vi) Trying to illegally change the state of thread etc.
When the java interpreter encounters such above errors it creates an
exception object and through its if the exception object its caught and handled the
interpreter will display an error message and will terminate the program.
For this purpose we require exception handling. The purpose of exception
handling is to provide a means to detect and report an exception condition. So that
appropriate action can be taken error handling code can be perform the following
task.
i) Find the problem [list the exception]
ii) Inform that an error has occurred [throw the exception]
iii) Receive the error information [catch the exception]
iv) Take an action [handle the exception]
The error handling code basically consist of two segments :-
a) To detect errors and to throw exceptions
b) To catch exception and take appropriate action.
The syntax of exception handling and block diagram is as follows :-
Try Block
Statement that
throws cause an exception Exception object
exception creator
object
Catch Block
Statement that
Exception
Handles the exception
Handler
AWT Package
The java GUI classes are contained in the java.awt package. Java
AWT package provides the following:
• A full set of user interface (UI) widgets and other components, including
windows, menus, buttons, check boxes, text fields, scroll bars and scrolling lists.
• Support for UI containers, which can contain other embedded containers or UI
widgets.
• An event system for managing system and user events among parts of the AWT.
• Mechanisms for laying out components in a way that enables paltform
independent UI design.
26
Frame
Frame is a subclass of window, title bar, menu bar, resizing corners. When
we create a frame object from with in an applet. It will contain a warning message like
“warning : Applet window”.
Canvas
This is another type of window it an encapsulate a blank window upon
which you can draw.
Control Fundamentals
The AWT supports following types of controls :-
1) Labels 8) Scroll Bar
2) Button 9) Frame Layout
3) Check Box 10) Flow Layout
4) Radio Button 11) Grid Layout
5) Choice Menu 12) Border Layout
6) Text Area 13) Card Layout
7) Score List
1) Label :-
A label is an object of type and it contains a string which it display.
Label are passive controls that do not support with the user.
Label defines the following constructor.
i) Label( )
[The first version creates a blank label.]
ii) Label(String str)
[It creates a Label that contains the string specified by the str. This string is
left justified.]
iii) Label(String str, int a)
[It creates a Label that contains string specified by string using the
alignment specified by a. eg.- Label.left, Label.right, Label.centre]
Ex.-
Import java.awt.*;
Import java.applet.*;
Public class Sati extends Applet
{
public void init( )
{
Label one= new Label(“one”);
Label two= new Label(“two”);
Label three= new Label(“three”);
add(one);
add(two);
add(three);
}
}
Save Sati.java
HTML file Sati.html
Applet<code=”Sati.class” width=300 height=200> <\Applet>
27
2) Button:-
The most widely used control is Button. The push Button is a
component that contains a label and that generates an event when it is pressed. Push
button are of objects of type button.
Button defines two constructors :-
i) Button( ) // Creates an empty Button.
ii) Button(String str) // Creates a button that contain string str.
Ex.-
Import java.awt.*;
Import java.applet.*;
Public class Sati extends Applet
{
public void init( )
{
Button one = new Button(“Yes”);
Button two = new Button(“No”);
Button three = new Button(“Cancel”);
add(Yes);
add(No);
add(Cancel);
}
}
3) Check Box :-
A check Box is a control that is used to turn an option of a small box that
can either contain a check mark or not use change the state of check by clicking
on it. Check Box can be used individually are as a part of grow. Check Box are
object of the check Box class.
Check Box supports following controls –
a) checkBox( )
b) checkBox(String str)
c) checkbox(String str, Boolean on);
d) checkBox(String str, Boolean on,checkboxGroup cb);
First creates a check box whose label is initially blank. The state of check box is
unchecked. The second creates a check box whose label is specified by str. The label
state of check box is unchecked. The third alongs initial state of check box if on is true.
Check box is initially checked otherwise it is cleared. The fourth creates a check box
whose label is created by str and whose group is specify by cb.
Ex.-
Public class Sati extends Applet
{
checkBox one = new checkBox(“Dos”);
checkBox two = new checkBox(“Win98”);
checkBox three = new checkBox(“WinXP”);
checkBox four = new checkBox(“Linux”);
add(one);
add(two);
add(three);
add(four);
}
28
4) Radio Button (check box Group) :-
Radio button is the special type of check box
control. Radio button can be created using check box group class. We can create a set of
mutually exclusive check box. You must first define the Group to which they will belong
and then specify that group and construct that group.
Check Box group are object of type check box group only the default constructor is
defined which creates an empty group.
Ex.- Public Sati extends Applet
{
checkBoxGroup cb;
checkBox one = new checkBox(“Dos”,cb,true);
checkBox two = new checkBox(“Win98”,cb,false);
checkBox three = new checkBox(“WinXP”,cb,false);
checkBox four = new checkBox(“Linux”,cb,false);
add(one);
add(two);
add(three);
add(four);
}
5) Choice Menu :-
The choice class is used to create a pop-up list of items from which
the user may choose. A choice control is the form of Menu when inactive a choice
component takes of only enough space to show the currently items.
When the user clicks on it the whole list of choice pop-up and new selection can be
made. Each item in the list is a string that appears has a left justified label in the order it
is added, to the choice added.
Choice only defines added constructor which create an empty list.
Ex.- Import java.awt.*;
Import java.applet.*;
Public class Sati extends Applet
{
public void init( )
{
choice OS = new choice( );
choice Browse = new choice( );
OS.add(“Dos”);
OS.add(“Win98”);
OS.add(“WinXP”);
OS.add(“Linux”);
Browser.add(“Netscape1.1”);
Browser.add(“Netscape1.X”);
Browser.add(“Netscape2.X”);
Browser.add(“Netscape3.X”);
Browser.add(“Internet Explorer 2.0”);
Browser.add(“Internet Explorer 3.0”);
Browser.add(“Internet Explorer 4.0”);
add(OS);
add(Browser);
}
}
29
6) Text Area :-
Another control tool is TextArea. The awt includes a simple multiline
editor called TextArea. The following constructors are used in TextArea :-
i)TextArea( );
ii) TextArea(int a, int b );
iii) TextArea(String str);
iv) TextArea(String str, int a, int b);
v) TextArea(String str, int a, int b, int c );
Here ‘a’ specifies the height in lines of TextArea and ’b’ specifies the width in
characters and ‘c’ must be one of these values –
a) SCROLL BAR –BOTH
b) SCROLL BARS-NONE
c) SCROLL BARS-HORIZONTAL ONLY
d) SCROLL BARS-VERTICAL ONLY
Ex.-
Import java.awt.*;
Import java.applet.*;
Public class Sati extends Applet
{
public void init( )
{
String str = “Sati vidisha”+”MCA dept.”+”MANIT Bhopal”;
TextArea text = new TextArea(Str, 10, 30);
}
}
7) Score List :-
Lists:- The List class provide a compact multiple choice is called
selection list. This is similar to choice object which shows only single selected items in
Menu. The List provide the following constructors-
i) List( )
ii) List(int a)
iii) List(int a, Boolean b);
Here the value of ‘a’ specifies the number of entries in the list that will always be
visible. The value of ‘b’ may be true or false if ‘b’ is true the user may select two or
more item at a time if it is false then only one item may be selected.
Ex.-
Import java.awt.*;
Import java.applet.*;
Public class Sati extends Applet
{
public void init( )
{
List OS = new List(4,true);
ListBrowser = new List(4,false );
OS.add(“Dos”);
OS.add(“Win98”);
OS.add(“WinXP”);
OS.add(“Linux”);
Browser.add(“Netscape1.2”);
Browser.add(“Netscape1.X”);
30
Browser.add(“Netscape3.X”);
Browser.add(“Netscape4.X”);
add(OS);
add(Browser);
}
}
8) Scroll Bar :-
Scroll bar is used to select continuous values between a specified
minimum or maximum. Scroll bars may be oriented horizontally or vertically. A
scroll bar is actually a composite of several individual parts each and has an arrow
that it can click to move the current value one unit in the direction of arrow. Scroll bar
defines the following constructors :-
i) ScrollBar( );
ii) ScrollBar(int a );
iii) ScrollBar(int a, int b, int c, int e );
First form creates vertical scroll bar. Second & Third allows you to specify
orientation of the scroll bar.
If (a is ScrollBar.HORIZONTAL)
If (a is ScrollBar.VERTICAL) is created.
Ex.-
Import java.awt.*;
Import java.applet.*;
Public class Sati extends Applet
{
public void init( )
{
ScrollBar VSB = new ScrollBar(ScrollBar.VERTICAL);
ScrollBar HSB = new ScrollBar(ScrollBar.HORIZONTAL);
add(VSB);
add(HSB);
}
}
9) Flow Layout :-
Flow Layout is another control tool flow layout implements a
simple layout scheme which is similar to how words flow in text editor. Flow layout
includes the following constructors.
i) Flowlayout( )
ii) Flowlayout(int a )
iii) Flowlayout(int a, int b, int c )
First form creates a default layout .
Second form specifies how each line is aligned the value of a are as follows-
a) Flowlayout.LEFT
b) Flowlayout.CENTRE
c) Flowlayout.RIGHT
These values specifies left centre and right alignment respectively.
Third form allows you to specifies the horizontal and vertical space between
components.
Ex.-
Import java.awt.*;
Import java.applet.*;
31
Public class Sati extends Applet
{
public void init( )
{
Flowlayout ABC = new Flowlayout(Flowlayout.LEFT);
SetLayout(ABC);
String str = “Sati vidisha“;
TextArea text = new TextArea(str, 10, 30);
Add(text);
}
}
10) Grid Layout :-
Grid Layout is another control tool. Grid layout component can be
used in 2D grid. It supports the following constructors :-
i) GridLayout( )
ii) GridLayout(int a, int b)
iii) GridLayout(int a, int b int c, int d)
The first form creates single column grid layout. Second form creates grid layout with
the specify no. of rows and columns. The Third form allow you to specify horizontal
and vertical space between the components.
Ex.-
Import java.awt.*;
Import java.applet.*;
Public class Sati extends Applet
{
public void init( )
{
GridLayout ABC = new GridLayout(4,4);
SetLayout(ABC);
For(i=1;i<=4;i++)
{
for(j=1;i<=4;j++)
System.out.println(i);
}
}
}
11) Border Layout :-
Class implements a common layout. It has four narrow fixed width
components at the age and one large area in the centre. The four sides are referred to has
north, south, east and west. The middle area is called centre. The constructor of
BorderLayout is as follows :-
i) BorderLayout( )
ii) BorderLayout(int a, int b)
The first form creates a default Border layout. The Second form allow you to specify
the horizontal and vertical space left between components A & B respectively.
Border Layout defines the following constant that specifies the reason :-
i) BorderLayout.CENTER
ii) BorderLayout.SOUTH
iii) BorderLayout.NORTH
iv) BorderLayout.EAST
v) BorderLayout.WEST
32
When adding components we use these constants with the following form of add( ) which
is defined by container.
Add(component, object, reason);
Ex.-
Import java.awt.*;
Import java.applet.*;
Public class Sati extends Applet
{
public void init( )
{
BorderLayout obj1 = new BorderLayout( );
SetLayout(obj1);
String str = “Sati vidisha“;
add(new TextArea(String),BorderLayout.CENTER);
}
}
12) Card Layout :-
Card Layout class is unique among the other layout. This is useful for
user interface with optional component that can be dynamically enabled and disabled
upon user input.
Card Layout provide two constructors :-
i) CardLayout( )
ii) CardLayout(int a, int b)
The first form creates a default layout. The Second form allows to specify Horizontal and
vertical space between A & B respectively.
Menu Bars
A menu bar display a list of Top level menu choice. Each choice is
associated with a drop down menu. This concept is implemented in Java by the following
classes :-
i) Menu Bar
ii) Menu
iii) Menu item
Menu Bar contains one or more Menu objects each menu objects contains a list of menu
item objects. Each menu item object represent something that can be selected by the user.
To create a Menu Bar :-
I ) Create an instance of menu Bar this class only defines the default constructor.
II) Next create instance of menu that will define the selection display of the Bar.
Following are the constructor of Menu :-
i) Menu( )
ii) Menu(String str)
iii) Menu(String str, Boolean b)
Here str, specifies the name of Menu selection. If b is true the pop-up menu can be
removed otherwise it will remain to the menu bar.
Menu Item :-
Individual Menu items are of type Menu item. It defines the following
constructors :-
i) MenuItem( )
ii) MenuItem(String str)
iii) MenuItem(String str, Menu Shortcut s);
Here str is the name shown in the menu and s is the menu shortcut for this item.
33
Ex.-
Import java.awt.*;
Import java.applet.*;
Public class Sati extends Applet
{
public void init( )
{
MenuBar obj = new MenuBar( );
SetmenuBar(obj);
MenuFile = new Menu(“File”);
MenuItem I1=new MenuItem(“New”);
MenuItem I2=new MenuItem(“Open”);
MenuItem I3=new MenuItem(“Close”);
MenuItem I4=new MenuItem(“Save”);
MenuItem I5=new MenuItem(“Quit”);
File.add(I1);
File.add(I2);
File.add(I3);
File.add(I4);
File.add(I5);
Obj.add(File);
Menu Edit = new Menu(“Edit”);
MenuItem I6 = new MenuItem(“cut”);
MenuItem I7 = new MenuItem(“copy”);
MenuItem I8 = new MenuItem(“select all”);
MenuItem I9 = new MenuItem(“undo”);
Edit.add(I6);
Edit.add(I7);
Edit.add(I8);
Edit.add(I9);
Obj.add(Edit);
}
}
34
Event Listeners :-
A listener is an object that is notify when an event occurs it has two
major requirements.
i) It must have been registered with one or more source to receive notification about
specific type of event.
ii) It must implements method to receive and process these notifications.
Listeners are created by implementing the interface defined by
the Java.awt.* some Listener interface are as follows :-
Event Classes
The classes that represent events are used for event handling.
At the root of Java event class hierarchy is event object which is in java.util.*;
Main event classes is given below :-
ActionEvent Classes
The ActionEvent is generated when a button is pressed or list
item is double clicked or a menu item is selected.
The ActionEvent class defines 4 integer components that can be used to identify any
modifiers associated with an action event.
35
Action event has two constructors :-
i) ActionEvent(object src, int a, string str)
ii) ActionEvent(object src, int a, string str, int b)
There src is a refrence to the object that generates this event. Where ‘a’ is the type of
event. str is the command string and ‘b’ is a an integer value.
We can obtain the command name for invoking action event by using the
getActioncommand( ).
AdjustmentEvent Class
An AdjustmentEvent is generated by scroll bar there are
five types of adjustment events.
The AdjustmentEvent class defines integer constants that can be used to identify them.
The constant and their meaning are-
Constants Meaning
i) BLOCK_DECREAMENT The user click inside the scroll bar to decrease its value.
ii)BLOCK_INCREAMENT The user click inside the scroll bar to increase its value.
iii) TRACK A slider.
iv)UNIT-DECREAMENT The button at the end of scroll bar was clicked to
decrease its value.
v) UNIT-INCREAMENT The button at the end of scroll bar was clicked to
increase its value.
The Adjustment event has following constructors :-
i) AdjustmentEvent(Adjustment src, int a, int b, int c)
Here src is a reference to the object that generates this event and a,b,c are integers.
ContainerEvent Class
It is generated when a component is added or removed from
container. The container events are of two types :-
i) Container event class defines integer constants that can be used to identify
them.
a) COMPONENT ADDED
b) COMPONENT REMOVED
Container event is a subclass of component event and has this constructor
ContainerEvent(component src, int a, component b)
Src is the reference to the container that generates this event. The type of event is
specified by a. The component that has been added or removed from the container from
the container b.
FocusEvent Class
A Focus event is generated when a component gains or losses
input focus.
These events are identified by the integer constants.
i) FOCUS-GAINED
ii) FOCUS-LOST
Focus event is a subclass of component event and has these constructors-
i) FocusEvent(component src, int a)
ii) FocusEvent(component src, int a, boolean b)
Here src is a reference to the component that generated this event. and the type of
event is specified by ‘a’ and ‘b’ is said to true a focus event is temporary, false
otherwise.
36
InputEvent Class
The Input event is a class of component event and is a super
class for component event. Its subclass are key event and mouse event. It defines
following 8 integer constants.
i) ALT_MASK
ii) ALT_GRAPH_MASK
iii) BUTTON1_MASK
iv) BUTTON2_MASK
v) BUTTON3_MASK
vi) CTRL_MASK
vii) META_MASK
viii) SHIFT_MASK
ItemEvent Class
An Item event is generated when a check box is clicked. There are
two types of item event which are identified by the following integer constants.
i) DESELECTED
ii) SELECTED
The ItemEvent has only one constructor –
ItemEvent(item selectable src, int a, object c, int d)
Src is the reference to the component .’a’ type of event specified by a. The item that
generated item event in passed in ‘c’ and ‘d’ is the item state.
KeyEvent Class
The Key event is generated when keyboard input occurs there are
3 types of key events which are identified by integer constants.
i) KEY_PRESSED
ii) KEY_RELEASED
iii) KEY_TYPED
The first two events are generated when any key is pressed or released.
The last event occurs only when a character is generated. The key event and has two
constructors.
KeyEvent(component src, int type, long a, int b, int c)
KeyEvent(component src, int type, long a, int b, int c, char ch)
The src is the reference to the component.
Type specify type of event.
The system at which the key was pressed is specified by ‘a’.
‘b’ argument indicate which modifiers were pressed.
This specifies – a) VK_UP b) VK_A
MouseEvent Class
There are 7 types of mouse events. The mouse event class
defines the following integer constants that can be used to identify them :-
i) MOUSE_CLICKED // user clicked mouse
ii) MOUSE_DRAGGED // user drag the mouse
iii)MOUSE_ENTERED // user entered a component
iv) MOUSE_EXITED // the exit from component
v) MOUSE_MOVED // the mouse moved
vi) MOUSE_PRESSED // mouse was pressed
vii) MOUSE_RELEASED // mouse was released
MouseEvent(component src, int type, long a, int b ,int x, int y, int c, Boolean b)
37
TextEvent Class
These are generated by text field and Text Area when character
are entered by user text event define the integer constant.
TEXT_VALUE_CHANGED
The constructor for this class is given below
TextEvent(component src, int a)
src is reference to the object that generated the type of event is specified by ‘a’.
WindowEvent Class
A Window event class defines integer constants that can be
used to identify them. The constants and their meaning is given below-
There are 7 types of Window events –
i) WINDOW_ACTIVATED // the window was activated
ii) WINDOW_CLOSED // the window has been closed
iii)WINDOW_CLOSING // the user requested that the window be closed.
iv) WINDOW_DEACTIVATED // the window was deactivated
v) WINDOW_DEICONIFIED // the window was deiconified
vi) WINDOW_ICONIFIED // the window was iconified
vii) WINDOW_OPENED // the window was opened
WindowEvent(window src, int a)
Here src is reference to the object that generates this event and the type of event is
specified to this event.
Unit – IV
Input-Output Stream
In file processing system input refers to the flow of
data into the input program and output means the flow of data out of a program.
Input to a program may come from the keyboard, the mouse, memory, the disk,
network or another program similarly the output from program may go to the screen
the printer, the memory the disk the network or another program.
Source Destination
Mouse Screen
Keyboard
Printer
JAVA
Memory
program Output Memor
y
Disk Input
Networ Network Disk
k
Stream:-
Java use the concept of stream to represent the ordered sequence of data. Or
stream represents a uniform easy to use object oriented interface between the program
and input output devices.
A stream in java is a path along which data flows .It helps a source and
destination. The concept of sending data from one steam to another has made streams
in java a powerful tool for file processing. Java streams are classified into two basic
types :-
i) Input stream
ii) output stream
38
i) Input stream :-
An input stream extracts {read} data from the source {file} and
sends it to the program.
Stream Classes :-
The Java.io package contains a large no. of stream classes that
provide capabilities for processing all types of data. These classes may be classified
into two category :-
JAVA
classes
Byte Character
Stream Classes Stream Classes
39
Object
Input Stream
Data input
Method Description
i) read( ) reads a byte from the input stream.
ii) read(byte b[]) reads an array of bytes in b.
iii) read(byte b[],int n,int m) reads m bytes into b, starting form nth byte.
iv) available( ) given a no. of bytes available in the input.
v) skip(n) skips over n.
vi) reset( ) go back of the beginning of the stream.
vii) close close the input stream.
40
The Output stream contains various methods. These methods are shown in the
table.
Method Description
i) write( ) writes byte to the Output stream.
ii) write(byte b[]) writes all bytes in the array b to the Output stream.
iii) write(byte b,int n,int m) writes m bytes from array b. a[b] starting from nth byte.
iv) close( ) close the Output stream.
v) flush( ) flush is the Output stream.
Object
Character
Reader Pipe
Reader
Input Stream
Reader Filter
Reader
File Reader
Push back Reader
Method Description
i) read( )
ii) read(char b[])
iii) read(char b,int n,int m)
iv) available( )
v) skip( )
vi) reset( )
vi) close( )
Object
Writer
Buffered Print
Writer Writer
Character String
Array Writer Writer
Output Stream
Writer
Filter Pipe
Writer Filter
File Writer
Method Description
i) write( )
ii) write(char b[])
iii) write(char b, int n, int m)
iv) close( )
v) flush( )
File Creation
We have the following purpose of creation of file :-
i) Reading a file
ii) Writing a file
iii) Updating a file
For the above purpose we need to handle with the file. So far handling the various
operation of the file we need to decide the following above the file :-
i) Suitable name for the file
ii) Data type to be stored
iii) Purpose (reading, writing, updating)
iv) Method of creating the file
44
• Once the ‘Microsoft Access Driver [.mdb]’ ODBC driver has been selected as the
driver of choice, click on the ‘finish’ button on the interface to complete creating
the system DSN. This interface allows the user to inform the newly created
system DSN as to where the database, table is located on the computer’s hard
disk.
• Fill in the datasource Name field on the interface. Thus giving the DSN a ‘Name’.
in this case the name given is ‘java’.
• Use the ‘select’ button on the interface and selecdt the Accesss .mdb by browsing
through the directory tree structure of the hard disk until the Access .mdb file is
located.
• Once these steps are completed, a 32 bit ODBC, named Data Source (driver)
exists and has been registered with the computer. This driver knows where the
MS-Access database, is and can communicate with any of its tables.
• The system DSN now exists. The DSN is aware of the existence of the MS
Access database.
The UI however has been coded using java. Java cannot communicate directly with an
ODBC driver as this driver has been created using technique that are outside Java. Hence
using appropriate Java code and associated Java driver’s a bridge must be set up between
the 32 bit ODBC driver and the Java UI. This is a JDBC-ODBC bridge. This allows the
Java UI to communicate with the MS Access database below it using an appropriate
(underlying) Java code layer.
Creates a Connection Object which communicates with the ODBC driver and
in turn spawns a Result Set object to hold the record set returned by the query
made to the Database Table.
The ResultSet Object this holds the records retrieved from the Access, table. Data
from this result set object can be bound to controls on a java form i.e. the UI.
45
The Driver Manager :-
Java’s Driver Manager controls interaction between the UI and
the use driver being used. It can support multiple drivers connecting to different DBMS
systems.The driver manager can perform the following tasks :
• Locate a driver for a particular database
• Process JDBC initialization calls
• Provides entry points to JDBC functions for each specific driver
• Perform parameter and sequence validation for JDBC calls.
The Driver Manager Class :- The Driver manager class works as the interface between
the application(UI) and the ODBC driver created to communicate with the MS Access
table.
The Driver Manager also provides a set of inbuilt methods for managing database drivers.
Some of the dirverManager methods are -
• getConnection ( JDBC:ODBC: Name of the DSN, <username>,<password>)
Proid :
Remarks :
46
The Java.Sql Package
The java.sql package contains various interface and
classes used by the JDBC API. This collection of interfaces and classes enable the
primary function of opening and managing connections to a particular DBMS System.
Executing SQL statements. Processing the results.
DriverManager Class :- The DriverManager class is available in the java.sql package. It
controls the interface between the application and a set of JDBC drivers. The
DriverManager also provides a set of methods for managing the drivers.
• GetConnection(URL, user, Password)
Connection Interfaces:-
A connection object represent a connection with a database.
Within this session SQL statement can be executed, returning resultsets. Some methods
of the connection objcet are :-
• void close( )
• Statement CreateStatement( )
• ResultSet exccuteQuery(String SQL_Statement)
• Int executeUpdate(String SQL_Statement)
PrepareStatement interface
• executeQuery( )
• executeUpdate( )
ResultSet Interface
• void close( )
• void getString( )
• next( )
ResultSetMetaData Interface
• getColumnCount( )
• String getColumnName(int)
• getTableName( )
JDBC Exception Classes
• SQL Warning
• Data truncation
• SQLException
SQL Warning Class :-
The java.sql.SQL Warning class extends java.sql.SQL Exception
class. The SQL Warning class provides information about a database access warining.
When a method of an object causes a warning to be reported, the warning is chained to
that object. Some method are :
• SQLWarining getNextWarning( )
This method returns the SQLWarning chained to the current SQLWarning object.
• void setNextWarning(SQLWarning nextWarning)
This method adds a SQLWarning object to the end of the chain.
DataTruncation Class :-
The Data Truncation class extends the java.sql.SQLWarning
class. When JDBC truncates a data value unexpectedly, it reports a DataTruncation
warning for a read process, or write process. Some methods are :
• int getIndex( )
This method returns the index of the column or the parameter that was
truncated.the return value is -1, if the column or parameter is unknown.
47
• Boolean getParameter( )
If the truncated value was a parameter the value returned is True, if the truncated
value was a column the value is False.
• Boolean getRead( )
If the value was truncated while being read from a database, the value returned is
True. If the value was truncated when writing to a database the value False is
returned.
SQLException Class :-
The Java.sql.SQLException class extends the java.lang.Exception
class. The SQL Exception class provides information about a database access error. Some
methods are :
• Int getErrorCode( )
This method returns the vendor specific exception code.
• String getSQLState( )
This method returns the SQLstate.
• SQLException getNextException( )
This method is used to obtain the next exception, chained to the current exception.
Unit – V
Sockets
Sockets are software interface that connect an application to a network.
On the internet, each machine has 65,536 addressable ports it can use. All standard
internet services(like e-mail, FTP) use agreed upon port numbers, colloquially termed
“well known port numbers.” Server program listen to these ports for any incoming
services request. A client program needs to open a port of its own before it can
connect to a server port at the other end.
80 21 23 7
TCP/IP OR UDP
7 Data
Through the classes in java.net, java progarms can use TCPor UDP to communicate
over the Internet. The URL, URL connection, Socket and ServerSocket classes all use
TCP. The DatagramPacket and DatagramServer classes use UDP to communicatae
over the network.
48
A call to a remote object using RMI is identical to a call made to a local object with
the following exceptions:
An object passed as a parameter to a remote method or returned from the
method must be serializable or be another Remote object.
An object passed as a parameter to a remote method or returned from the
remote method called is passed by value and not by reference.
The only exception is when a remote object is passed to a remote method or
when a remote object is returned by the remote method. In this case a
reference to the remote object is used.
A client always refers to a remote object through one of the romote interface
that it implements. A remote object can be typecast to any of the interfaces
that a client implements.
The java.rmi and the java.rmi.server packages contain the interfaces and classes that
define the functionality of the java RMI system. These packages and interfaces provide
the building blocks for creating server-side and client-side object stubs.
RMI Architecture
Transport Layer
RMI Registry
A server registry any remote object that it is exporting with a
name server called a registry. When a client wishes to a obtain a reference to a remote
object, a lookup is performed with a known registry and a reference to the remote
object is returned if the loodup is successful.
Registry services can be used in one of two ways –
The first method is to maintain a registry server that is running on a well
known predefined port number. Any application that is exporting objects can
register with this registry, as long as that application is running on the same
machine as the registry.
The second method involves an application running its own registry services.
This allows the application to have total over the registry but at the same
time makes it more difficult to define a well known port number that client
application can use to access remote objects.
RMI uses the first method to maintain a registry. The registry keeps track of the addresses
of all the remote objects that are being exported by their applications. All objects are
assigned unique names that are used to identify them. Application can add, remove and
access remote objects in the registry in the registry table of objecs by calling certain
methods from the rmi.registry. Registry interface, or from the rmi.Naming class.
49
Creating RMI Application
To create an application that uses RMI, one needs the
classes and interfaces defined by the java.rmi package.
To create an RMI application the following steps need to be followed :
Define an Interface for the Remote Classes
Implement the Interface in a Server-side Application
Bind Objects to a registry service
Create Stubs and Skeletons classes
Create and Compile the Client Program to Access the Remote Objects
Install files on the Client and Server Machines
Start the RMI Registry.
Ex:-
Import java.rmi.*;
Interface MethodImpl extends Remote
{
double getSqrt(double dbl) throws RemoteException;
}
THE END
50