Вы находитесь на странице: 1из 50

Unit-I

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.

• C++ was designed as an extension of the C programming language. To this


procedural programming language designed for efficient execution, C++ has
added support for statically-typed object-oriented programming, exception

1
handling, scoped resource management, and generic programming, in particular.
It also added a standard library that includes generic containers and algorithms.

• Java was created initially to support network computing. It relies on a virtual


machine to be secure and highly portable. It is bundled with an extensive library
designed to provide a complete abstraction of the underlying platform. Java is a
statically typed object-oriented language that uses a syntax similar to C, but is not
compatible with it. It was designed from scratch, with the goal of being easy to
use and accessible to a wider audience.
• Java syntax has a context-free grammar which can be parsed by a simple LALR
parser. Parsing C++ is somewhat more complicated; for example, Foo<1>(3); is
a sequence of comparisons if Foo is a variable, but it creates an object if Foo is
the name of a class template.
• C++ allows namespace level constants, variables, and functions. All such Java
declarations must be inside a class or interface.
• const in C++ indicates data to be conceptually 'read-only,' and is applied to types.
final in Java indicates that the variable is not to be reassigned. For basic types
such as const int vs final int these are identical, but for complex classes,
they are different

• 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.

• For passing parameters to functions, C++ supports both true pass-by-reference


and pass-by-value. In Java, all parameters are passed using pass-by-value.

• 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

backwards compatible with C source


incompatible with other languages
code

allows direct calls to native system Calling native system libraries is


libraries difficult

Exposes low-level system facilities runs in a protected virtual machine

no automated bounds checking provides pervasive memory protection

value-based semantics and explicit reference semantics for user-defined


pointers objects

Explicit memory management automatic garbage collection

allows explicitly overriding types type safety

Supports procedural, object-oriented,


Object-oriented, with some support for
functional and generic programming
generic programming
paradigms

Standard C++ library has a limited scope Extensive language-specific library (also
(containers, algorithms, file and console allows GUI programming, networking,
I/O) etc)

operator overloading meaning of operators is immutable

Editing, Compiling and Running a Java Program 


The instructions
here should work on either Windows or Linux systems. Java is relatively platform
independent, Here is the basic process broken down into steps:

• Open a dos command prompt window or a Linux xterm shell.


• Make a directory where you would like to keep your Java programs and change to
that directory.
• Open a text editor program (e.g. vim, vi, emacs or whatever you normally use).
• Type or paste a Java program into the editor. For instance you could start with
the following example:
// My first Java Program

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)

Applet Life Cycle 


Every java applet inherits a set of default behaviour from the
applet class as a result when an applet is loaded is it undergoes a series of changes in its
states the applet life cycle is given below.
Begin (Load applet)
Initialization
Born

Start( )
Stop( )
Display Running Idle
Paint( ) Start( ) destroy( )

Destroyed Dead End

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.

Creating and Executing an Applet 


For Applet creation we create separate two files –
(i) Java file ii) HTML file
and both files has same name and with different extension. .java and .html
We compile the java file it creates another file that is called class file.
An Executable Applet is the class file of the applet which is obtained by compiling the
source code by the java file.
The steps required for compiling the java file are as follows :-
i) Move to the directory containing the source code and type the following
command - javac filename.java
ii) The compile O/P file called filename .class is placed in the same directory as
the source.
Running the Applet :-
To run an Applet the three files must be in same directory.
Filename.java
Filename.class
Filename.html
The following tools are require to run an Applet-
i) Java enabled web browser such as Hotjava or Netscape
ii) Java Appletviewer

Data Types 

NUMERIC (all numbers are signed)

• short integer (16 bit number) --> i.e. +/- 32,768


• int integer (32 bit number) --> i.e. +/- 2 billion or 2 x 109
• long integer (64 bit number) --> i.e. +/- 9 x 1018
• float real (32 bit decimal) --> i.e. +/- 1.4 x 10-45 to +/- 3.4 x 1038
• double real (64 bit decimal) --> i.e. +/- 4.9 x 10-324 to +/- 1.7 x 10308

CHARACTER/STRING

• char a unicode (2-byte) char


• the String class handles multi-character strings (strings are unicode, as well).
Strings are said to be immutable: updates to a String cause the new string to be
created in memory (and pointed to by the String class). However the old string is
not actually "updated", rather, its reference is lost (and it becomes available for
garbage collection).

BOOLEAN

• boolean (with values true, false)

DATE

• the Date class measures the milliseconds since Jan 1, 1970 and provides
supporting functions to interpret and manipulate date/times

7
ARRAYS 

• arrays hold multiple instances of a data type or object


• arrays can be declared but still need to be explicitly initialized
int [] dataPoints; // declares the array of integer
dataPoints = new int[10] ; // allocates array size (now usable)
dataPoints = new int[numPoints]; // allocates array size with size specified by a
run-time variable
• an array can be re-initialized (with the same data type) at runtime, at which point
old array entries are discarded
• Java standard arrays cannot are not dynamically resizable like arrays in Visual
Basic or PowerBuilder (i.e. where the language can dynamically extend the array,
if needed). Java throws an exception if an out-of-bounds array index is
referenced. Java.util's Vector class provides dynamic array-like capability (a
Vector can store a collection of any type of object). The standard Vector class
does not, however, limit data to a specific data type (data type limitation
capability has to be built in a Vector extension).

4. Simple Output and Input Statement in Java

5. Major Constructs

6. Methods (functions)

Major Operators 

Operator Description Comment / Example


/* */ encloses multi-line
comment
//
indicates rest of line is a
comment
= Assignment
; terminates a line x = x + y;
== checks for equality, e.g. if If you accidentally use if (x=1), the compiler
(x==1) flags the mistake. For string comparion, always
!= use the equals method: str1.equals(str2)
check for inequality
> >= greater than, gr. than or
equal
< <=
less than, less than or
equal
! NOT (negates a boolean
expression)
+= -= *= shorthand operator to x += s (is like x = x + s, doing addition or string
add/subtract/multiple two concat. depending on whether these are numbers

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;

// 32 bit standard integer


int myInteger;

myLongInteger = myInteger;

The extra storage associated with the long integer, in the above example, will simply be
padded with extra zeros.

Explicit Conversion (Casting) 


The above will not work the other way round.
For example we cannot automatically convert a long to an int because the first requires
more storage than the second and consequently information may be lost. To force such a
conversion we must carry out an explicit conversion (assuming of course that the long
integer will fit into a standard integer). This is done using a process known as a type cast:

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";

Two Dimensional Arrays 


Two dimensional arrays are declared, allocated and
initialized much like one dimensional arrays. However we have to specify two
dimensions rather than one, and we typically use two nested for loops to fill the array.
class FillArray
{
public static void main (String args[])
{
int[][] M;
M = new int[4][5];
for (int row=0; row < 4; row++)
{
for (int col=0; col < 5; col++)
{
M[row][col] = row+col;
}
}
}
}

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 

• this – Reference to the current subclass (assumed by default) (i.e.


this.someMethod()).
• super – Reference to the parent class (i.e. super.someMethod()).

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.

• default – accessible only within the package in which it's defined.


• public – extends access to classes outside the package

Class member access 


Class members are fields, methods, constructors and nested
classes declared within the body of a class. In order of increasing scope of access, the
access modifiers for class members are:
1) private – accessible only within the class
2) package-private (no modifier) – accessible to other classes in the same package
3) protected – extends access to subclasses outside the package
4)public – accessible by any class.

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 :-

• Reduce problems in name conflicts.


• Control the visibility of classes, interfaces, methods and data defined within them.

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:

A hierarchy of bicycle classes.

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:

class MountainBike extends Bicycle


{
// new fields and methods defining a mountain bike would go here
}

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 

Overriding method definitions

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;

public Circle(double radius) {


this.radius = radius;
}
// other method definitions here
public double getArea() {
return Math.PI*radius*radius;
}//this method returns the area of the circle
}// end of class circle

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.

The Cylinder class is defined below.

class Cylinder extends Circle {


//declaring the instance variable
protected double length;

public Cylinder(double radius, double length) {


super(radius);
this.length = length;
}

// other method definitions here

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

Interface : Multiple Inheritance


Interface is basically a kind of class like class interface contain method and variable. But
with major difference.
The difference is between that is :-
Interface define only abstract method and final fields only.

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
{
……………..
……………...
}

Accessing interface variables :-


Interface can be used to declare a set of constants that can
be used in different classes. This is similar to creating header files in C++. To contain a
large number of constants. Since such interface do not contain method. The constant
value will be available for any class that implements the interface. The value can be used
in any method as part of any variable declaration are any where we can use a final value.
Ex:-
Interface A
{
int m=10;
int n= 50;
}
class B implements A
{
int x=m;
void function(int size)
{
if(size<n)
…………..
…………..
}
}

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

The thread control methods 


• Start( ) Used to start the execution of the thread. The start( ) method
when called will immediately execute the run( ) method.
• Stop( )  Used to stop the execution of the thread no matter what the
thread is doing. The thread is then considered dead.
• Suspend( )  Used to temporarily stop the execution of the thread. All
the states and resources of the thread are retained. This method pauses a
running thread.
• Resume( )  Used to resume the execution of a suspended thread.
• Sleep( )  A class method that causes the runtime to put a thread to sleep
for a specified time period. The exception,interruptedException, may
thrown while sleeping.
• Join( )  The join( ) method waits until the thread on which it is called
terminates i.e. it ensures that the thread has finished it’s execution.
• Yield( )  A class method that temporarily stops the called thread and
puts it at the enc of the queue to wait for another turn to be executed.

Life Cycle of Thread 


Every thread after creation and before destruction will always be
in one of four states:- newly created, runnable, blocked, or dead.
Newly created threads :-
A thread enters the newly created states immediately after
creation. This thread is created when the new statement is executed. In this state, its local
members are allocated and initialized. By executing the start( ) method which in turn
calls the run( ) method, the thread is in a runnable state.
Runnable thread :-
When a thread is in the runnable state its ready to executes its
‘signature’and can now be in one of two states, running or queued. When a thread is in
the running state, it is assigned CPU cycle and is actually running. When a thread is in
the queue state, it is waiting in a queue and competing for its turn to spend CPU cycles.
Blocked thread :-
The blocked state is entered when one of the following event occurs :
• The thread itself or another thread calls the suspend( ) method.
• The thread calls an object’s wait( ) method.
• The thread itself calls the sleep( ) method.
• The thread is waiting for some I/O operation to complete.
• A thread in a blocked state is not scheduled for running.
It will go back to the runnable state competing for CPU cycles when –
• Another thread calls the suspended thread’s resume( ) method.
20
• A thread is put to sleep and the specified sleeping time elapses.
• If the thread is blocked on I/O and the specified I/O operation completes.
Dead Thread :-
The dead state is entered when a thread finishes its execution or is stopped
by another thread calling its stop( ) method.

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( );
}
}

Life Cycle of thread 


During the life time of thread there are many states it can
enter. They include :-
i) New born state
ii) Runnable state
iii) Running state
iv) Blocked state
v) Dead state
22
A thread is always in one of these five states. It can move from one state to another
via different ways as shown in following figure.

New thread New born


stop
Start killed
thread
Active
Thread D
Dead
Running Runnable

Suspend sleep resume


Wait notify stop

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

Runnable Dead state


state

Scheduling a new born state

ii) Runnable state [Ready process] :-


The runnable state means that a thread is
ready for execution and is waiting for availability of the processor that is the thread is
in the key of threads that is waiting for execution. Its state diagram is as follows :-

Yield

Running thread Runnable threads

iii) Running state :-


It means that the processor has given its time to the thread for
its execution. A running thread has following situations :-
23
a) It has been suspended using suspend( ) method. A suspended thread can
be receive by using resume( ) method. Its diagram like as –

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

Running Runnable sleeping


c) It has been told to wait until some event occurs. This is done using the wait
method. The thread can be scheduled to run again using the notify( ) method.

Wait

Notify
Running Runnable waiting

iv) Blocked state :-


A thread is said to be blocked when it is prevented from
entering into the runnable state and sleeping into the runnable state. This happen
when the thread is suspended sleeping or waiting in order to satisfy certain
requirements.

vi) Dead state :-


A running thread ends its life when it has completed executing its
run method. It is natural death.

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

Exception handling mechanism


Syntax :- Ex:-
----------------------------- class error
try {
{ public state void main(string args[])
statements; { int a=10,b=5,c=5,x,y;
} try
catch (exception_type e) {
{ x=a/(b-c);
statements; }
} catch(ArithmeticException e)
{
system.out.println(“Division by zero”);
}
y=a /(b+c);
system.out.println(“y= “+y);
}
25
Multiple Catch Statement :-
It is possible to have more than one catch statement in one
block. The syntax of multiple catch statement as follows :-
Try Ex:-
{ class error
statement; {
} public static void main(Sring arg[])
catch(exception_type1 e) {
{ int a[]=(5,10);
statements; int b=5;
} try
catch(exception_type2 e) {
{ int x=a[2]/b-a[i];
statements; }
} catch(ArithmeticException e)
………………… {
………………… system.out.println(“Div by zero”);
catch(exception_typen e) catch(Arrayindexout of boundException e)
{ {
statements; system.out.println(“wrong data type”);
} }
int y=a[1]/a[0];
system.out.println(“y= “+y);
}
}
Unit – III
Applet 
Applet Security Restrictions 
Java applets are run in a web browser, there are some
restrictions to what an applet is capable of doing. If these were not in place, a malicious
Java progarmmer could write an applet that deletes user files, collects private information
from the system and commits other security breaches. An applet cannot do any of the
following:-
• They cannot read or write files on the user file system.
• They cannot communicate with an internet site other than the one that served the
Web page, which included the applet.
• They cannot run any program on the reader’s system.
• They cannot load programs stored on the user’s system, such as executable
programs and shared libraries.

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);
}
}

The Source of events are as follows :-

Events Source Description


i) Button Generates or event when button is presented.
ii) CheckBox Generates event when the check box is selected.
iii) Choice Genereates item events when the choice is changed.
iv) List Generates action event when an item is double clicked and
generates item event when an item is selected.
v) Menu Item Generates action events when an item is selected and
generates item event when checkable Menu item is selected.
vi) Scroll Bar Generates adjustment event when the scroll bar is
manipulated.
vii) Text component Generates text event when the user enters a character.
viii) Window Generates window events when window is activated, close,
deactivated, opened, quit etc.

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 :-

Listener Interface Description


i) ActionListener Defines 1 method to receive action events.
ii) AdjutmentListener Defines 1 method to receive adjustment events.
iii)ComponentListener Defines 4 method to recognize when a component is hidden
moved reside are shown.
iv) ContainerListener Defines 2 method when a component is added to or
removed from a container.
v) FocusListener Defines 2 method to recognize when a component gains are
losses keyword focus.
vi) KeyListener Defines 3 method to recognize when a key is pressed,
released or typed.
vii) MouseListener Defines 5 method when mouse is clicked enter a component
exit a component is pressed is released.
viii) TextListener Defines 1 method to recognize when a text value is changed.
ix) WindowListener Defines 7 methods to recognizes when a window is activated,
closed, deactivated, opened, quit etc.

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 :-

Listener Interface Description


i) ActionEvent Generated when a button is pressed. A list item is double
clicked or menu item is selected.
ii) AdjutmentEvent Generated when a scroll bar is manupulated.
iii)ContainerEvent Generated when a component added or removed.
iv) FocusEvent Generated when a component gains or losses keyword focus.
v) ItemEvent Generated when a check box list item are when a choice
selection is made.
vi)KeyEvent Generated when input is received from keyboard.
vii) MouseEvent Generated when the mouse is dragged, moved, click, press,
release etc.
viii) TextEvent Generated when the value of text area are text is changed .
ix) WindowEvent Generated when window is activated ,closed, deactivated ,
opened, quit etc.

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.

ii) Output stream :-


An output stream receives data from the program and
sends{writes} it to the destination {file}.

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 :-

i) Byte stream classes :-


This provide support for handling I/O operation on
bytes.

ii) Character stream classes :-


It provides support for managing I/O operation
for characters. The following diagram shows the classification and their functions
byte stream and character stream contain specialized to deal with Input and Output
operation of various devices.

JAVA
classes

Byte Character
Stream Classes Stream Classes

I/P Stream O/P Stream Reader Classes Writer Classes


Classes Classes

Memory File Pipe Memory File Pipe

Classification of Java Stream Classes

39
Object

Input Stream

File input Sequence


Stream input Stream

Pipe input Object input


Stream Stream

Byte Array String buffer


input Stream File input Stream input Stream

Buffer input Data input Push back


Stream Stream input Stream

Data input

The Super Class Input Stream :-


The Super class input stream defines method for
performing into function such as –
i) Reading bytes
ii) Closing streams
iii) Marking position in streams
iv) Skipping ahead in streams
v) Finding a number of bytes in a stream
The input stream class provide the following methods.

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.

Output Stream Classes :-


The Output stream classes are derived from the base class
output stream the hierarchy of output stream class are shown in following figure.
The output stream can be used are performing Output operation. The Output stream
designed to perform the following task.
i) Writing bytes
ii) Closing stream
iii) Flushing 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.

Character stream classes :-


Character stream classes can also be classified into a two
categories :-

i) Reader Stream classes :-


Reader stream classes are designed to read char from
the files. Reader class is the base class for all other classes that is shown in the
following figure these classes.

Object

Buffered Reader String


Reader
Reader

Character
Reader Pipe
Reader

Input Stream
Reader Filter
Reader

File Reader
Push back Reader

Hierarchy of Reader stream classes


These classes are similar to the input stream classes only difference is that the input
stream classes use bytes as there fundamental unit information while reader stream
classes use characters. The reader stream classes provide the following methods :-

Method Description
i) read( )
ii) read(char b[])
iii) read(char b,int n,int m)
iv) available( )
v) skip( )
vi) reset( )
vi) close( )

Writer Stream classes :-


The Writer stream classes are designed to perform all
output operation on files similar to output stream classes. The output stream classes
41
are designed to write byte. But write stream classes are designed to write chars. The
diagram of writer stream classes is given below :-

Object

Writer

Buffered Print
Writer Writer

Character String
Array Writer Writer
Output Stream
Writer

Filter Pipe
Writer Filter
File Writer

Hierarchy of Writer Stream Classes


The Writer stream classes providing following methods-

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

i) Suitable name for the file :-


A file name is a unique string of chars that helps
identify a file on the disk. The length of a file name and the chars allowed are
dependent on the operating system on which Java program is executed.
A file name contains two parts- i) file name ii) extension
Ex.- Text.doc , Sati.text, input.data, vidisha
ii) Data type to be stroed :-
Data type is important to decide a type of file stream
classes to be used for handling the data. We should decide whether the data to be
handled is in the form of character are byte.
42
iii) Purpose :-
The purpose of using file must also deciding it for example :-
We should know whether the file is created for reading only or writing only or
both operation.
iv) Method of creating a file or File opening methods :-
There are two methods for
creating a file.
b) Direct method
c) Indirect method
a) Direct method :- This method use constructors and we provide the name of file.
File_inputstream fis;
try
{
fis=new fileinputstream(“test.dat”);
…………………..
…………………..
}
catch (IOExceptione)
{
………………….
}
b) Indirect method :- This approach use the file that has been initiated desired file
name.
File Infile;
Infile= new(“test.dat”);
Fileinputstream fis;
try
{
fis= new fileinputstream(infile);
………………………
……………………….
}

Random Access File 


Java support Random access file class in java.io package that
can be used for reading and writing data with random access such files are known as
random access file. A random access purpose a file can be created and opened are
random access by giving a mode string as a parameter to the constructor when we open
the file we can use one of the following two mode strings :-
i) “r” :- For reading only.
ii)”rw” :- For both reading and writing.
Random access file supports a pointer known as file pointer that can be move to
specified position for reading and writing file. The file pointer is moved using a method
seek( ) in the random access class. When the random access file is opened. We use the
following syntax :-
Obj1=new RandomAccessFile(“filename”,”rw”);
The file pointer is automatically positioned at the beginning of the file.
// Program for finding the size of file //
import java.io.*;
class sizeoffile
{
43
public static void main(String args[])
{
RandomAccessFile obj1;
Try
{
obj1=new RandomAccessFile(“abc”,”rw”);
n=obj1.length( );
System.out.println(n);
obj1.close( );
}
catch(IOException e)
{
System.out.println(e);
}
}

JDBC –ODBC Bridge 


Since the database is MS-Access a microsoft product a 32 bit
ODBC driver is used to communicate with the tables held within the database.
Create the database :-
 Choose Start program, Microsoft Access.
 Choose the option ‘Bland Database’ since a new database file needs to be create.
Then click on the ‘OK’ button.
 Give the name of the database file as ‘INVENTORY’ and also specify the path
where the file has to be saved. This will create a database file called
‘Inventory.mdb’.
 To create a table within the database file ‘Inventory.mdb’ click on the option
Table and then click on the option ‘New’
 Choose the option ‘Design View’ to create the structure of the table.
 Specify the structure of the table to be created.
 Specify the primary key if needed by clicking on the file name and the ‘Key’ icon
on the tool bar.
 Save the table as ‘ProductMaster’.
 The table ‘ProductMaster’ has been created within the database file
‘Inventory.mdb’.
 To add test records, click on the option ‘Option’.
Next create a 32 bit ODBC driver :-
Create the 32 bit ODBC driver via which the Java UI will communicate with the database
table as described in the following pages.
The steps for creating the 32 bit ODBC driver on a Window95/98 computer is as follows:
• Click on ‘Start’, go to ‘Setting’ and select ‘Control Panel’.
• Select the ‘ODBC Data Source(32 bit)’ from the Control Panel. When this is done
the ODBC administrator interface will open.
• The ODBC data source administrator allows the creation of several types of
Named Data Sources. Select ‘System DSN’ from the tabbed notebook.
• Once the System DSN page is selected from the ‘Tabbed Notebook’, click on the
‘Add’ button on the interface.
• This will open up another interface, which will display all the ODBC drivers
installed on the current computer. Each ODBC driver will communicate
effectively with the database for which the driver was built.
• Select the appropriate driver, in this case Microsoft Access Driver [.mdb].

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.

The Connectivity Model 

Java Application 32-bit The Access


The user interface ODBC Database
Access and Its
Driver tables

Java’s Driver Manager, Responsible for setting up the


JDBC:ODBC bridge
The Java application is the UI. This is turn communicates with a driver manager using
underlying Java code. The DriverManager is a class that belongs to the java.sql package.
The driver manager in turn communicates with the 32-bit ODBC driver. The 32-bit
ODBC driver in turn communicates with the Access databse, and its tables.
The functionality of java’s driver manager and how this communicates with an
appropriate database driver needs to be understood to be able to deal effectively with
JDBC.
Using Java’s Driver Manager to connect to a Database :
The Java Driver manager The ODBC System DSN The Access Database,
table, with Data in it

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>)

Navigating the Resultset Object’s Contents 


A ResultSet is composed of
zero, one or multiple rows returned from the databases. This object is created in memory
and hence its data cannot be seen. To see the data held within the ResultSet object its
each must be read and its contents written to the command line.
Using a loop does this. Each row of the ResultSet is scanned one by one and the contents
of each row written to the command line.
A ResultSet object is created when SQL statements are executed against the DBMS.
Executing the statement object can also create a ResultSet. Closing the ResultSet objecdt
release all data associated with it.
The rs.next( ) method, placed in a loop fetches one row at time which can be then printed
out at the command line for viewing. The ResultSet pointer is initially positioned before
its first row. A call to the next( ) method is required to access the first row. After the first
call, the first row becomes the current row, and is ready to be processed. Successive calls
to the next( ) method fetches the subsquent rows. The method retruns false when there are
no more rows available in the ResultSet.
A combination of the methods of the UI and the methods of the ResultSet object, enable
the UI to manipulate data in the ResultSet. The data in the ResultSet is tightly bound to
data in the table. This binding in via the connection obnect. This is a fairly standard
model used for connecting a Java UI with an ODBC compaint database, table using a
JDBC:ODBC bridge.

The User Interface :[Product Master Form]

Proid :

Remarks :

The ResultSet Object O The Access


D Database an
B Tables
Connection
C

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.

HTTP FTP TELNET ECHO

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.

RMI (Remote method invocation) 


RMI is a simple method used for
developing and deploying distributed object applications in a java environment.
Creating a distributed object application using RMI is as simple as writing a stand
alone java application.
Remote method invocation(RMI) enables a programmer to create distributed java
applications, in which the methods of remote java objects can be called from other
java Virtual machines running either on the same host or on different hosts scattered
across a 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 

Client Application Server Application

Client Stub Server Skeleton

Remote Reference Layer Remote Reference Layer

Transport Layer

The RMI Layers

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

Вам также может понравиться