0% found this document useful (0 votes)
63 views

Java AOOP

Java is an object-oriented programming language that is similar to C and C++ but is not the same as them. Java code is compiled into bytecode that runs on a Java Virtual Machine (JVM) which provides portability so that Java programs can run on any device that supports a JVM. The key aspects of Java are that it is portable, object-oriented, high performance due to just-in-time compilation, robust, simple, secure and multithreaded. A simple "Hello World" Java program is provided as an example of how to write, compile and run a Java program.

Uploaded by

Dewsun Riseon
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
63 views

Java AOOP

Java is an object-oriented programming language that is similar to C and C++ but is not the same as them. Java code is compiled into bytecode that runs on a Java Virtual Machine (JVM) which provides portability so that Java programs can run on any device that supports a JVM. The key aspects of Java are that it is portable, object-oriented, high performance due to just-in-time compilation, robust, simple, secure and multithreaded. A simple "Hello World" Java program is provided as an example of how to write, compile and run a Java program.

Uploaded by

Dewsun Riseon
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 76

Prepared By: Shiba R.

Tamrakar

Note: It is assumed that the students have some basic knowledge of C and C++ so
some common keywords and other concepts are skipped (like loop, array etc if
required do refer to class room note).

What is Java?
 Java is a high-level, third generation programming language.
 Compared to other programming languages, Java is most similar to C. However
although Java shares much of C's syntax, it is not C. Knowing how to program in
C or, better yet, C++, will certainly help you to learn Java more quickly, but you
don't need to know C to learn Java. \
 Unlike C++ Java is not a superset of C. A Java compiler won't compile C code,
and most large C programs need to be changed substantially before they can
become Java programs.
 What's most special about Java in relation to other programming languages is
that it lets you write special programs called applets that can be downloaded
from the Internet and played safely within a web browser.
 A Java applet cannot write to your hard disk without your permission. It cannot
write to arbitrary addresses in memory and thereby introduce a virus into your
computer. It should not crash your system.

The ByteCode and JVM (Java Virtual Machine)


 An imaginary machine that is implemented by emulating software on a real
machine
 It provides the hardware platform specifications to which you compile all java
technology code.
 JVM is an interpreter for bytecode.
 Bytecode is a highly optimized set of instructions designed to be executed
by the Java run-time system i.e. Java Virtual Machine (JVM).
 Independent of any particular computer hardware, so any computer with a
java interpreter can execute the compiled java program, no matter what type
of computer program was compiled on.
 ByteCode and JVM are the key that allows java to solve both the security and
the portability problems.
 The reason is straightforward: only the JVM needs to be implemented for
each platform.
 The details of the JVM will differ from platform to platform, but all
interpret the same Java bytecode.
 The fact that a Java program is interpreted also helps to make it secure.
Because the execution of every Java program is under the control of the JVM,
the JVM can contain the program and prevent it from generating side effects
outside of the system.
 Safety is also enhanced by certain restrictions that exist in the Java language.
 When a program is interpreted, it generally runs substantially slower than
it would run if compiled to executable code.
 With Java, differential between the two is not so great.
 Although Java was designed for interpretation, there is technically nothing
about Java that prevents on-the-fly compilation of bytecode into native code.
 Just in Time (JIT)
o Sun supplies its Just In Time (JIT) compiler for bytecode, which is
included in the Java 2 release.

1
Prepared By: Shiba R. Tamrakar

o When the JIT compiler is part of the JVM, it compiles bytecode into
executable code in real time, on a piece-by-piece, demand basis.
o It is important to understand that it is not possible to compile an entire
Java program into executable code all at once, because Java
performs various run-time checks that can be done only at run time.
o Just-in-time approach still yields a significant performance boost.
o Even when dynamic compilation is applied to bytecode, the portability
and safety features still apply, because the run time system which
performs the compilation still is in charge of the execution environment.

Java Source Code


Compiled
Bytecode Filename.class
Pass to JVM
Other Components
of JVM
JIT Compiler

Interpreted or JIT
compilation
Executable Code

Fig.: Demonstration of JVM’s Functionality (Java2)


Features of Java
 Architecture-Neutral
o A central issue for the Java designer was that of code longevity and
portability.
o Software Industry is rapidly changing s/w tools.
o JVM helps java to be run from one system to another.
o If the architecture of the Hardware or OS changes, only the JVM will be
changed and the current program will correctly.
 Distributed
o Java is designed for the distributed environment of the Internet, because
it handles TCP/IP protocols.
o RMI feature of Java helps the programmer to design distributed software.
 Dynamic
o Java programs carry with them substantial amount of run time type
information that is used to verify and resolve accesses to objects at run
time.
o This makes it possible to dynamically link code in a safe and convenient
manner.
 Interpreted and High Performance
o Java enables the creation of cross-platform programs by compiling into an
intermediate representation called Java bytecode.
o This code can be interpreted on any system that provides a JVM.
o Relative to other interrelated languages like BASIC and Perl Java
interpretation gives high performance.
 Multithreaded
o Java was designed to meet the real world requirement of creating
interactive, networked programs.

2
Prepared By: Shiba R. Tamrakar

o To accomplish this, Java supports multithreaded programming, which


allows us to write programs that do many things simultaneously.
 Object Oriented
o Java is purely object oriented language because any program created in
java must have class.
 Portable
o JVM feature in Java provides the portability facility.
o Even though every operating system has different architecture JVM
behaves as intermediate between Java bytecode and the OS.
 Robust
o The multi-plat formed environment of the web places extraordinary
demands on a program, because the program must execute reliably in a
variety of systems.
o Java can be used in multiple purpose software development
 Simple
o Java inherits the features of C and C++ so most of the coding in Java is
similar to C and C++
o If any one has some Idea on C and C++ then learning java is simple.
o Even though if you don’t know C and C++ you can learn Java easily
 Security
o Java also provides security up to some extents. Since all the programs of
Java runs under JVM, the program cannot do any side effect outside JVM.

First program in Java


//HelloWorld.java
class HelloWorld {

public static void main (String args[]) {


System.out.println("Hello World!");
}

}
 The goal of this program is not to learn how to print words to the terminal. It's to
learn how to type, save and compile a program.
 To write the code you need a text editor. You can use any text editor like
Notepad, Brief, emacs or vi or notepad. Personally I use vi on Linux or
kawa,Textpad,editplus on Windows.
 You should not use a word processor like Microsoft Word or WordPerfect since
these save their files in a proprietary format and not in pure ASCII text. If you
absolutely must use one of these, be sure to tell it to save your files as pure text.
Generally this will require using Save As... rather than Save.
 When you've chosen your text editor, type or copy the above program into a new
file. For now type it exactly as it appears here. Like C and unlike Fortran, Java is
case sensitive so System.out.println is not the same as system.out.println.
CLASS is not the same as class, and so on.
 However, white space is not significant except inside string literals. The exact
number of spaces or tabs you use doesn't matter.
 Save this code in a file called HelloWorld.java.

Compiling and Running Hello World


 To make sure your Java environment is correctly configured, bring up a
command-line prompt and type

3
Prepared By: Shiba R. Tamrakar

javac null.java

 If your computer responds with

error: Can't read: null.java

 you're ready to begin. If, on the other hand, it responds

javac: Command not found

 or something similar, then you need make sure you have the Java environment
properly installed and your PATH configured.
 Assuming that Java is properly installed on your system there are three steps to
creating a Java program:

1. writing the code


2. compiling the code
3. running the code

 Under Unix, compiling and running the code looks like this:
$ javac HelloWorld.java
$ java HelloWorld
Hello World
$
 Under Windows, it's similar. You just do this in a DOS shell.
C:> javac HelloWorld.java
C:> java HelloWorld
Hello World
C:>
 Notice that you use the .java extension when compiling a file, but you do not use
the .class extension when running a file.

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. On Unix it should look something like this:

CLASSPATH=.:/usr/local/java-1.6/lib

 Under Windows it will probably look something like this

C:\JDK\JAVA\CLASSES;c:\java\lib\classes.zip

 Under Unix you set CLASSPATH variables like this:

csh: % setenv CLASSPATH my_class_path

sh: % CLASSPATH=my_class_path

4
Prepared By: Shiba R. Tamrakar

 You'll probably want to add one of these lines to your .login or .cshrc file so it will
be automatically set every time.
 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

 The CLASSPATH variable is also important when you run Java applets, not just
when you compile them. It tells the web browser or applet viewer where it should
look to find the referenced .class files. If the CLASSPATH is set improperly, you'll
probably see messages like "Applet could not start."
 If the CLASSPATH environment variable has not been set, and you do not specify
one on the command line, then Java sets the CLASSPATH to the default:

 Unix: .:$JAVA/classes:$JAVA/lib/classes.zip
 Windows: .:$JAVA\classes:$JAVA\lib\classes.zip
 Mac: ./$JAVA:classes/$JAVA:lib:classes.zip

 Here . is the current directory and $JAVA is the main Java directory where the
different tools like javac were installed.

String

 In Java a string is a sequence of characters as usual. But, unlike many other


languages that implement strings as character arrays, Java implements string
as objects of type String.
 Implementing string as built-in objects allows Java to provide a full
complement of features that make string handling convenient.
 For example, Java has methods to compare two strings, search for a
substring, concatenate two strings, and change the case of letters within a
string.
 Also, String objects can be constructed a number of ways, making it easy to
obtain a string when needed.
 When we create a String object, we are creating a string that cannot be
changed.
 Even though the characters contained cannot be changed, we can still
perform all types of string operations.
 The difference is that each time you need an altered version of an existing
string, a new String approach is used because fixed, immutable strings can be
implemented more efficiently that changeable ones.
 It is defined in java.lang. Thus, there are available to all class automatically.

Similarities between String and StringBuffer

 Both the String and String Buffer are the classes


 Both are defined in java.lang.
 Both are declared final, which means that neither of these classes may be
sub-classed.

String Constructors
String s=new String( )

5
Prepared By: Shiba R. Tamrakar

String s=new String(char_array[ ])


String(char char_array[ ], int startIndex, int numChars)
String(String strObj)
String(byte asciiChars[ ])
String(byte asciiChars[ ], int startIndex, int numChars)

String Methods
length( )
toString( )
o By overriding toString( ) for classes that we create, we allow them to be
fully integrated into Java’s programming environment.
o If you have created toString( ) method in any class, and you call the
object without specifying any method of the class then toString( ) method
is automatically invoked.
Example
Box b=new Box(10);
System.out.println(b); //This line will print the string which will be
returned by toString( ) method of class b automatically.

Character Extraction
charAt(int where)
getChars(int sourceStart, int sourceEnd, char targer[ ], int targetStart)
Example
Class getCharsDemo
{
Public static void main(String args[ ])
{
String s=”This is a demo of the getChars method.”;
Int start=10;
Int end=14;
Char buf[ ]=new char[end-start];

s.getChars(start,end,buf,0);
System.out.println(buf);
}
}

getBytes( )
o There is an alternative to get Chars( ) that stores the characters in an
array of bytes.
o It uses the default character to byte conversion provided by the platform.
byte[ ] getBytes( )
toCharArray( )

String comparison
equals( )
o To compare two strings for equality.
boolean equals(Object str)
equalsIgnoreCase(String str)
Comparison between equals( ) and ==
o The equals( ) method compares the characters inside a String object.

6
Prepared By: Shiba R. Tamrakar

o The == operator compares two object references to see whether they


refer to the same instance.
Example
Class EqualsNotEqualTo
{
String s1=”Hello”;
String s1=new String(s1);

System.out.println(s1+”equals”+s2+”->”+s1.equals(s2));
System.out.println(s1+”==”+s2+”->”+s1==s2);
}
Int indexOf(int ch)
Int lastIndexOf(int ch)
Int indexOf(String str)
Int lastIndexOf(String str)
String substring(int startIndex)
String substring(int startIndex, int endIndex)
String Concat(String str)
String replace(char original, char replacement)
String str.trim( )

StringBuffer
 It is a peer class of String that provides much of the functionality of strings.
 In contrast to String StringBuffer represents grow able and writeable
character sequences.
 It may have characters and substrings inserted in the middle or appended to
the end.
 It will automatically grow to make room for such additions and often has
more characters per allocated than are actually needed, to allow room for
growth.
StringBuffer Constructors
StringBuffer( )
StringBuffer(int size)
StringBuffer(String str)

Converting Strings to Numbers

When processing user input it is often necessary to convert a String that the user
enters into an int. The syntax is straightforward. It requires using the static
Integer.valueOf(String s) and intValue() methods from the java.lang.Integer class.
To convert the String "22" into the int 22 you would write

int i = Integer.valueOf("22").intValue();

Doubles, floats and longs are converted similarly. To convert a String like "22" into
the long value 22 you would write

long l = Long.valueOf("22").longValue();

To convert "22.5" into a float or a double you would write:

7
Prepared By: Shiba R. Tamrakar

double x = Double.valueOf("22.5").doubleValue();
float y = Float.valueOf("22.5").floatValue();

The various valueOf() methods are relatively intelligent and can handle plus and
minus signs, exponents, and most other common number formats. However if you
pass one something completely non-numeric like "pretty in pink," it will throw a
NumberFormatException. You haven't learned how to handle exceptions yet, so try
to avoid passing theses methods non-numeric data.

You can now rewrite the E = mc2 program to accept the mass in kilograms as user
input from the command line. Many of the exercises will be similar.

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

double c = 2.998E8; // meters/second


double mass = Double.valueOf(args[0]).doubleValue();
double E = mass * c * c;
System.out.println(E + " Joules");
}
}

Here's the output:

$ javac Energy.java
$ java Energy 0.0456
4.09853e+15 Joules

Testing for Equality with equals()

That's not what you expected. To compare strings or any other kind of object you
need to use the equals(Object o) method from java.lang.String. Below is a corrected
version that works as expected. The reasons for this odd behavior go fairly deep into
Java and the nature of object data types like strings.

class JackAndJill {

public static void main(String args[]) {

String s1 = new String("Jack went up the hill.");


String s2 = new String("Jack went up the hill.");

if ( s1.equals(s2) ) {
System.out.println("The strings are the same.");
}
else {
System.out.println("The strings are not the same.");
}
}
}

8
Prepared By: Shiba R. Tamrakar

Vector
 An array is a collective type of variable which stores data in sequential
memory blocks. Index is used to access any value in array
 ArrayList is class that extends AbstractList and implements the List interface
which s
 Vector implements a dynamic array which is similar to ArrayList.
 Vector constructors:
Vector( )
Vector(int size)
Vector(int size, int incr)
Vector(collection c)
 Vector ( ): Default vector which has an initial size of 10.
 Vector (int size): Vector whose initial capacity is specified by size.
 Vector (int size, int incr): vector whose initial capacity is specified by size
and whose increment is specified by incr. The increment specifies the number
of elements to allocate each time that a vector is resized upward.
 Vector (Collection c): Vector that contains the elements of collection c.
 When an object is to store on the vector and there is no space or have less
space to store those objects then these no. of elements is automatically
incremented.
 By default the vector size is incremented by doubled by each allocation cycle.
 Vector’s protected data members
int capicityIncrement;
int elementCount;
Object elementData[ ];
 capacityIncrement: The increment value is stored in it.
 elementCount: The no. of elements currently in the vector is stored in it.
 elementData: the array that holds the vector stored in it
 Methods
Void addElement(Object element)
The object specified by the element is added to vector
Int capacity( )
The maximum number of elements that the vector can hold
Boolean contains(Object element)
Return true if element is contained by vector
void copyInto(Object array[ ])
Copy the content to an array
Object elementAt(int index)
Object firstElement( )
int indexOf(Object element)
Boolean isEmpty( )
Object LastElement( )
int LastIndexOf(object element)
void removeAllEments( )
void removeElementAt(int index)
void setElementAt(Object element, int index)
int size( )
String toString( )

Difference between vector and Array


Vector Array
1. It is dynamic 1. It is fixed in size

9
Prepared By: Shiba R. Tamrakar

2. It is a class and we can create its 2. It is a collective data type.


object instances
3. It can store multiple type of data in 3. It can store only on data type in single
single vector Array

Two differences between Vector class and ArrayList


1. Vector is synchronized and it contains many legacy methods that are not part
of the collection framework.
2. In Java 2 Vector is fully compatible to collection as it extends AbstractList and
implement the List interface.

Difference between class, Abstract Class and Interface


Concrete Class Abstract Class Interface
 Specify the full  Specify the full set  Specifies a subset of methods
set of methods of methods for an for an object
for an object object
 Implements all  Implements none,  Implements none of its methods
of its methods some, or all of its
methods
 Can have  Cannot have  Cannot have instances
instances instances
 Can have  Must have  Cannot have subclasses; must
subclasses subclasses; have classes that implement it;
otherwise useless useless otherwise

Multithreading

Introduction to Multithreading
 A multithreaded program contains two or more parts that can run
concurrently.
 Each part of such a program is called a thread, and each thread defines a
separate path of execution.
 Multithreading is a specialized form of multitasking
What are the differences between Processes based multitasking and thread
based multitasking?

Process based Multitasking Thread based Multitasking


 A process is, in essence, a program  A single program can perform two or
that is executed. Thus process based more tasks simultaneously.
multitasking is the feature that
allows our computer to run two or
more programs concurrently.
 For example, process based  For example, a text editor can
multitasking enables us to run the format text at the same time that it
Java compiler at the same time that is checking the spelling.
we are using a text editor.
 A program is the smallest unit of  The thread is the smallest unit of
code that can be dispatched by the dispatch able code.
scheduler
 It deals with the “big picture”  It handles the details within the
program

10
Prepared By: Shiba R. Tamrakar

 It requires more overheads than  It requires less overhead than


thread based Multitasking process based Multitasking
 It is heavily weighted tasks that  It is light weight and shares the
require their own separate address same address space and
spaces cooperatively share the same
heavyweight process.
 Inter process communication is  Inter thread communication is
expensive and limited inexpensive, and context switching
from one thread to the next is low
cost.
 It is not under the control of Java  It is under the control of Java
 It relatively west more CPU time.  It enables us to write very efficient
programs that make maximum use
of the CPU, because idle time can be
kept to a minimum.
 It have to finish the current task to  It can handle multiple tasks
start another task with in a program concurrently without requiring
finishing the current tasks.

What is the difference between multithreading and multitasking?


Multitasking Multithreading
 Multitasking is a broader term than  Specialized form of multitasking.
multithreading. Multitasking provides Multithreading is program that
multiple tasks to be done contains two or more parts that can
concurrently. run concurrently. Each part of such a
program is called thread.

The Java Thread Model


 Java run-time system depends on threads for many things, and all the class
libraries are designed with multithreading in mind.
 Java uses threads to enable the entire environment to be asynchronous. This
helps reduce inefficiency by preventing the waste of CPU cycles.
 Single-thread systems use an approach called an event loop with polling.
 In this model a single thread of control runs in an infinite loop, polling a single
event queue to decide what to do next.
 Once this polling mechanism returns with, say a signal that a network file is
ready to be read, then the event loop dispatches control to the appropriate
event handler.
 Until this event handler returns, nothing else can happen in the system.
 This wastes CPU time. It is also in one part of a program dominating the
system and preventing any other events from being processed.
 In general, in a singled-threaded environment, when a thread blocks because
it is waiting for some resource, the entire program stops running.
 The benefit of Java’s multithreading is that the main loop/polling
mechanism is eliminated.
 One thread can pause without stopping other parts of your program.
 For example, the idle time created when a thread reads data from a network
or waits for user input can be utilized elsewhere.
 Multithreading allows animation loops to sleep for a second between each
frame without causing the whole system to pause.

11
Prepared By: Shiba R. Tamrakar

 When a thread blocks in a Java program only the single thread that is blocked
pauses.
 All other threads continue to run.
 Threads exist in several states.
o A thread can be running.
o A thread can be ready to run as soon as it gets CPU time.
o A thread can be suspended, which temporarily suspends its activity.
o A suspended thread can then be resumed, allowing it to pick up where
it left off.
o A thread can be blocked when waiting for a resource.
o At any time, a thread can be terminated, which halts its execution
immediately.

Characteristics of Thread
Thread in java have five Characteristics, they are:
 Thread body
 Thread state
 Thread priority
 Daemon Threads
 Threads group.

Thread Body
This is the sequence of instructions for thread to perform. This is defined in (
) method. There are two ways to supply a run method to a thread.
1. Extending a thread class and overriding the run( ) method,
2. Creating a thread by implementing the Runable interface.

Waiting
Runnable blocked IO blocked
New
Ready List
wait
Wait( )
yield( )
start( )

Suspended suspended( )

sleep sleep( )
Runnig

Dead

Fig: Thread states

Thread States
Every thread, after creation and before destruction, will always be in one of the six
states. They are:
 New
 Runnable

12
Prepared By: Shiba R. Tamrakar

o Ready
o Running
 Waiting
o Blocked
o Sleep
o Suspended
o Wait
 Dead
New
 A enters the newly created by using a new operator.
 It is in new state or born state immediately after creation; that is when a
constructor is called the Thread is created but is not yet to run ( ) method
will not begin until its start ( ) method is called.
 After the start ( ) method is called, the thread will go to the next state,
Running state.
Runnable
Ready
o Once the start ( ) method is invoked, the new thread is appended to
Queue (Ready List).
o When it is in queued state, it is waiting in the queue and competing for
its turn to spend CPU cycles.
o It is controlled by Virtual Machine Controller.
Running
 When the thread is running state, it is assigned by CPU cycles and is actually
running.
 When we use the yield ( ) method it makes sure other threads of the same
priority have chance to run.
 This method causes voluntary move itself to the queued state from the
running state.
Waiting states
 The waiting state is entered when one of the following events occurs:
o The thread itself or another thread calls the wait ( ) method.
o The thread itself calls the sleep( ) method
o The thread is waiting for some IO operation to complete.
o The thread will join ( ) another thread.
o The thread itself or another thread calls the suspend ( ) method.
 The thread in a block state will not be scheduled for running.
 It will go back to the Ready Queue when its cause of block is completed.
o If the thread is blocked by calling wait ( ) method, the object’s notify
( ) and noifyAll ( ) method is called.
o If a thread has been put to sleep, the specified number of milliseconds
must expire.
o If the thread is blocked on I/O, the specified I/O operation is
completed.
o If the thread is suspended, another thread calls its resume ( )
method.
Dead
 A thread is dead for any one of the two reasons:
o It dies a natural death because the run method exits normally.
o It dies an abnormally because uncaught exception terminates the run
method.
 In particular the stop ( ) method is used to kill the thread.
 We can use interruption for terminating the thread.

13
Prepared By: Shiba R. Tamrakar

 To find whether a thread is alive that is currently in runnable or Blocked state,


use the threads isAlive ( ) method, if it returns true the thread is alive.

Thread Priority
 Every thread in java is assigned a priority value, when more than one thread
is competing for CPU time; the thread with highest priority value is given
preference.
 You can also use the Thread class constants.

Constants Integer value
Thread.MIN_PRIORITY 1
Thread.MAX_PRIORITY 10
Thread_NORM_PRIORITY 5

 The setPriority ( ) method is used to set the priority value of a thread


 The getPriority ( ) method is used to get the priority of the thread.
 The default priority is Thread.NORM_PRIORITY.

Daemon Thread
 This denotes that a thread is a “server” thread.
 A server thread is a thread that services client request.
 They normally enter an endless loop waiting for clients requesting services.
 To create a daemon Thread, call the setDaemon ( ) method after the thread
creation and before the execution is started.
 The syntax is
setDaemon (boolean b)
o If b is true, the thread is marked as daemon thread. Otherwise, it is a
non-daemon thread.
 isDaemon ( ), this method returns true if this thread is a daemon else return
false.

Thread Group
 For large programs that generate many things, java allows us to group similar
threads and manage them as a group.
 Every thread instance is a member of exactly one thread group.
 When a program is started, the java virtual machine creates the main thread
group as a member of the system thread group.
 A new thread group is created by instantiating the ThreadGroup class.
 The getThreadGroup ( ) returns the parent thread group of the thread.
o getParent( ) returns the parent Thread group of the thread group
o getName ( ) returns the name of the thread group.
 The thread class defines several methods that help us to manage threads.

Method Description
Getname( ) Obtain the threads name
setName( ) Set the name of a thread
isAlive( ) Determine if the thread is still running
join( ) Wait for thread to terminate
sleep( ) Suspend a thread for specified time
Start Start a thread by calling its run Method
wait( ) This is used to make a thread wait.

14
Prepared By: Shiba R. Tamrakar

notify( ) This is used to wake a thread that is


waiting
notifyall( ) This is used to wake all the threads that
are waiting

Why to use Runnable interface.

Using the Runnable interface is a bit more complicated but it has two
advantages:

 The thread's run( ) method has access to the private variables of the class in
which it is located
 Since Java only has single inheritance, you may not be able to subclass
Thread if you also want your class to subclass something else. For example,
you cannot create an applet which is a subclass of Thread because your
applet is already a subclass of the Applet class.

15
Prepared By Shiba R. Tamrakar copy () left

Chapter 2 (Applet)
What is an Applet
Applets are small Java programs that are primarily used in Internet computing.
They can be transported over the Internet from one computer to another and run
using the Applet Viewer or any Web browser that supports Java. Applet, like any
application program, can do many things for us.

Java.lang.Object

Java.awt.Component

Java.awt.Container

Java.awt.panel

Java.applet.Applet

Fig. The Class Hierarchy of Applet

How Applets Differs from Applications


Although both the applets and stand-alone applications are Java programs, there
are significant differences between them. Applets are not full-featured application
programs. They are usually written to accomplish a small task or a component of
task. Since they are usually designed for use on the Internet, they impose certain
limitations and restriction in their design.

 Applets do not use the main ( ) method for initiating the execution of the
code. Applets, when loaded, automatically call certain methods of Applet class
to start and execute the applet code.
 Unlike stand-alone applications, applets cannot be run independently. They
are run from inside a Web page using a special feature known as HTML tabs.
 Other points are given below in Security Restrictions

What Applets Can and Can't Do

Security Restrictions
Every browser implements security policies to keep applets from
compromising system security. This section describes the security policies that
current browsers adhere to. However, the implementation of the security policies
differs from browser to browser. Also, security policies are subject to change. For
example, if a browser is developed for use only in trusted environments, then its
security policies will likely be much more lax than those described here.
Current browsers impose following restrictions on any applet that is loaded over the
network:
 An applet cannot load libraries or define native methods.
 It cannot ordinarily read or write files on the host that's executing it.
 It cannot make network connections except to the host that it came from.
 It cannot start any program on the host that's executing it.
 It cannot read certain system properties.
 Windows that an applet brings up look different than windows that an
application brings jp.

Elective BE7 (Advanced Programming) 1


Prepared By Shiba R. Tamrakar copy () left

Each browser has a SecurityManager object that implements its security policies.
When a SecurityManager detects a violation, it throws a SecurityException. Your
applet can catch this SecurityException and react appropriately.

Applet Capabilities
The java.applet package provides an API that gives applets some capabilities
that applications don't have. For example, applets can play sounds, which other
programs can't do yet.
Here are some other things that current browser and other applet viewers let applets
do:
 Applets can usually make network connections to the host they came from.
 Applets running within a Web browser can easily cause HTML documents to be
displayed.
 Applets can invoke public methods of other applets on the same page.
 Applets that are loaded from the local file system (from a directory in the
user's CLASSPATH) have none of the restrictions that applets loaded over the
network do.
 Although most applets stop running once you leave their page, they don't
have to.

Life Cycle of the Applet

Loading the Applet


When an applet is loaded, here's what happens:

 An instance of the applet's controlling class (an Applet subclass) is created.


 The applet initializes itself.
 The applet starts running.

Leaving and Returning to the Applet's Page


When the user leaves the page -- for example, to go to another page -- the
applet has the option of stopping itself. When the user returns to the page, the
applet can start itself again. The same sequence occurs when the user iconifies and
then reopens the window that contains the applet. (Other terms used instead of
iconify are minaturize, minimize, and close.)

Reloading the Applet


Some browsers let the user reload applets, which consists of unloading the applet
and then loading it again. Before an applet is unloaded, it's given the chance to stop
itself and then to perform a final cleanup, so that the applet can release any
resources it holds. After that, the applet is unloaded and then loaded again, as
described in Loading the Applet, above.

Methods for Milestones


public class Simple extends Applet {
...
public void init( ) { . . . }
public void start( ) { . . . }
public void stop( ) { . . . }
public void destroy( ) { . . . }
...
}

Elective BE7 (Advanced Programming) 2


Prepared By Shiba R. Tamrakar copy () left

The Simple applet, like every other applet, features a subclass of the Applet
class. The Simple class overrides four Applet methods so that it can respond to major
events:
init
To initialize the applet each time it's loaded (or reloaded).
start
To start the applet's execution, such as when the applet's loaded or when the
user revisits a page that contains the applet.
stop
To stop the applet's execution, such as when the user leaves the applet's page
or quits the browser.
destroy
To perform a final cleanup in preparation for unloading.

Important Note on init and Constructor


 The init method is useful for one-time initialization that doesn't take very
long.
 In general, the init method should contain the code that you would normally
put into a constructor.
 The reason applets shouldn't usually have constructors is that an applet
isn't guaranteed to have a full environment until its init method is called.
 For example, the Applet image loading methods simply don't work inside of an
applet constructor.
 The init method, on the other hand, is a great place to call the image loading
methods, since the methods return quickly.

paint( ) stop( ) destroy( )


init( )

Begin Running Idle Dead


start( ) start( )

Fig: Life Cycle of Applet


Applet Tag format in HTML
<Applet
[codebase=codebaseURL]
code=Applet_file
[Alt=alternate text]
[Name=applet_Instance_name]
width=pixel
Height=pixel
[align=alignment]
[vspace=pixel]
[hspace=pixel]
>
[<param Name=Attributename value=attributevalue>]
[<param Name=Attributename value=attributevalue>]
...
</Applet>

Elective BE7 (Advanced Programming) 3


Prepared By Shiba R. Tamrakar copy () left

Examples

Sample Hello world Applet program (Example 1)


/*
Author: Shiba R. Tamrakar
Program: "hello world"
*/

import java.applet.*;
import java.awt.*; // required to paint on screen

public class HelloWorld extends Applet // Extending Applet class


{

public void init() //automatically calls init() class


{
// It is required but does not need anything.
}

// This method gets called when the applet is terminated


// That's when the user goes to another page or exits the browser.
public void stop()
{
// no actions needed here now.
}

// The standard method that you have to use to paint things on screen
// This overrides the empty Applet method, you can't called it "display" for example.

public void paint(Graphics g)


{
//method to draw text on screen
// String first, then x and y coordinate.
g.drawString("Hey hey hey",20,20);
g.drawString("Hellooow World",20,40);
}
}

Sample Applet Program to sum two given number.


// Sum.java
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;

public class Sum extends JApplet{


JButton add = new JButton("Add");
JTextField one = new JTextField(5);
JTextField two = new JTextField(5);
JTextField ans = new JTextField(5);
JLabel plus = new JLabel("+");

Elective BE7 (Advanced Programming) 4


Prepared By Shiba R. Tamrakar copy () left

JLabel equalsto = new JLabel("=");


JPanel jp = new JPanel();
public void init(){
jp.add(one);
jp.add(plus);
jp.add(two);
jp.add(equalsto);
jp.add(ans);
add.addActionListener(new ActionListener(){public void
actionPerformed(ActionEvent ae){
int x = Integer.parseInt(one.getText());
int y = Integer.parseInt(two.getText());
ans.setText(String.valueOf(x+y));
}
});
jp.add(add);
getContentPane().add(jp);
}
public void start(){
}
}

Sample Example to draw shapes with colors.


import java.awt.*;
import java.applet.*;
public class DrawExample extends Applet
{
Font bigFont; //font variable
Color redColor;
Color weirdColor;
Color bgColor;
public void init()
{
bigFont = new Font("Arial",Font.BOLD,16);
weirdColor = new Color(60,60,122);
bgColor = Color.blue;
}
public void stop()
{

}
public void paint(Graphics g)
{
g.setFont(bigFont);
g.drawString("Shapes and Colors",80,20);
g.setColor(redColor);
g.drawRect(100,100,100,100);
g.fillRect(110,110,80,80);
g.setColor(weirdColor);
/* a circle (int x, int y, int width, int height,int
startAngle, int arcAngle);*/
g.fillArc(120,120,60,60,0,360);
g.setColor(Color.yellow);
// Draw a line (int x1, int y1, int x2, int y2)
g.drawLine(140,140,160,160);

Elective BE7 (Advanced Programming) 5


Prepared By Shiba R. Tamrakar copy () left

// reset the color to the standard color for the next time
the applets paints
g.setColor(Color.black);
}
}

Sample program to draw line


import java.applet.*;
import java.awt.*;

public class DrawingLines extends Applet {

int width, height;

public void init() {


width = getSize().width;
height = getSize().height;
setBackground( Color.black );
}

public void paint( Graphics g ) {


g.setColor( Color.green );
for ( int i = 0; i < 10; ++i ) {
g.drawLine( width, height, i * width / 10, 0 );
}
}
}

Sample program Drawing different shapes objects


import java.applet.*;
import java.awt.*;

public class DrawingStuff extends Applet {

int width, height;

public void init() {


width = getSize().width;
height = getSize().height;
setBackground( Color.black );
}

public void paint( Graphics g ) {

// As we learned in the last lesson,


// the origin (0,0) is at the upper left corner.
// x increases to the right, and y increases downward.

g.setColor( Color.red );
g.drawRect( 10, 20, 100, 15 );
g.setColor( Color.pink );
g.fillRect( 240, 160, 40, 110 );

Elective BE7 (Advanced Programming) 6


Prepared By Shiba R. Tamrakar copy () left

g.setColor( Color.blue );
g.drawOval( 50, 225, 100, 50 );
g.setColor( Color.orange );
g.fillOval( 225, 37, 50, 25 );

g.setColor( Color.yellow );
g.drawArc( 10, 110, 80, 80, 90, 180 );
g.setColor( Color.cyan );
g.fillArc( 140, 40, 120, 120, 90, 45 );

g.setColor( Color.magenta );
g.fillArc( 150, 150, 100, 100, 90, 90 );
g.setColor( Color.black );
g.fillArc( 160, 160, 80, 80, 90, 90 );

g.setColor( Color.green );
g.drawString( "Groovy!", 50, 150 );
}
}

Sample program to Trapping mouse movement


import java.applet.*;
import java.awt.*;
import java.awt.event.*;

public class Mouse1 extends Applet


implements MouseListener, MouseMotionListener {

int width, height;


int mx, my; // the mouse coordinates
boolean isButtonPressed = false;

public void init() {


width = getSize().width;
height = getSize().height;
setBackground( Color.black );

mx = width/2;
my = height/2;

addMouseListener( this );
addMouseMotionListener( this );
}

public void mouseEntered( MouseEvent e ) {


// called when the pointer enters the applet's rectangular area
}
public void mouseExited( MouseEvent e ) {
// called when the pointer leaves the applet's rectangular area
}
public void mouseClicked( MouseEvent e ) {
// called after a press and release of a mouse button
// with no motion in between
// (If the user presses, drags, and then releases, there will be
// no click event generated.)

Elective BE7 (Advanced Programming) 7


Prepared By Shiba R. Tamrakar copy () left

}
public void mousePressed( MouseEvent e ) { // called after a button is pressed
down
isButtonPressed = true;
setBackground( Color.gray );
repaint();
// "Consume" the event so it won't be processed in the
// default manner by the source which generated it.
e.consume();
}
public void mouseReleased( MouseEvent e ) { // called after a button is released
isButtonPressed = false;
setBackground( Color.black );
repaint();
e.consume();
}
public void mouseMoved( MouseEvent e ) { // called during motion when no
buttons are down
mx = e.getX();
my = e.getY();
showStatus( "Mouse at (" + mx + "," + my + ")" );
repaint();
e.consume();
}
public void mouseDragged( MouseEvent e ) { // called during motion with buttons
down
mx = e.getX();
my = e.getY();
showStatus( "Mouse at (" + mx + "," + my + ")" );
repaint();
e.consume();
}

public void paint( Graphics g ) {


if ( isButtonPressed ) {
g.setColor( Color.black );
}
else {
g.setColor( Color.gray );
}
g.fillRect( mx-20, my-20, 40, 40 );
}
}

Java Applet program which will get input of semester and 5 different
subjects from web browser and display it in applet.

Java File
import java.awt.*;
import java.applet.*;
public class Question4 extends Applet
{
String Semester,Sub1, Sub2, Sub3, Sub4, Sub5;
public void init()
{
Semester=getParameter("Semester");
Sub1=getParameter("Sub1");

Elective BE7 (Advanced Programming) 8


Prepared By Shiba R. Tamrakar copy () left

Sub2=getParameter("Sub2");
Sub3=getParameter("Sub3");
Sub4=getParameter("Sub4");
Sub5=getParameter("Sub5");
}
public void paint(Graphics G)
{
G.drawString(Semester,10,30);
G.drawString(Sub1,10,50);
G.drawString(Sub2,10,70);
G.drawString(Sub3,10,90);
G.drawString(Sub4,10,110);
G.drawString(Sub5,10,130);
}
}
HTML File
<html>
<head>
<title>Question 4</title>
</head>
<body>
<applet code="Question4" width="250" height="150">
<param name= Semester value=5>
<param name= Sub1 value="Advance Programming. ">
<param name= Sub2 value="Computer Graphics.">
<param name= Sub3 value="Object Oriented Analysis and
Design.">
<param name= Sub4 value="Software Engineering.">
<param name= Sub5 value="Web Technology.">
</applet>
</body>
</head>
</html>

Elective BE7 (Advanced Programming) 9


Prepared By: Shiba R. Tamrakar Copy() left

Chapter 3 (AWT and Swing)

(Note: This document is dedicated for BE Computer 7th Sem. or BCA 5th Sem., so it is
assumed that the already have knowledge what is GUI Programming. Further discussion
on the example will be in class)

• AWT and Swing are two different classed used for develop GUI interfaces.
• All the part of GUI window are objects
• Every GUI is composed of three parts:
o The Interface (actual windows)
o The Engine (the underlying functionality of an application)
o The Listener ( the connection between the interface and the engine.)

Listener

Update
action
Upate to Method Call
Windows Return
values values

Interface
Engine

Fig: Working Model of GUI programming in Java

AWT
AWT stands for "Abstract Windowing Toolkit". It's main purpose is to provide the Java
programmer the means needed to generate the UI (User Interface) for their application
which will communicate with the user. The Abstract Window toolkit (AWT) contains
numerous classes and methods that allow us to create and manage windows. It is used to
support Applet window as well as GUI environment such as window. The AWT must reach
into the GUI components of the native OS, which means that it performs a task that an
applet cannot otherwise accomplish. An untrusted applet cannot make any direct calls
into an OS because otherwise it could do bad things to the user’s machine. The only way
an untrusted applet can access important functionality such as “draw a window on the
screen” is through calls in the standard Java library that’s been specially ported and
safety checked for that machine.

Swing
Swing is a set of classes that provides more powerful and flexible components that are
possible with the AWT.

Benefits of Swing
• Swing components are Beans (and thus use the Java 1.1 event model), so they can
be used in any development environment that supports Beans.
• Swing provides a full set of UI components.
• For speed, all the components are lightweight (no “peer” components are used),

BE Computer 7th/BCA 5th (Advance Programming) 1


http://www.shiba.com.np/java/javaGUI.pdf
Prepared By: Shiba R. Tamrakar Copy() left

• Swing is written entirely in Java for portability.


• Keyboard navigation is automatic – you can use a Swing application without the
mouse, but you don’t have to do any extra programming (the old AWT required some
ugly code to achieve keyboard navigation).
• Scrolling support is effortless – you simply wrap your component in a JScrollPane
as you add it to your form.
• Other features such as tool tips typically require a single line of code to
implement.
• Swing also supports something called “pluggable look and feel,” which means that
the appearance of the UI can be dynamically changed to suit the expectations of users
working under different platforms and operating systems. It’s even possible to invent
your own look and feel.
• If you’ve struggled long and hard to build your UI using Java 1.1, you don’t want to
throw it away to convert to Swing. Fortunately, the library is designed to allow easy
conversion – in many cases you can simply put a ‘J’ in front of the class names of each
of your old AWT components.

Difference between AWT and Swing


AWT Swing
• It have to use OS peer for each • We would have only one peer, the
components operating system's window object. All
of the buttons, entry fields, etc. are
drawn by the Swing package on the
drawing surface provided by the
window object.
• It consist of less code but • Swing has more code and program
programmer have to code extensively don’t have to code extensively
• AWT is a thin layer of code on top • Swing is much larger
of the OS, whereas Swing is much
larger
• It has less functionalities • Swing also has very much richer
functionality
• It is called Heavy weight • Swing components are called
programming because all the "lightweight" because they do not
components have their peer in OS. require a native OS object to
implement their functionality.
• JDialog and JFrame are
heavyweight, because they do have a
peer. So components like JButton,
JTextArea, etc., are lightweight
because they do not have an OS peer.
• For GUI-intensive work, AWT feels • Because Swing implements GUI
very primitive to work with compared functionality itself rather than relying
to Swing on the host OS, it can offer a richer
environment on all platforms Java
runs on.
• AWT is more limited in supplying • Swing us platform independent so
the same functionality on all it in not limited in supplying the same
platforms because not all platforms functionality on all platforms.
implement the same-looking controls
in the same ways.
• It has their own viewport which • It does not write itself to the
sends the output to the screen screen but redirect it to the
component it builds on

BE Computer 7th/BCA 5th (Advance Programming) 2


http://www.shiba.com.np/java/javaGUI.pdf
Prepared By: Shiba R. Tamrakar Copy() left

• Its components also have their • Its components don’t have z-


own z-ordering. ordering
• AWT and Swing in the same • AWT and Swing in the same
container. If you do, AWT will always container. If you do, Swing will always
be drawn on top of the Swing be drawn on Below the Swing
components. components.
• Its components are dependent to • Its components are not dependent
OS, so its appearance changes in to OS, so its appearance remains
different platform same in all the platforms
• AWT supports Ctrl-C Ctrl-V • In Swing, it requires page and
copy/paste without any coding. pages of bubblegum. Further you
can't do it at all in unsigned Swing
JApplets.
• AWT is supported in older version • Swing is bigger and more
of JVMs also. complicated, and is not supported by
earlier JVMs.
• With AWT you must not deal with • With Swing you must deal with the
the irritatingly pointless complexity of irritatingly pointless complexity of
ContentPanes. ContentPanes.
• They are faster in operation • They are slower because they
because it uses OS components have to draw all components them
self
• There are no equivalents in AWT. • Swing has JSpinner, JSlider and
JColorChooser.

Similarities between AWT and Swing


• There are no big architectural differences; the class hierarchy is almost the same.
The reason is that
o Swing is built upon AWT.
• Both AWT and Swing are used for GUI and window programming.

Fig: AWT Class Hierarchy

BE Computer 7th/BCA 5th (Advance Programming) 3


http://www.shiba.com.np/java/javaGUI.pdf
Prepared By: Shiba R. Tamrakar Copy() left

Fig: Swing Class Hierarchy

GUI Design Strategy


1. Identified Needed Components
2. Isolate regions of behavior
3. Sketch the GUI
4. Choose Layout Manager

Common Methods
• getSize() and setSize()
• getLocation() and setLocation()
• setVisible()
• setEnabled()
• setFont()
Basic swing Components
• Swing component classes can be found in javax.swing package.
• The component class name all begins with J.
• AWT and Swing components should not be combined.
• Non component object of AWT can be combined with Swing.
• Swing components are sub classes of java.awt.Container.
Type of Components
• Container Components (Applet, JFrame, JDialog)
• Ordinary Components or Atomic Components (JButton, JLabel etc.)
• Menu Components (Not included in course)

Container Component
• It can contain other components including other containers

BE Computer 7th/BCA 5th (Advance Programming) 4


http://www.shiba.com.np/java/javaGUI.pdf
Prepared By: Shiba R. Tamrakar Copy() left

• It uses layout managers for determining the size and position of child components.
JFrame
o Independent movable window.
o An application can contain 1 or more.
o Sample
public static void main(String[] args)
{
JFrame f= new JFrame(“Demo”);
f.setSize(300,400);
f.setVisible(true);
}

Note: pack() method resizes the frame to fit it's content and choose appropriate Layout
manager.
Example
public static void main(String args[])
{
JFrame f = new JFrame (“demo”);
f.setSize(300,250);
Container c = f.getContentPane();
c.setLayout(new FlowLayout());
c.add(new JButton(“#1”));
c.add(new JButton(“#2”));
f.setVisible(true);
}
JPanel
o In above example the Layout manager manages layout of container instead
of JFrame.
o Blank rectangular component that can contain other components.
o Each panel uses a separate layout manager.
o By default JPanel used FlowLayout manager.
o Example
public static void main(String args[])
{
JFrame f = new JFrame(“Cantent pane”);
f.setSize(350,250);
Container c=f.getContentPane();
c.setLayout(new GridLayout(2,1));
JPanel p= new JPanel();
p.setBackground(Color.LightGray);
p.add(new JButton(“#1”));
p.add(new JButton(“#2”));
c.add(p);
p.setBackground(Color.LightGray);
p.add(new JButton(“#1”));
p.add(new JButton(“#2”));
c.add(p);
f.setVisible(true);
}

Ordinary (Atomic) Components


• JLabel
• JButton
• JCheckBox
• JRadioButton
BE Computer 7th/BCA 5th (Advance Programming) 5
http://www.shiba.com.np/java/javaGUI.pdf
Prepared By: Shiba R. Tamrakar Copy() left

• JTextField
• JTextArea
• JComboBox
• JScrollBar
JLabel
• Simplest component type which will display text and/or image.
• Do not respond to user imput and do not emit events.

public static void main(String args[])


{
JFrame f = new JFrame(“JLabel Demo”);
Container c = f.getContentPane();
c.setLayout(new FlowLayout());
c.add(new JLabel(“This is JLabel”);
f.setVisible(true);
}

JButton
• Implements simple push button.
• Can display text/icon or both.
• On user click, action events are sent to all registered Action listeners.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class ButtonDemo extends JFrame


{
private JButton bntExit;
public static void main(String args[])
{
(new ButtonDemo()).setVisible(true);
}

ButtonDemo()
{
super(“Button Demo”);
setSize(350,250);
Container c=getContentPane();
c.setLayout(new FlowLayout());
btnExit=new JButten(“Exit”);
c.add(btnExit);

ButtonListener listener = new ButtonListener();


btnExit.addActionListener(listener);
}
class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == bntExit)
System.out.println(“Hello”);
}
}
}

BE Computer 7th/BCA 5th (Advance Programming) 6


http://www.shiba.com.np/java/javaGUI.pdf
Prepared By: Shiba R. Tamrakar Copy() left

JCheckbox
• Implements a check box that can be selected or deselected.

import java.awt.*;
import javax.swing.*;
public class chkbxDemo{
public static void main(String[] args){
JFrame frame = new JFrame(“CheckBoxDemo”);
frame.setSize(300,200);
Container cont = frame.getContentPane();
cont.setLayout(new FlowLayout());
cont.add(new JCheckBox(“Apple”);
cont.add(new JCheckBox9(“Banana”);
cont.add(new Button(“Submit”);
frame.setVisible(true);
}
}
JRadioButton
• Implements a check box that can be selected or deselected.

import java.awt.*;
import javax.swing.*;
public class RadioDemo{
public static void main(String[] args) {
JFrame frame = new JFrame("Radio Demo");
frame.setSize(350,250);
Container cont = frame.getContentPane();
cont.setLayout(new FlowLayout());
ButtonGroup btnGroup = new ButtonGroup();

JRadioButton rbtnP = new JRadioButton("Programmer",true);


JRadioButton rbtnD = new JRadioButton("Designer");
btnGroup.add(rbtnP);
btnGroup.add(rbtnD);

cont.add(rbtnP);
cont.add(rbtnD);

frame.setVisible(true);
}
}
JScrollBar
• Lets the user enter an adjustable pseudo-analog value.
• Can be organized horizontally or vertically.
o JScrollBar.HORIZONTAL
o JScrollBar.VERTICAL

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ScrollBarDemo extends JFrame{


public static void main(String args[]){
(new ScrollBarDemo()).setVisible(true);

BE Computer 7th/BCA 5th (Advance Programming) 7


http://www.shiba.com.np/java/javaGUI.pdf
Prepared By: Shiba R. Tamrakar Copy() left

}
ScrollBarDemo(){
super("Scroll Bar Demo");
setSize(350,250);
Container cont = getContentPane();
JScrollBar sbar = new JScrollBar(JScrollBar.HORIZONTAL);
cont.add(sbar,BorderLayout.NORTH);

BarListener listener = new BarListener();


sbar.addAdjustmentListener(listener);
}
class BarListener implements AdjustmentListener{
public void adjustmentValueChanged(AdjustmentEvent e){
System.out.println("Val = " + e.getValue());
}
}
}
JTextField and JTextArea
• Single line and multi-line text entry.
• Both are inherited javax.swing.text.JTextComponent.
• Both sends Key events when they receive keyboard input.
• In addition Action events occurs while pressed Enter.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class TextDemo extends JFrame implements ActionListener, KeyListener{


private JTextField field;
private JTextArea area;
public static void main(String args[]){
(new TextDemo()).setVisible(true);
}

TextDemo(){
super("TextDemo");
setSize(350,250);
Container cont = getContentPane();

field = new JTextField("Type here");


field.addKeyListener(this);
field.addActionListener(this);
cont.add(field,BorderLayout.NORTH);

area=new JTextArea();
cont.add(area,BorderLayout.CENTER);
}
public void keyPressed(KeyEvent e){
System.out.println(e);
}

public void keyReleased(KeyEvent e){}

public void keyTyped(KeyEvent e){


area.append("Key: " + e.getKeyChar() + "'");
}
BE Computer 7th/BCA 5th (Advance Programming) 8
http://www.shiba.com.np/java/javaGUI.pdf
Prepared By: Shiba R. Tamrakar Copy() left

public void actionPerformed(ActionEvent e){


area.append("Action: " + field.getText() + "'");

}
}
JComboBox
ComboDemo()
{
super("ComboDemo");
setSize(350,250);
Container cont = getContentPane();
cont.setLayout(new FlowLayout());

String[] initialVals = {"BCA","BE Comp","BIT"};


JComboBox combo = new JComboBox(initialVals);
combo.setEditable(true);
cont.add(combo);
}
}

Layout Management

• A layout manager determines the location and size of components placed into a
container.
• Different layout manager classes use different algorithms for determining size and
location.
• The only layout manager methods that are normally used are constructors.
• In Java we normally do not manually manage layout, because there are two main
reasons
o It is very tedious to manually layout a large number of components.
o Sometimes the width and height information is not yet available when we
need to arrange some control, because it is pretty confusing to figure out when it is
okay to use the size of a given component to position it relative to another.
• A layout manager is an instance of any class that implements the
LayoutManager interface.
• If no call to setLayout( ) is made, then the default layout manager is used.
• Whenever a container is resized (or sized for the first time), the layout manager is
used to position each of the components within it.

The setLayout( ) method has the following general form:

Void setLayout(LayoutManager layoutObj)

o Here, layoutObj is a reference to the desired layout manager.


o If we wish to disable the layout manager and position components
manually, pass null for layoutObj.
o In this case, we have to determine the shape and size of each component
manually, using the setBounds( ).

• Each component that is being managed by a layout manager contains the


getPreferredSize( ) and getMinimumSize( ) methods.

BE Computer 7th/BCA 5th (Advance Programming) 9


http://www.shiba.com.np/java/javaGUI.pdf
Prepared By: Shiba R. Tamrakar Copy() left

• These return the preferred and minimum size required to display each component.

FlowLayout Class

• It places components in rows.


• Each component is given its preferred size. When a row has as many components
as can fit, a new row is started.
• This is the default layout manager for JPanel and Applet.
• Components are laid out from the upper-left corner, left to right and top to bottom.
• It uses the constructor to tune the behavior.

There are three useful constructors.

o new FlowLayout( )
o new FlowLayout(int algn)
o new FlowLayout(int algn, int hgap, int vgap)

• The first form creates the default layout, which centers components and leaves
five pixels of space between each component.
• The second form lets us specify how each line is aligned.

FlowLayout.LEFT
FlowLayout.RIGHT
FlowLayout.CENTER

• The third form allows us to specify the horizontal and vertical space left between
components in hgap and vgap

Fig: Initial State of Applet.

Fig: After resize (decrease the width and increase the height)

BE Computer 7th/BCA 5th (Advance Programming) 10


http://www.shiba.com.np/java/javaGUI.pdf
Prepared By: Shiba R. Tamrakar Copy() left

BorderLayout Class

• It divides its container into three horizontal stripes:


o top (north),
o middle, and
o bottom (south).
• At most one component can be placed into the north or south.
• These components get their preferred height, but they take up the full width of the
container.
• The middle stripe gets whatever height is available after deducting the heights of
the north and south components.
• It can hold three components:
o one on the left (west),
o one in the middle (center), and
o one on the right (east).
• The east and west components get their preferred widths, but they take up the full
height of the middle stripe.
• This is the default layout manager for content panes (JFrame,JDialog,Window).
• There are two useful constructors.

o new BorderLayout( )
o new BorderLayout(int hgap, int vgap)

• When components are added to a container that uses a BorderLayout, they should
be added with the following kind of statement.

container.add(component, whr);

• The parameter whr should be one of the following.


o BorderLayout.NORTH
o BorderLayout.EAST
o BorderLayout.SOUTH
o BorderLayout.WEST
o BorderLayout.CENTER

Fig: Initial State Fig: resizing horizontally Fig: resizing vertically

BE Computer 7th/BCA 5th (Advance Programming) 11


http://www.shiba.com.np/java/javaGUI.pdf
Prepared By: Shiba R. Tamrakar Copy() left

GridLayout Class

• It places components in a rectangular grid whose cells all have the same size.
Each component is sized to fill the cell.
• There are two useful GridLayout constructors.
o new GridLayout(int rows, int cols)
o new GridLayout(int rows, int cols, int hgap, int vgap)

Fig:Initial State Fig: after resizing (in diagnol increase height and width both)

(Example already discussed above)

BoxLayout Class

• It places components into a single row or column, as specified by the second


constructor parameter.
• For a row (parameter value BoxLayout.X_AXIS), each component get its preferred
height.
• The widths are adjusted according to a formula that incorporates both preferred
and maximum widths.
• For a column (parameter value BoxLayout.Y_AXIS), each component gets its
preferred width.
• The heights are adjusted according to a formula that incorporates both preferred
and maximum heights.
o new BoxLayout(Component c, BoxLayout.X_AXIS)
o new BoxLayout(Component c, BoxLayout.Y_AXIS)

BE Computer 7th/BCA 5th (Advance Programming) 12


http://www.shiba.com.np/java/javaGUI.pdf
Prepared By: Shiba R. Tamrakar Copy() left

Fig: XboxLayout Fig: yBoxlayout

CardLayout

• It is unique among the other layout managers in that it stores several different
layouts.
• Each layout can be thought of as being on a separate index card in a deck that can
be shuffled so that any card is on top at a given time.
• This can be useful for user interfaces with optional components that can be
dynamically enabled and disabled upon user input.
• We can prepare the other layouts and have them hidden, ready to be activated
when needed.
o CardLayout provides these two constructors:

CardLayout( )
CardLayout(int horz, int vert)

• The first form creates a default card layout.


• The second form allows us to specify the horizontal and vertical space left
between components in horz and vert, respectively.
• Use of a card layout requires a bit more work than the other layouts.
• The cards are typically held in an object of type Panel.
• This panel must have CardLayout selected as its layout manager.
• The cards that form the deck are also typically objects of type Pane.
• Thus we must create a panel that contains the deck and a panel for each chard in
the deck.
• Next, we add to the appropriate panel the components that form each card.
• We then add panel to the main applet panel.
• Once these steps are complete, we must provide some way for the user to select
between cards.
• Once these steps are complete, we must provide some button for each card in the
deck.
• When card panels are added to a panel, they are usually given a name.

GridBagLayout

• GridBagLayout is the most sophisticated, flexible layout manager the Java platform
provides.

BE Computer 7th/BCA 5th (Advance Programming) 13


http://www.shiba.com.np/java/javaGUI.pdf
Prepared By: Shiba R. Tamrakar Copy() left

• Grid bag layouts are the most complex and most flexible of the AWT layouts,
letting you specify more exactly than any of the other AWT layout managers where
you want your components to go.

Assignment:

Write programs to demonstrate GridBagLayout and CardLayout.

Hints:
Students should be familier with AWT, Swing, JFrame, JPanel, JTextField, JLabel,
JCheckBox, JRadioButton and JTextArea along with event handling.

In Layout Management students should practice on FlowLayout, GridLayout, BorderLayout


and combination

Extra Stuff (not in Syllabus)

JMenu
• Allow the programmer to organize Swing components in menus.
• JMenuBar component implements a menu bar that occupies the top portion of a
JFrame and can contain drop-down menus.
• JFrame calls setJMenuBar(theMenuBar) to insert menu.
• to populate a menu bar, construct a number of instances of JMenu and install them
in the menu bar by calling the theMenuBar.add(theMenu).
• The JMenu constructor takes as an argument the string that will appear on the
menu bar.
• Example
//MenuDemo.java
// Title : MenuDemo.java - Simple demo of building menus.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

public class MenuDemo {


public static void main(String[] args) {
JFrame win = new MenuDemoGUI();
win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
win.setVisible(true);
}
}
//MenuDemoGUI
class MenuDemoGUI extends JFrame {
JTextArea m_editArea = new JTextArea(20, 50);

// declare and create new menu


JMenu m_fileMenu = new JMenu("File");
// create new menu item
JMenuItem m_openItem = new JMenuItem("Open");
//another menu item
JMenuItem m_quitItem = new JMenuItem("Quit");
JMenu m_editMenu = new JMenu("Edit");
JMenuItem m_copyItem = new JMenuItem("Copy");
JMenuItem m_pasteItem= new JMenuItem("Paste");

BE Computer 7th/BCA 5th (Advance Programming) 14


http://www.shiba.com.np/java/javaGUI.pdf
Prepared By: Shiba R. Tamrakar Copy() left

//constructor
public MenuDemoGUI() {
//... Add listeners to menu items
m_openItem.addActionListener(new OpenAction());
m_quitItem.addActionListener(new QuitAction());

JMenuBar menubar = new JMenuBar(); // declare and create new menu bar
menubar.add(m_fileMenu);
m_fileMenu.add(m_openItem);
m_fileMenu.addSeparator(); // add separator line to menu
m_fileMenu.add(m_quitItem);
menubar.add(m_editMenu);
m_editMenu.add(m_copyItem);
m_editMenu.add(m_pasteItem);
//... Content pane: create, layout, add components
JPanel content = new JPanel();
content.setLayout(new BorderLayout());
content.add(m_editArea, BorderLayout.CENTER);

//... Set JFrame's menubar, content pane, and title.


this.setContentPane(content); // Set windows content pane..
this.setJMenuBar(menubar); // Set windows menubar.
this.pack();
this.setTitle("MenuDemo");
}//endconstructor

//// OpenAction
class OpenAction implements ActionListener {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "Sorry, can't open anything");
}
}

/// QuitAction
class QuitAction implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.exit(0); // terminate this program
}
}
}

Example of uing JTable


import java.awt.event.WindowAdapter;

BE Computer 7th/BCA 5th (Advance Programming) 15


http://www.shiba.com.np/java/javaGUI.pdf
Prepared By: Shiba R. Tamrakar Copy() left

import java.awt.event.WindowEvent;
import javax.swing.*;

public class jTableEx extends JFrame


{
String data[][]={{"Shiba","Bagbazar","BCA Honors"},{"Roshan","BE Elec and
e","Lazimpat"}};

String fields[]={"Name","Address","Education"};

public static void main( String[] args)


{
jTableEx myEx = new jTableEx("JTAble Example");
}

public jTableEx( String title )


{
super ( title );
setSize(150,150);
addWindowListener ( new WindowAdapter()
{ public void windowClosing( WindowEvent we ){
dispose();
System.exit( 0 );
}
});
init();
pack();
setVisible (true);

}
private void init()
{
JTable jt = new JTable (data,fields);
JScrollPane pane = new JScrollPane ( jt );
getContentPane().add( pane);
}
}

Example of JList
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class JListEx extends JFrame


{
private DefaultListModel nameList;
private JList list;

public JListEx()
{
nameList = new DefaultListModel();
nameList.addElement("Ramesh");
nameList.addElement("Santosh");
nameList.addElement("Prakash");

list = new JList ( nameList);

BE Computer 7th/BCA 5th (Advance Programming) 16


http://www.shiba.com.np/java/javaGUI.pdf
Prepared By: Shiba R. Tamrakar Copy() left

list.setSelectionMode( ListSelectionModel.SINGLE_SELECTION);

//create JButton ( "Add Name");


JButton addButton = new JButton ("Add Name");
addButton.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
//prompt user for name
String name = JOptionPane.showInputDialog(JListEx.this,"Enter Name");

//add new Name to model


nameList.addElement(name);
}
});

//create JButton for removing selected name


JButton removeButton = new JButton("Remove Selected Name");

removeButton.addActionListener(
new ActionListener(){
public void actionPerformed (ActionEvent event )
{
nameList.removeElement( list.getSelectedValue());
}
}
);

//lay out GUI Components


JPanel inputPanel = new JPanel();
inputPanel.add( addButton );
inputPanel.add( removeButton );

Container container = getContentPane();


container.add(list,BorderLayout.CENTER);
container.add( inputPanel,BorderLayout.NORTH);

setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(400,300);
setVisible(true);
} //end of JListEx constructor

public static void main(String args[])


{
new JListEx();
}
}

BE Computer 7th/BCA 5th (Advance Programming) 17


http://www.shiba.com.np/java/javaGUI.pdf
Prepared By: Shiba R. Tamrakar copy () left

Chapter 4 (Java IO)

(Note: This document is dedicated for BE Computer 7 th Sem. or BCA 5th Sem., so it is
assumed that the already have knowledge what is IO actually. Further discussion on the
example will be in class)

Introduction
While working with program we may have to deal with external IO operation like reading
files, writing files, socket programming etc. Java IO deals with all IO operations.

Data Sinks
 Resource for Data
 Types of Data Sinks
o File
 Read/write from file
o Memory
 Read/write from memory
o Pipe
 Read/write across threads
 Types of Data
o Character
 Input from Keyboard and output to screen
 As memory sinks and pipe sinks
o Raw data
 Network/sockets data or data read from other programming
language.
o Formatted Data
 Formatted object, images or video files
o Compressed Data
 Gzip, jar etc

Character Sink Classes


Type Classes
File FileReader
FileWriter
Memory CharArrayReader
CharArrayWriter
StringReader
StringWriter
Pipe PipedReader
PipeWriter

Data Sink Classes


Type Classes
File FileInputStream
FileOutputStream
Memory ByteArrayInputStream
ByteArrayOutputStream
Pipe PipedInputStream
PipeOutputStream

BE Computer 7th /BCA 5th (Advance Programming) 1


http://www.shiba.com.np/java/javaIO.pdf
Prepared By: Shiba R. Tamrakar copy () left

Introduction to Streams
- Java uses the concept of streams to represent the ordered sequence of data, a
common characteristic shared by all the input/output devices as started above.
- For example, if we are using terminal in one side, the other side should not always
be terminal, it may be file or socked output.
- Standard Input, File Stream, Standard Output, File System etc all are handled
through streams.
- Streams are used to access resources
- Different classes handle different types of data
- Streams are often stacked to process data
- Exception must be handled
- I/O classes were redesigned in Java 1.1 (older classes still exist
- It contains binary information
- The streams are basically divided into InputStream and OutputStream.
- Streams can also be classified as Data(Byte) Streams and Character Streams
- Again both data stream and character streams are divided into Input Stream and
Output Stream
- It don’t care underlying source/destination
- Data and Character Streams
o OutputStream
 Write program data out to stream.
o InputStream
 Read data from data sinks into a program.
o Writer
 Work with character data to write into stream
o Reader
 Work with character data to read from stream
o InputStreamReader
 Allow to read in data and character into program from stream.
o OutputStreamWriter.
 Allow to read in data and character into program from stream.
I/O Exception Class Hierarchy
- IOException
- FileNotFoundException
- InterruptedIOException
- ObjectStreamException

I/O Classes
- InputStrem (abstrace class/base class)
o void close()
o int read()
o int read(byte[] b)
o int read(byte[] b, int off, int len)
o void reset()
o long skip(long n)
- OutputStream (abstrace class/base class)
o void close()
o void flush()
o void write(int b)
o void write(byte[] b)
o void write(byte[] b, int off, int len)

BE Computer 7th /BCA 5th (Advance Programming) 2


http://www.shiba.com.np/java/javaIO.pdf
Prepared By: Shiba R. Tamrakar copy () left

File
 Most of the java.io operates on stream, but file class doesn’t.
 It deals directly with files and the file system.
 The File class does not specify how information is retrieved from or stored in files;
it describes the properties of a file itself.
 A File object is used to obtain or manipulate the information associated with a disk
file, such as the permissions, time, date, and directory path, and to navigate
subdirectory hierarchies.
 There are several restriction to use file in Applet
 A directory is treated as simply a file with one property added.
 Following constructors can be used to crate File objects:
File(String directoryPath)
File(String directoryPath,String Filename)
File(File dirObj,String filename)
File(URI uriObj)
 Here, directoryPath is the pathname
 filename is the name of the file
 dirObj is a File object that specifies a directory
 uriObj is a URI object that describes a file.
 Example
File f1=new File(“/”);
File f2=new File(“/”,”test.dat”);
File f3=new File(f1,”test.dat”);
 File defines many methods that obtain the standard properties of a file object.
 Methods related to File object
getName( ) getPath( ) getAbsolutePath( )
getParent( ) exists( ) canWrite( )
canRead( ) isDirectory( ) isFile( )
isAbsolute( ) lastModified( ) length( )
boolean renameTo( ) void deleteOnExit( ) isHidden( )
boolean delete( ) Boolean setLastModified(long millisec)
Boolean setReadOnly( )

Example
//fileproperties.java
import java.io.*;

public class fileproperties


{
static void property(String s)
{
System.out.println(s);
}
public static void main(String arg[])
{
File f=new File(".\\a\\L7Q1.java");
property("File Name: " +f.getName());
property("File Path: " +f.getPath());
property("Absulate path: " +f.getAbsolutePath());
property("Parent : " +f.getParent());
property("Existence: " +f.exists());
property("Is File: " +f.isFile());
property("Is Directory: " +f.isDirectory());
property("Read/Write: " +f.canWrite());
property("Read only: " +f.canRead());
BE Computer 7th /BCA 5th (Advance Programming) 3
http://www.shiba.com.np/java/javaIO.pdf
Prepared By: Shiba R. Tamrakar copy () left

property("Is absolute: " +f.isAbsolute());


property("Is Hidden: " +f.isHidden());
property("File Size: " +f.length() +" Bytes");
property("Is Modified on : " +f.lastModified());
}
}

Directories
 A directory is a File that contains a list of other files and directories.
 When we create a File object and it is a directory, the isDirectory( ) method will
return true.
 list( ) method is used to extract the list of other files and directories inside
 It has two forms
String [ ] list ( )
Example
//dir.java
import java.io.*;

public class dir


{

public static void main(String arg[])


{
File f=new File("..\\iolab.txt"); // iolab.txt is in parent directory
if (f.isDirectory())
{
System.out.println("The content of directory lab7 is : ");
String s[]=f.list();
for(int i=0;i<s.length;i++)
System.out.println(s[i]);
}
}
}

Byte Stream Classes through Reading from and Writing to a File


 Byte stream classes are used to provide functional future for creating and
manipulating streams and files for reading and writing bytes.
 Java provides both input and output byte stream classes.
 The FileInputStream class allows you to read from a file in the form of a stream.
 A stream is a path along which data flows.
 We can create an object of the class using a File class.
 The FileOutputStream class allows us to write the output to a file steam.
Example
//CopyFile.java
//Copy one file to another
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class CopyFile


{
public static void main(String[] args)
{
if(args.length !=2){
System.out.println("Usage: java CopyFile <infile> <outfile>");
BE Computer 7th /BCA 5th (Advance Programming) 4
http://www.shiba.com.np/java/javaIO.pdf
Prepared By: Shiba R. Tamrakar copy () left

return;
}
try{
int value;
FileInputStream in = new FileInputStream(args[0]);
FileOutputStream out = new FileOutputStream(args[1]);
while((value=in.read()) != -1)
out.write(value);
in.close();
}catch(IOException e)
{
System.out.println(e);
}
}
}

Character Stream classes through Reading from and Writing to a File


 The character stream classes supports Input and Output for Unicode characters.
 Character Stream classes namely reader and writer stream class provide read and
write 16 bit Unicode characters.
 FileReader class is used to read characters from files.
 The FileWriter class provides writing characters to a file.
 These classes are very similar to the Byte stream Input and Output classes; the
only difference is fundamental unit of information (Byte/Character).
Example
//Enter your name in console and get welcome message
import java.io.*;

public class BasicIO


{
public static void main(String[] args)
{
try
{
InputStreamReader isr = new InputStreamReader( System.in );
BufferedReader stdInput = new BufferedReader (isr);

System.out.print("Print enter your Name:");


String inputData = stdInput.readLine();
System.out.println("Welcome " + inputData);
}catch(IOException ioe)
{
System.out.println("An I/O Error has occoured");
}
}
}
Example 2
//findCube.java
//Find the square of a number inputted by the user.
public class findCube
{
public static void main(String args[]) throws IOException
{
String str;
BE Computer 7th /BCA 5th (Advance Programming) 5
http://www.shiba.com.np/java/javaIO.pdf
Prepared By: Shiba R. Tamrakar copy () left

int num;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the Number :");
str=br.readLine();
System.out.print("\n");
num=Integer.parseInt(str);
age=age*age;
System.out.println("Square of the Number is: "+num);
}
}

Random Access File


 The RandomAccessFile enables us to read and write bytes, text and java data types
to any location in a file.
 Java.io.RandomAccessFile class provides the ability to read and write data from
or write any specified location in a file.

 This class implements DataInput and DataOutput interfaces.
 The random access means that data can be read from or written to random
location within a file.
 This class also provides permissions like read and write, and allows files to be
accessed in read only and read write mode.
 There are two ways to create a random access file.
o Using an object of the file class
o Using the path name as a String.
RandomAccessFile(File name,String Mode)
RandomAccessFile(String pathname,String Mode)
 We can use one of the following two mode Strings
o “r” for reading only
o “rw” of read and write.
 The following program creates a random access file and opens it in the form of “rw”
mode.
 We can read and write the primitive data types through readXXX( ) and WriteXXX(
) methods.
 The RandomAccessFile Class has several methods that allow random access to the
content within file.
 The void seek(long position), it sets the file pointer to a particular location
inside the file.
 The length( ) method returns the length of the file in terms of bytes.
 Long getFilePointer( ) returns the current byte location of the file pointer
 int skipBytes(n) jumps the pointer by n bytes from its current location.

Example
//randomfile.java
import java.io.*;
class randomfile
{
public static void main(String args[ ]) throws IOException
{
try
{
RandomAccessFile r1=new RandomAccessFile("in.dat","rw");
r1.writeShort(10);
r1.writeInt(20000);
BE Computer 7th /BCA 5th (Advance Programming) 6
http://www.shiba.com.np/java/javaIO.pdf
Prepared By: Shiba R. Tamrakar copy () left

r1.writeDouble(342.234);
r1.writeChar('a');
r1.writeBoolean(true);
r1.writeLong(545234325);
r1.writeFloat((float)42342.343);
r1.seek(0);
System.out.println(r1.readShort());
System.out.println(r1.readInt());
System.out.println(r1.readDouble());
System.out.println(r1.readChar());
System.out.println(r1.readBoolean());
System.out.println(r1.readLong());
System.out.println(r1.readFloat());
r1.close();
}
catch(FileNotFoundException e)
{
System.out.println(e.getMessage());
}
}
}

Sequence Input Stream


 The SequenceInputStream class allows you to concatenate multiple InputStreams.
 The SequenceInputStream use the following constructor:
o SequenceInputStream(InputStream is1,InputStream is2)
 It read requests from the is1 until it runs out and then switches over the is2.
 (try it your self)

Serialization
 Serialization is the process of writing the state of an object to a byte stream.
 This is useful when we want to save the state of out program to a persistent storage area, such
as a file.
 At a later time, we may restore these objects by using the process of deserialization.

import java.io.*;

public class SerializationEx


{
public static void main(String arg[])
{
try
{
X obj1=new X("hi",-7,2.0);
X obj2;
System.out.println("obj1"+obj1);
FileOutputStream fos=new FileOutputStream("serial");
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos.writeObject(obj1);
oos.flush();
oos.close();
FileInputStream fis=new FileInputStream("serial");
ObjectInputStream ois=new ObjectInputStream(fis);
obj2=(X)ois.readObject();
ois.close();
BE Computer 7th /BCA 5th (Advance Programming) 7
http://www.shiba.com.np/java/javaIO.pdf
Prepared By: Shiba R. Tamrakar copy () left

System.out.println("obj2"+obj2);
}
catch(Exception e)
{
System.out.println("the error is : "+e);
}
}
}

class X implements Serializable


{
String s;
int i;
double d;

public X(String s,int i,double d)


{
this.s=s;
this.i=i;
this.d=d;
}
public String toString()
{
return "s="+s+";i="+i+";d="+d;
}
}

BE Computer 7th /BCA 5th (Advance Programming) 8


http://www.shiba.com.np/java/javaIO.pdf
Prepared By: Shiba R. Tamrakar

Java Database Connectivity (JDBC)

Introduction
 JDBC (Java Database Connectivity) is defined, as a set of java classes and methods to interface with
database.
 It also provides uniform access to a wide range of relational databases.
 The java 2 software bundle includes JDBC and the JDBC-ODBC Bridge.
 JDBC provides a standard API for tool/database developers and makes it possible to write database
applications using a pure Java API.

What does JDBC do?


Simply put, JDBC makes it possible to do three things:

establish a connection with a database


send SQL statements
Process the results.

JDBC Is a Low-level API and a Base for Higher-level APIs


JDBC is a "low-level" interface, which means that it is used to invoke (or "call") SQL commands
directly.
It works very well in this capacity and is easier to use than other database connectivity APIs, but it
was designed also to be a base upon which to build higher-level interfaces and tools.
A higher-level interface is "user-friendly," using a more understandable or more convenient API that is
translated behind the scenes into a low-level interface such as JDBC. At the time of this writing, two
kinds of higher-level APIs are under development on top of JDBC:

1. An embedded SQL for Java (Example SQLJ). At least one vendor plans to build this. DBMSs
implement SQL, a language designed specifically for use with databases. JDBC requires that the
SQL statements be passed as Strings to Java methods. An embedded SQL preprocessor allows
a programmer to instead mix SQL statements directly with Java: for example, a Java variable can
be used in a SQL statement to receive or provide SQL values. The embedded SQL preprocessor
then translates this Java/SQL mix into Java with JDBC calls.
2. A direct mapping of relational database tables to Java classes. JavaSoft and others have
announced plans to implement this. In this "object/relational" mapping, each row of the table
becomes an instance of that class, and each column value corresponds to an attribute of that
instance. Programmers can then operate directly on Java objects

ODBC API
Microsoft ODBC (Open Database connectivity) Application programming interface is probably the
most widely used programming interface for accessing RDBMS.
ODBC is written entirely in C, JDBC is written in Java.
But, both JDBC and ODBC are based on the X/Open SQL Command level Interface.
It is an interface to perform SQL calls to database.
The SQL statements are embedded in the statements.

Application Oracle
ODBC
Database

Oracle SQL
Driver Driver SQL
Database
JDBC API
JDBC provides a database programming API for Java programs.
Java programs cannot directly communicate with the
Fig. ODBC Database ODBC driver.
Design
Sun Microsystems provides a JDBC-ODBC bridge that translates JDBC to ODBC.
There are several type of JDBC drivers available they are:

1
Prepared By: Shiba R. Tamrakar

o JDBC-ODBC bridge+ODBC driver


o Native API party java Driver
o JDBC-Net Pure java Driver
o Native protocol pure java Driver.

Java Application JDBC JDBC-ODBC Oracle Driver Oracle Database


Other Driver
(0r) Driver Bridge Other Database
Client
Java machine
Applet Manager
Server Machine (Business Logic)
Driver Database Server

Fig. JDBC Application


JDBC-ODBC Bridge+ODBC driver (Type Architecture
1 Drivers)
These drivers are the bridge drivers such as the JDBC-ODBC Bridge.
These drivers rely on an intermediary such as ODBC to transfer the SQL calls to the database.
Bridge drivers often rely on native code, although the JDBC-ODBC library native code is part of the
Java 2 virtual machine.

Application
JDBC-Driver
Manager
ODBC Driver ODBC
Database
Manager
ODBC libraries

Fig. JDBC-ODBC Bridge Driver

Native API partly java Driver (Type 2 Drivers) (not in course)


A native API is partly a java driver uses native C language library calls to translate JDBC to native
client Library.
These drivers are available for Oracle, Sybase, DB2 and other client library based RDBMS.
Although these drivers are faster than Type 1 drivers, these drivers use native code and require
additional permissions to work in an Applet.
This driver might need client side database code to connect over the network.

Application
JDBC
DBMS Vendor Client
Socket
Side Libraries base DBMS
Connection
on C language Server

Fig. Native API partly Driver

JDBC-Net Pure Java Driver (Type 3 Drivers) (not in course


This Driver consists of JDBC and DBMS independent protocol driver.
Here the calls are translate and sent to middle tier server through the socket.
The middle tier contacts the databases.
It is simple and most flexible.
It calls the database API on the server.
JDBC requests from the client are first proxied to the JDBC Driver on the server to run.
It and Type 4 drivers can be used by thin (java based) clients as they need no native code.

2
Prepared By: Shiba R. Tamrakar

Native protocol pure java Driver (Type 4 Drivers) (not in course)


It contains JDBC calls that are converted directly to the network protocol used by the DBMS server.
The highest level of driver re-implements the database network API in the Java language.
It can also be used on thin clients as they also have native code.
The network protocol is defined by the vendor and is typically proprietary; the driver usually comes
only from the database vendor.

Application
JDBC Socket
Java Based Socket
Connection
Driver
DBMS
(DBMS specific
Server
prolocol)
Fig. Native protocol all java driver
The Statement Object Driver
The statement object is created by calling the createStatement( ) method of the connection object.
The statement object is used to execute simple Queries.
It has three methods that can be used for the purpose of querying.
o executeQuery( )
This is used to execute simple select quer6y and return a single ResultSet object.
o executeUpdate( )
This is used to execute SQL Insert, Update and Delete statements
o execute( )
It is used to execute SQL statements that may return multiple values.
In the example programmes we find import the java.sql package.
The JDBC-ODBC bridge is a bridge driver that is loaded by Class.forName( ) method.
The connection object is initialized by getConnection( ) method.
Then, statement is created. Next we execute a simple select query using the executeQuery ( )
method of the statement object (st).

Working with ResultSet


When a database query is executed, the results of the query are returned as a table of data organized
according to rows and columns.
The ResultSet interface is to provide access to table data.
Initially the pointer is positioned before the first row.
So we use the next ( ) method to move the cursor to the first row.
You can access the data from the ResultSet rows by calling the getXXX methods.
The XXX is the data type of the parameter such as String, Int and so on.
The column is a ResultSet are accessed beginning with index 1, not 0.
If you specify 0 as the index, you will get runtime error message such as Invalid descriptor Index.
The next program illustrate the executeUpdate( ) method and execute insert, select, update and
delete SQL statements.

Obtaining a Connection
The java.sql.Driver class acts as a pass-through driver by forwarding JDBC requests to the real
database JDBC Driver.
The JDBC driver class is loaded with a call to Class.forName(drivername).
These next lines of code show how to load two different JDBC driver classes:
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
Class.forName(“sun.jdbc.odbc.OracleDriver”);
Each JDBC driver is configured to understand a specific URL so multiple JDBC drivers can be loaded
at one time.
When you specify a URL at connect time, the first machine JDBC driver is selected.
The standard way to establish a connection with a database is to call the method
DriveManager.getConnection(URL), the argument URL is a string that provides a way of identifying
database.

3
Prepared By: Shiba R. Tamrakar

It has three parts:


Syntax:
<protocol>:<subprotocol>:<subname>
Protocol
This is always jdbc in the URL.
Subprotocol
This is used for specifying the type of driver or the database connectivity mechanism.
If the mechanism of retrieving the data is JDBC-ODBC Bridge, the subprotocol must be odbc. This is
reserved for URLs that specify ODBC style data source names.
Subname
This is used to identify the database.
This is to give enough information to locate the database.
Ex. jdbc:odbc:mydsn
In this example the odbc is the subprotocol and mydns is the local odbc data source name.
Ex. jdbc:oracle:sales
In this example the oracle is the database driver and sales is the local database.

The Connection Object


It represent a connection with the database.
You may have several connection object in an application that connects one or more database.
A database connection can be established with a call to the DriverManager.getConnection method.
The call takes a URL that identifies the database and optionally, the database login user name and
password.
Connection con=DriverManager.getConnection(url);
Connection con=DriverManager.getConnection(url,”Username”,”Password”);
After a connection is established, a statement can be run against the database.
The results of the statement can be retrieved and the connection closed.
Example
Connection con=DriverManager.getConnection(“jdbc:odbc:mydsn”);
Connection con=DriverManager.getConnection(“jdbc:oracle”,”scott”,”tiger”);

DriverManager
The DriverManager class is the management layer of JDBC, working between the user and the
drivers.
It keeps track of the drivers that are available and handles establishing a connection between a
database and the appropriate driver.
In addition, the DriverManager class attends to things like driver login time limits and the printing of
log and tracing messages.
For simple applications, the only method in this class that a general programmer needs to use directly
is DriverManager.getConnection.
As its name implies, this method establishes a connection to a database.
JDBC allows the user to call the DriverManager methods getDriver, getDrivers, and registerDriver as
well as the Driver method connect, but in most cases it is better to let the DriverManager class
manage the details of establishing a connection.

PreparedStatement
The PreparedStatement interface inherits from Statement and differs from it in two ways:

1. Instances of PreparedStatement contain an SQL statement that has already been compiled. This
is what makes a statement "prepared."
2. The SQL statement contained in a PreparedStatement object may have one or more IN
parameters. An IN parameter is a parameter whose value is not specified when the SQL
statement is created. Instead the statement has a question mark ("?") as a placeholder for each
IN parameter. A value for each question mark must be supplied by the appropriate setXXX
method before the statement is executed.

Because PreparedStatement objects are precompiled, their execution can be faster than that of
Statement objects. Consequently, an SQL statement that is executed many times is often created as
a PreparedStatement object to increase efficiency.
4
Prepared By: Shiba R. Tamrakar

Being a subclass of Statement, PreparedStatement inherits all the functionality of Statement.


In addition, it adds a whole set of methods which are needed for setting the values to be sent to the
database in place of the placeholders for IN parameters.
Also, the three methods execute, executeQuery, and executeUpdate are modified so that they take
no argument.
The Statement forms of these methods (the forms that take an SQL statement parameter) should
never be used with a PreparedStatement object.

Callable Statement
A CallableStatement object provides a way to call stored procedures in a standard way for all
DBMSs.
A stored procedure is stored in a database; the call to the stored procedure is what a
CallableStatement object contains.
This call is written in an escape syntax that may take one of two forms: one form with a result
parameter, and the other without one.
(See Section 4, "Statement," for information on escape syntax.) A result parameter, a kind of OUT
parameter, is the return value for the stored procedure.
Both forms may have a variable number of parameters used for input (IN parameters), output (OUT
parameters), or both (INOUT parameters).
A question mark serves as a placeholder for a parameter.

Example to find the data type of the field in database


String query = "select * from Table1";
ResultSet rs = stmt.executeQuery(query);
ResultSetMetaData rsmd = rs.getMetaData( );
int columnCount = rsmd.getColumnCount( );
for (int i = 1; i <= columnCount; i++) {
String s = rsmd.getColumnTypeName(i);
System.out.println ("Column " + i + " is type " + s);
}

JDBC-ODBC Driver Bridge Driver


If possible, use a Pure Java JDBC driver instead of the Bridge and an ODBC driver.
This completely eliminates the client configuration required by ODBC.
It also eliminates the potential that the Java VM could be corrupted by an error in the native code
brought in by the Bridge (that is, the Bridge native library, the ODBC driver manager library, the
ODBC driver library, and the database client library).

What Is the JDBC-ODBC Bridge?


The JDBC-ODBC Bridge is a JDBC driver which implements JDBC operations by translating them
into ODBC operations.
To ODBC it appears as a normal application program.
The Bridge implements JDBC for any database for which an ODBC driver is available.
The Bridge is implemented as the sun.jdbc.odbc Java package and contains a native library used
to access ODBC.
The Bridge is a joint development of Intersolv and JavaSoft.
The Bridge is implemented in Java and uses Java native methods to call ODBC.

The ResultSetMetaData Interface


Consider the following situation suppose you don’t know about the column name of the table, Number
of columns and their data type.
You cannot access the data through the getXXX ( ) method.
Overcome this problem by ResultSetMetaData interface.
It provides constants and methods that are used to obtain the information about ResultSet object.
getColumnCount ( ) : It returns number of columns in the table of data accessed by a result set.
getColumnName ( ): It returns the name of each column in the database from which the data is
retrieved.

5
Prepared By: Shiba R. Tamrakar

Sample Java Program


/* Before continuing to this program following requirement is needed

There should be a database with thable emp

Which contains fields id (int) and empName (varchar)

Then you should create System DSN ing ODBC pointing to above database. For simplicity you can
create an Access database and create DSN with name mydsn.

*/

import java.sql.*;

public class jdbcDemo

public static void main(String args[ ])

ResultSet r;

try

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Connection c=DriverManager.getConnection("jdbc:odbc:mydsn");

//our data source name is std_dns

Statement st=c.createStatement( );

r=st.executeQuery("select * from emp");

System.out.println("ID\tName");

System.out.println("*******************");

while(r.next( ))

System.out.println(r.getString(1)+"\t"+r.getString(2));

}catch(SQLException e)

System.out.println("SQL Error:"+e);

catch(Exception e)

6
Prepared By: Shiba R. Tamrakar

System.out.println("Error:"+e);

Sample Java Program


import java.io.*;

import java.sql.*;

public class jdbc_opr

static Connection c;

public static void main(String args[ ]) throws Exception

int ch;

/* For Mysql

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

c = DriverManager.getConnection("jdbc:mysql://localhost/cba?user=shiba&password=pword");

*/

/* For Oracle Uncomment it

DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver( ));

c=DriverManager.getConnection("jdbc:oracle:oci8:@cba","scott","tiger");

*/

//Delete the line below for Oracle and MySql

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

InputStreamReader i=new InputStreamReader(System.in);

BufferedReader b=new BufferedReader(i);

try

//Delete the line below for Oracle and Mysql

c=DriverManager.getConnection("jdbc:odbc:mydsn");
7
Prepared By: Shiba R. Tamrakar

do

System.out.println("\t\t\tMenu");

System.out.println("\t\t\t1. View");

System.out.println("\t\t\t2. Clear");

System.out.println("\t\t\t3. Insert");

System.out.println("\t\t\t4. Modify");

System.out.println("\t\t\t5. Delete");

System.out.println("\t\t\t6.exit");

System.out.println("\t\t\tEnter Your Choice:");

ch=Integer.parseInt(b.readLine( ));

switch (ch)

case 1:

display( ); break;

case 2:

System.out.clrscr( );break;

case 3:

insert( );

display( ); break;

case 4:

modify( );

8
Prepared By: Shiba R. Tamrakar

display( ); break;

case 5:

delete( );display( );break;

case 6:

System.out.println("Thank you");

System.exit(0);

default:

System.out.println("Invalid Choice");

}while(ch!=6);

catch(Exception e){ }

static void display( )

try

ResultSet r;

int row=0;

Statement st=c.createStatement( );

r=st.executeQuery("select * from emp");

System.out.println("Id\tName");

System.out.println("*********************");

9
Prepared By: Shiba R. Tamrakar

while (r.next( ))

System.out.println(r.getInt(1)+"\t"+r.getString(2));

r.close( );

catch(Exception e){ }

static void clrscr( )

for(int k=1;k<25;k++)

System.out.println( );

static void insert ( )

try

int row;

Statement ins_st;

ins_st=c.createStatement( );

System.out.println("4032,shiba");

row=ins_st.executeUpdate("insert into emp values('4032','shiba')");

c.commit( );

System.out.println("No of Rows inserted="+row);

catch(SQLException e)

System.out.println("Error in insert"+e);

static void modify( )

10
Prepared By: Shiba R. Tamrakar

try

int row;

Statement modi_st;

modi_st=c.createStatement( );

row=modi_st.executeUpdate("update emp set name='cba' where name='shiba'");

c.commit( );

System.out.println("No of Rows updated="+row);

}catch(SQLException e)

static void delete( )

try

System.out.println("4032,cba");

int row;

Statement del_st;

del_st=c.createStatement( );

row=del_st.executeUpdate("delete from emp where id=4032");

if (row>0)

c.commit( );

else

System.out.println("Record not found");

11
Prepared By: Shiba R. Tamrakar

catch(SQLException e)

System.out.println("Error in delete" +e);

/*

Note: System.out.clrscr( ) is removed in new version of jdk.

*/

Reference: Java Documentation from sum.com

Java Tutorial from sun.com

Oracle Handout (SSI book) and Complete Reference of Oracle 9i, Oracle Press

Internet and Java programming by R. Krishnamoorthy and S. Prabhu

Extra Stuff

"Why do you need JDBC but not ODBC?" There are several answers to this question:

1. ODBC is not appropriate for direct use from Java because it uses a C interface. Calls from Java to
native C code have a number of drawbacks in the security, implementation, robustness, and
automatic portability of applications.
2. A literal translation of the ODBC C API into a Java API would not be desirable. For example, Java has
no pointers, and ODBC makes copious use of them, including the notoriously error-prone generic
pointer "void *". You can think of JDBC as ODBC translated into an object-oriented interface that is
natural for Java programmers.
3. ODBC is hard to learn. It mixes simple and advanced features together, and it has complex options
even for simple queries. JDBC, on the other hand, was designed to keep simple things simple while
allowing more advanced capabilities where required.
4. A Java API like JDBC is needed in order to enable a "pure Java" solution. When ODBC is used, the
ODBC driver manager and drivers must be manually installed on every client machine. When the
JDBC driver is written completely in Java, however, JDBC code is automatically installable, portable,
and secure on all Java platforms from network computers to mainframes.

Why Java is recommended to use Oracle and not to use Ms-Access as


backend database?

Oracle Ms-Access
Java has its own Oracle JDBC Driver Java doesn’t have special Ms-Access JDBC Driver
and use JDBC-ODBC bridge driver.
Oracle JDBC driver is included in the Server Since it uses JDBC-ODBC bridge driver it don’t have
Application its driver on Server Application and ODBC should be
configured in each client.
Oracle Provides concurrently use of Database Ms-Access doesn’t provide concurrent access to the
database.
12
Prepared By: Shiba R. Tamrakar

Since it has its own JDBC driver the performance is Since JDBC-ODBC bridge driver, its performance is
high and database access if fast. low as ODBC configuration has to be configured
support JDBC. So, database access is also slow.
Java is most widely used for Distributed or Network Ms-Access is not a Server base Database so it is not
base Application like web, Network Applications so, preferred for Distributed database.
Oracle Database is preferred as it is a Server based
Database. So we don’t have to install Oracle in every
client.
Oracle database also have embedded SQL for Java Ms-Access Don’t has embedded SQL for Java
called SQLJ
Oracle corporate also have developed Java for Microsoft has not developed the Java for Ms-Access
Oracle and compilers for them
It uses Pure Native Jave JDBC driver It doesn’t have.

Statement Versus PreparedStatement


Statement PreparedStatement
1. It is a super class of PreparedStatement class. 1. It is a subclass of Statement class.
2. Instances of Statement contain an SQL statement 2. Instances of PreparedStatement contain an SQL
that has not been compiled. statement that has already been compiled. This is
what makes a statement "prepared."
3. We can not use IN parameter in SQL Statement. 3. We can use IN parameter in SQL Statement.
4. It consists of less method and properties. 4. As it is the subclass of Statement, it consists of all
most all the methods and properties of the Statement
class and it has its additional properties and
methods.
5. It is slower to execute than PreparedStatement 5. It is relatively faster
6. It has to do verify its metadata against the 6. It has to verify its metadata only once
database many times.
7. Under typical use of SQL statement objects 7. Under typical use of SQL statement objects
performance is better than PreparedStatement performance is worse than Statement when there is
where there are small number of SQL statements small number of SQL statements
8. It is not design to work with large objects like 8. It is design to work with large objects like BLOBs
BLOBs and CLOBs and CLOBs

13
Why Netowk?
­ communication
­ Access to a large amount of dynamic data
­ dynamic data
­ ability to distribute data

uses
­ to communicate with other programming running in outer OS (or System) which may be 
written in other language beside java.

Overview of Networing
­ TCP
Transmission Control Protocol
Reliable communication (error Control)
­UDP
User Datagram Protocol
Faster, unreliable communications (no error Control)

­ Information is transferred in packets
 ports are virtual network connections (0 to 65535)
<1024 reserved.

­ Reserved port numbers and services

ftp 20,21
Telnet 23
SMTP 25
HTTP 80
POP3 110
IMAP 143
SNMP 161

Making a Connection
­ Sender must know:
o Address of remote machine
o Port number
o Type and structure of data to be transferred
­ Remote machine can determine:
o Senders address and port

Networking Classes
­ java.net.*; package
TCP Classes UDP Classes
URL DatagramPacket
URLConnection DatabramSocket
Socket MulticastSocket
ServerSocket
InetAddress

InetAddress Class
­ Abstract class
­ Obtaining an InetAddress Object:
o InetAddress getLocalHost()
o InetAddress getByName(String n)
o InetAddress[ ] getAllByName(String n)

URL Class
­ Common Constructors:
o URL(String spec)
o URL(String protocol, String host, int port, String file)
o URL(String protocol, String host, String file)
­ Common Methods:
o Object getContent()
o String getFile()
o String getHost()
o Int getPort()
o String getProtocol()
o URLConnection openConnection()
o InputString openStream()
o String toString()

Example
import java.net.URL;
import java.io.*;

public class ReadURL
{
    public static void main(String[] args)
    {
        String str;
        
        try{
            URL url = new URL("http://www.google.com/");
            InputStream is = url.openStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            while((str = br.readLine()) != null)
                System.out.println(str);
            br.close();
        } catch(IOException e){
            System.out.println(e);
        }
    }
}

Example 2
import java.net.*;
import java.io.*;

public class ReadURL2
{
    public static void main(String[] args)
    {
        String str;
        
        try{
            URL url = new URL("http://www.google.com/"); 
            URLConnection uc = url.openConnection();
            InputStream is = uc.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            while((str = br.readLine()) != null)
                System.out.println(str);
            br.close();
        } catch(IOException e){
            System.out.println(e);
        }
    }
}
Example 3
import java.net.*;
import java.io.*;
import java.util.Properties;

public class ReadURL3
{
    public static void main(String[] args)
    {
        String str;
        Properties props = System.getProperties();
        props.setProperty("proxySet","true");
        props.setProperty("ProxyPort","3128");
        props.setProperty("proxyHost","proxy1.wlink.com.np");
        
        
        try{
            URL url = new URL("http://www.google.com/"); 
            URLConnection uc = url.openConnection();
            InputStream is = uc.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            while((str = br.readLine()) != null)
                System.out.println(str);
            br.close();
        } catch(IOException e){
            System.out.println(e);
        }
    }
}

Overview of Sockets
­ Uses TCP/IP
­ Sockets support bi­directional communication with ports
­ Connection stays open
­ The ServerSocket class waits for a connection
­ The Socket class sends and receives packages

Client Server

Socket

Socket
OutputStream ServerSocket
InputStream
InputStream

OutputStream

Creating a Server
­ Create ServerSocket object to listen for connections
­ Accept a connection
­ Open InputStream
­ Open OutputStream
­ Send and receive information
­ Close streams and connections 
Client Side application
­ Create Socket object
­ Open InputStream
­ Open OutputStream
­ Send and receive information
­ Close streams and connection.
Prepared By: Shiba R. Tamrakar

Distributed Programming with RMI

Overview

Distributed object computing extends an object-oriented programming system by allowing objects to be


distributed across a heterogeneous network, so that each of these distributed object components interoperate as
a unified whole.
 These objects may be distributed on different computers throughout a network, living within their own
address space outside of an application, and yet appear as though they were local to an application.
 Three of the most popular distributed object paradigms are :
o Microsoft's Distributed Component Object Model (DCOM)
o OMG's Common Object Request Broker Architecture (CORBA)
o JavaSoft's Java/Remote Method Invocation (Java/RMI).
o Enterprise Java Beans (JEB)

CORBA

 CORBA relies on a protocol called the Internet Inter-ORB Protocol (IIOP) for remoting objects.
 Everything in the CORBA architecture depends on an Object Request Broker (ORB).
 The ORB acts as a central Object Bus over which each CORBA object interacts transparently with other
CORBA objects located either locally or remotely.
 Each CORBA server object has an interface and exposes a set of methods.
 To request a service, a CORBA client acquires an object reference to a CORBA server object.
 The client can now make method calls on the object reference as if the CORBA server object resided in
the client's address space.
 The ORB is responsible for finding a CORBA object's implementation, preparing it to receive requests,
communicate requests to it and carry the reply back to the client.
 A CORBA object interacts with the ORB either through the ORB interface or through an Object Adapter
- either a Basic Object Adapter (BOA) or a Portable Object Adapter (POA).
 Since CORBA is just a specification, it can be used on diverse operating system platforms from
mainframes to UNIX boxes to Windows machines to handheld devices as long as there is an ORB
implementation for that platform.
 Major ORB vendors like Inprise have CORBA ORB implementations through their VisiBroker product
for Windows, UNIX and mainframe platforms and Iona through their Orbix product.

DCOM

 DCOM which is often called 'COM on the wire', supports remoting objects by running on a protocol
called the Object Remote Procedure Call (ORPC).
 This ORPC layer is built on top of DCE's RPC and interacts with COM's run-time services.
 A DCOM server is a body of code that is capable of serving up objects of a particular type at runtime.
 Each DCOM server object can support multiple interfaces each representing a different behavior of
the object.
 A DCOM client calls into the exposed methods of a DCOM server by acquiring a pointer to one of the
server object's interfaces.
 The client object then starts calling the server object's exposed methods through the acquired interface

BE Comp. VII, BCA V, Kantipur City Collage 1


Prepared By: Shiba R. Tamrakar

pointer as if the server object resided in the client's address space. As specified by COM, a server
object's memory layout conforms to the C++ vtable layout.
 Since the COM specification is at the binary level it allows DCOM server components to be written in
diverse programming languages like C++, Java, Object Pascal (Delphi), Visual Basic and even COBOL.
 As long as a platform supports COM services, DCOM can be used on that platform.
 DCOM is now heavily used on the Windows platform. Companies like Software AG provide COM
service implementations through their EntireX product for UNIX, Linux and mainframe platforms;
Digital for the Open VMS platform and Microsoft for Windows and Solaris platforms.
 Enterprise JavaBeans (EJB) implements server-side, arbitrarily scalable, transactional, multi-user,
secure enterprise-level applications.
 It is Java's component model for enterprise applications.

Enterprise Java Beans (EJB)

 EJB combines distributed object technologies such as CORBA and Java RMI with server-side
components to simplify the task of application development.
 EJBs can be built on top of existing transaction processing systems including traditional transaction
processing monitors, Web servers, database servers, and application servers.
 Sun claims that EJB is not just platform independent--it is also implementation independent.
 An EJB component can run in any application server that implements the EJB specification.
 User applications and beans are isolated from the details of the component services.
 The ability to reuse the same enterprise bean in different specific applications is one advantage of this
separation.
 The bean implementation or the client application need not have the parameters that control a bean's
transactional nature, persistence, resource pooling, or security management.
 These parameters can be specified in separate deployment descriptors.
 So, when a bean is deployed in a distributed application, the properties of the deployment environment
can be accounted for and reflected in the setting of the bean's options.
 EJB is a distributed component model. A distributed component model defines how components are
written.
 Hence different people can build systems from components with little or no customization.
 EJB defines a standard way of writing distributed components.
 The EJB client only gets a reference to an EJBObject instance and never really gets a reference to the
actual EJB Bean instance itself.
 The EJBObject class is the client's view of the enterprise Bean and implements the remote interface.
 EJB is a rather specialized architecture--aimed at transaction processing and database access.
 It is not really an environment for general distributed computing in our sense.

RMI (Remote Method Invocation)

 Java/RMI relies on a protocol called the Java Remote Method Protocol (JRMP).
 Java relies heavily on Java Object Serialization, which allows objects to be marshaled (or transmitted) as
a stream.
 Since Java Object Serialization is specific to Java, both the Java/RMI server object and the client object
have to be written in Java.
 Each Java/RMI Server object defines an interface which can be used to access the server object outside
of the current Java Virtual Machine (JVM) and on another machine's JVM.
 The interface exposes a set of methods which are indicative of the services offered by the server object.
 For a client to locate a server object for the first time, RMI depends on a naming mechanism called an

BE Comp. VII, BCA V, Kantipur City Collage 2


Prepared By: Shiba R. Tamrakar

RMIRegistry that runs on the Server machine and holds information about available Server Objects.
 A Java/RMI client acquires an object reference to a Java/RMI server object by doing a lookup for a
Server Object reference and invokes methods on the Server Object as if the Java/RMI server object
resided in the client's address space.
 Java/RMI server objects are named using URLs and for a client to acquire a server object reference, it
should specify the URL of the server object as you would with the URL to a HTML page.
 Since Java/RMI relies on Java, it can be used on diverse operating system platforms from mainframes to
UNIX boxes to Windows machines to handheld devices as long as there is a Java Virtual Machine (JVM)
implementation for that platform.
 In addition to Javasoft and Microsoft, a lot of other companies have announced Java Virtual
Machine ports.
 RMI allows us to execute methods on remote server. It helps us locate and execute methods of remote
objects.
 It’s like placing a class on Machine A and calling methods of that class from Machine B as through they
were from the same machine.
 It is the easiest solution for distributed programming.
 RMI is a pure Java solution unlike CORBA where we can have objects from different programming
languages interacting.

Limitation of RMI
Inherently, RMI server is not multi threaded. As a programmer, you have to take care of the variables in it. If a
programmer wishes to create a nontrivial application using RMI then it faces several difficulties, which is as
described below:
 Firstly, because of the requirements imposed on remote interfaces (they must implement Remote, and
their methods must throw RemoteException), it is found that interfaces not designed with RMI in mind
cannot be used remotely.
 Secondly, calls to remote interfaces prove bulky, because they must be enclosed in a try/catch block for
catching the possible RemoteException. Therefore, throughout the application, you must scatter
exception-handling code. To avoid doing so, developers usually limit remote invocation to a small portion
of their programs.
 Thirdly, it is found that the bother of RemoteExceptions also makes it difficult to user interfaces
designed for remote execution locally.
 Fourthly, no convenient approach can generically handle disconnections from a server in a single
location. (An example of such handling might include looking up the remote object again and trying to re-
invoke the method.)
 Since they normally extend UnicastRemoteObject, therefore implementations of Remote interfaces
cannot easily extend arbitrary classes. (You could avoid this limitation with some effort, by re-
implementing UnicastRemoteObject)

Concept
 Objects which have to be made available to other machines have to be exported to Remote Registry
Server so that they can be invoked.
 If Machine A wants to call methods of some object on machine B, then Machine B would have to export
that object on its Remote Registry Server (RRS).
 RRS is a service that runs on the server and helps client’s search and access objects on the server
remotely.
 Now, if an object has to be capable of being exported then it must implement the Remote Interface
present in the RMI package.
 For example, say that we want an object Xyz on machine A to be available for remote method
invocation, than it must implement the Remote Interface.
 RMI uses stub and a skeleton.

BE Comp. VII, BCA V, Kantipur City Collage 3


Prepared By: Shiba R. Tamrakar

 The stub is present on the client side, and the skeleton the server side.
 There are a number of events that have to take place beforehand which help in the communication of the
data.
 The stub is like a local object on the client side, which acts like a proxy of the object on the server side.
 It provides the methods to the client which can be invoked on the server.
 The stub then sends the method call to the skeleton, which is present on the server side.
 The Skeleton then implements the method on the server side.
 The stub and skeleton communicate with each other through Remote Reference Layer (RRL).
 This layer gives the stub and skeleton the capability to send data using the TCP/IP protocol.
 Whenever a client wants to make a reference to any object on the server, have we thought how he
would tell the server what object he wants to create? Well, this is where the concept of Binding comes
in.
 On the server end we associate a string variable with an object.
 The client tells the server what object he wants to create by passing that string to these strings and
objects are stored in the RRS on the Server.

Some terminologies used in RMI coding


 The Remote Object
 This interface will have only method declarations.
 It will have a declaration for each method that we want to export.
 This would implement the Remote interface, which is present in the Java.rmi package.
 The Remote Object Implementation
 This is a class that implements the Remote Object.
 If we implement the Remote Object, its common sense that we implementation class would actually
have all of the method bodies of the methods that we want to export.
 This method will be extended from the UnicastRemoteObject class.
 The Remote Server
 This is a class that will act like a server to the client wanting to access remote methods.
 Here’s the place where we will bind any string with the object we want to export.
 The binding process will be taken care of in this class.
 The Remote Client
 This is a class that will help us access the remote method.
 This is the end user, the client.
 We will call the remote method from this class.
 We will use methods to search and invoke that remote method.

RMI Architecture

There are three layers that comprise the basic remote-object communication facilities in RMI:

o The stub/skeleton layer, which provides the interface that client and server application objects use
to interact with each other.
o The remote reference layer, which is the middleware between the stub/skeleton layer and the
underlying transport protocol. This layer handles the creation and management of remote object
references.
o The transport protocol layer, which is the binary data protocol that sends remote object requests
over the wire.

 These layers interact with each other as shown in Figure 3-1.In this figure, the server is the application
that provides remotely accessible objects, while the client is any remote application that communicates

BE Comp. VII, BCA V, Kantipur City Collage 4


Prepared By: Shiba R. Tamrakar

with these server objects.


 In a distributed object system, the distinctions between clients and servers can get pretty blurry at times.
 Consider the case where one process registers a remote-enabled object with the RMI naming service,
and a number of remote processes are accessing it.
 We might be tempted to call the first process the server and the other processes the clients.
 But what if one of the clients calls a method on the remote object, passing a reference to an RMI object
that's local to the client.
 Now the server has a reference to and is using an object exported from the client, which turns the tables
somewhat.
 The "server" is really the server for one object and the client of another object, and the "client" is a client
and a server, too.
 For the sake of discussion, I'll refer to a process in a distributed application as a server or client if its role
in the overall system is generally limited to one or the other.
 In peer-to-peer systems, where there is no clear client or server, I'll refer to elements of the system in
terms of application-specific roles (e.g., chat participant, chat facilitator).

Figure 3-1. The RMI runtime architecture


 As you can see in Figure 3-1, a client makes a request of a remote object using a client-side stub; the
server object receives this request from a server-side object skeleton. A client initiates a remote method
invocation by calling a method on a stub object. The stub maintains an internal reference to the remote
object it represents and forwards the method invocation request through the remote reference layer by
marshalling the method arguments into serialized form and asking the remote reference layer to
forward the method request and arguments to the appropriate remote object. Marshalling involves
converting local objects into portable form so that they can be transmitted to a remote process. Each
object is checked as it is marshaled, to determine whether it implements the java.rmi.Remote

BE Comp. VII, BCA V, Kantipur City Collage 5


Prepared By: Shiba R. Tamrakar

interface. If it does, its remote reference is used as its marshaled data. If it isn't a Remote object, the
argument is serialized into bytes that are sent to the remote host and reconstituted into a copy of the
local object. If the argument is neither Remote nor Serializable, the stub throws a
java.rmi.MarshalException back to the client.

If the marshalling of method arguments succeeds, the client-side remote reference layer receives the remote
reference and marshaled arguments from the stub. This layer converts the client request into low-level RMI
transport requests according to the type of remote object communication being used. In RMI, remote objects can
(potentially) run under several different communication styles, such as point-to-point object references, replicated
objects, or multicast objects. The remote reference layer is responsible for knowing which communication style is
in effect for a given remote object and generating the corresponding transport-level requests. In the current
version of RMI (Version 1.2 of Java 2), the only communication style provided out of the box is point-to-point
object references, so this is the only style we'll discuss in this chapter. For a point-to-point communication, the
remote reference layer constructs a single network-level request and sends it over the wire to the sole remote
object that corresponds to the remote reference passed along with the request.

On the server, the server-side remote reference layer receives the transport-level request and converts it into a
request for the server skeleton that matches the referenced object. The skeleton converts the remote request
into the appropriate method call on the actual server object, which involves unmarshalling the method arguments
into the server environment and passing them to the server object. As you might expect, unmarshalling is the
inverse procedure to the marshalling process on the client. Arguments sent as remote references are converted
into local stubs on the server, and arguments sent as serialized objects are converted into local copies of the
originals.

If the method call generates a return value or an exception, the skeleton marshals the object for transport back to
the client and forwards it through the server reference layer. This result is sent back using the appropriate
transport protocol, where it passes through the client reference layer and stub, is unmarshaled by the stub, and
is finally handed back to the client thread that invoked the remote method.

RMI Object Services

On top of its remote object architecture, RMI provides some basic object services you can use in your distributed
application. These include an object naming/registry service, a remote object activation service, and distributed
garbage collection.

Naming/registry service
 When a server process wants to export some RMI-based service to clients, it does so by registering one
or more RMI-enabled objects with its local RMI registry (represented by the Registry interface).
 Each object is registered with a name clients can use to reference it.
 A client can obtain a stub reference to the remote object by asking for the object by name through the
Naming interface.
 The Naming.lookup( ) method takes the fully qualified name of a remote object and locates the object on
the network.
 The object's fully qualified name is in a URL-like syntax that includes the name of the object's host and
the object's registered name.
 It's important to note that, although the Naming interface is a default naming service provided with RMI,

BE Comp. VII, BCA V, Kantipur City Collage 6


Prepared By: Shiba R. Tamrakar

the RMI registry can be tied into other naming services by vendors.
 Once the lookup( ) method locates the object's host, it consults the RMI registry on that host and asks for
the object by name.
 If the registry finds the object, it generates a remote reference to the object and delivers it to the client
process, where it is converted into a stub reference that is returned to the caller.
 Once the client has a remote reference to the server object, communication between the client and the
server commences as described earlier.
 We'll talk in more detail about the Naming and Registry interfaces later in this chapter.

Object activation service


 The remote object activation service is new to RMI as of Version 1.2 of the Java 2 platform.
 It provides a way for server objects to be started on an as-needed basis.
 Without remote activation, a server object has to be registered with the RMI registry service from within a
running Java virtual machine.
 A remote object registered this way is only available during the lifetime of the Java VM that registered it.
 If the server VM halts or crashes for some reason, the server object becomes unavailable and any
existing client references to the object become invalid.
 Any further attempts by clients to call methods through these now-invalid references result in RMI
exceptions being thrown back to the client.
 The RMI activation service provides a way for a server object to be activated automatically when a client
requests it.
 This involves creating the server object within a new or existing virtual machine and obtaining a
reference to this newly created object for the client that caused the activation.
 A server object that wants to be activated automatically needs to register an activation method with the
RMI activation daemon running on its host.
 We'll discuss the RMI activation service in more detail later in the chapter.

Distributed garbage collection


 The last of the remote object services, distributed garbage collection, is a fairly automatic process that
you as an application developer should never have to worry about.
 Every server that contains RMI-exported objects automatically maintains a list of remote references to
the objects it serves.
 Each client that requests and receives a reference to a remote object, either explicitly through the
registry/naming service or implicitly as the result of a remote method call, is issued this remote object
reference through the remote reference layer of the object's host process.
 The reference layer automatically keeps a record of this reference in the form of an expirable "lease" on
the object.
 When the client is done with the reference and allows the remote stub to go out of scope, or when the
lease on the object expires, the reference layer on the host automatically deletes the record of the
remote reference and notifies the client's reference layer that this remote reference has expired.
 The concept of expirable leases, as opposed to strict on/off references, is used to deal with situations
where a client-side failure or a network failure keeps the client from notifying the server that it is done
with its reference to an object.
 When an object has no further remote references recorded in the remote reference layer, it becomes a
candidate for garbage collection.
 If there are also no further local references to the object (this reference list is kept by the Java VM itself
as part of its normal garbage-collection algorithm), the object is marked as garbage and picked up by the
next run of the system garbage collector.

BE Comp. VII, BCA V, Kantipur City Collage 7


Prepared By: Shiba R. Tamrakar

Sample Code
//AddServer.java
import java.rmi.*;

public interface AddServer extends Remote


{
public int AddNumbers(int fno,int sno) throws RemoteException;
}

//AddServerImpl.java
import java.rmi.*;
import java.rmi.server.*;
public class AddServerImpl extends UnicastRemoteObject implements AddServer
{

public AddServerImpl() throws RemoteException


{
super();
}

public int AddNumbers(int fno,int sno) throws RemoteException


{

return fno+sno;
}
}

//RmiServer.java
import java.rmi.*;
import java.net.*;

public class RmiServer


{
public static void main(String args[]) throws RemoteException, MalformedURLException
{
AddServerImpl add=new AddServerImpl();
Naming.rebind("addnumbers",add);
}
}

//RmiClient.java
import java.rmi.*;
import java.net.*;
public class RmiClient
{
public static void main(String args[]) throws RemoteException, MalformedURLException,
NotBoundException
{
String url="rmi://127.0.0.1/addnumbers";
AddServer add;
add=(AddServer)Naming.lookup(url);
int result =add.AddNumbers(10,5);
System.out.println(result);
}

BE Comp. VII, BCA V, Kantipur City Collage 8


Prepared By: Shiba R. Tamrakar

Compiling RMI
Compile Remote object:
javac AddServer.Java
Compile Remote Object Implementation:
javac AddServerImpl.Java
 We end up with two Java files and two class files.
 We are now going to create our stub and skeleton.
 For creating the stub and skeleton files we have to use the rimc compiler on the remote object
implementation file.
rmic AddServerImpl
 After following the above step you will see that two newer class files have been created.
 They are addServerImpl_Stub.class (the stub which will reside on the client side and
AddServerImpl_skel.class (the skeleton which will reside on the server side).
Compile RMIServer.java as well as RMIClient.java
Compile RMIServer.java
javac RMIServer.Java
Compile RMIClient:
javac RMIClient.Java
 Start RMI Registry server
start rmiregistry
 Run RMIServer First and then RMIClient.
Run->Cmd <enter>
Go to the folder where you store java files
java RmiServer
Run->cmd <enter>
Go to the folder where you store java files
Java RmiClient

BE Comp. VII, BCA V, Kantipur City Collage 9

You might also like