Java AOOP
Java AOOP
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.
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.
Interpreted or JIT
compilation
Executable Code
2
Prepared By: Shiba R. Tamrakar
}
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.
3
Prepared By: Shiba R. Tamrakar
javac null.java
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:
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
C:\JDK\JAVA\CLASSES;c:\java\lib\classes.zip
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
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
String Constructors
String s=new String( )
5
Prepared By: Shiba R. Tamrakar
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
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)
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();
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[]) {
$ javac Energy.java
$ java Energy 0.0456
4.09853e+15 Joules
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 {
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( )
9
Prepared By: Shiba R. Tamrakar
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?
10
Prepared By: Shiba R. Tamrakar
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
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
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
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
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
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
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.
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.
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.
Examples
import java.applet.*;
import java.awt.*; // required to paint on screen
// 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)
{
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);
// reset the color to the standard color for the next time
the applets paints
g.setColor(Color.black);
}
}
g.setColor( Color.red );
g.drawRect( 10, 20, 100, 15 );
g.setColor( Color.pink );
g.fillRect( 240, 160, 40, 110 );
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 );
}
}
mx = width/2;
my = height/2;
addMouseListener( this );
addMouseMotionListener( this );
}
}
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();
}
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");
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>
(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
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),
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
• 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);
}
• 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.
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.*;
ButtonDemo()
{
super(“Button Demo”);
setSize(350,250);
Container c=getContentPane();
c.setLayout(new FlowLayout());
btnExit=new JButten(“Exit”);
c.add(btnExit);
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();
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.*;
}
ScrollBarDemo(){
super("Scroll Bar Demo");
setSize(350,250);
Container cont = getContentPane();
JScrollBar sbar = new JScrollBar(JScrollBar.HORIZONTAL);
cont.add(sbar,BorderLayout.NORTH);
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
TextDemo(){
super("TextDemo");
setSize(350,250);
Container cont = getContentPane();
area=new JTextArea();
cont.add(area,BorderLayout.CENTER);
}
public void keyPressed(KeyEvent e){
System.out.println(e);
}
}
}
JComboBox
ComboDemo()
{
super("ComboDemo");
setSize(350,250);
Container cont = getContentPane();
cont.setLayout(new FlowLayout());
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.
• These return the preferred and minimum size required to display each component.
FlowLayout Class
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: After resize (decrease the width and increase the height)
BorderLayout Class
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);
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)
BoxLayout Class
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)
GridBagLayout
• GridBagLayout is the most sophisticated, flexible layout manager the Java platform
provides.
• 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:
Hints:
Students should be familier with AWT, Swing, JFrame, JPanel, JTextField, JLabel,
JCheckBox, JRadioButton and JTextArea along with event handling.
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.*;
//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);
//// 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
}
}
}
import java.awt.event.WindowEvent;
import javax.swing.*;
String fields[]={"Name","Address","Education"};
}
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 JListEx()
{
nameList = new DefaultListModel();
nameList.addElement("Ramesh");
nameList.addElement("Santosh");
nameList.addElement("Prakash");
list.setSelectionMode( ListSelectionModel.SINGLE_SELECTION);
removeButton.addActionListener(
new ActionListener(){
public void actionPerformed (ActionEvent event )
{
nameList.removeElement( list.getSelectedValue());
}
}
);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(400,300);
setVisible(true);
} //end of JListEx constructor
(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
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)
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.*;
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.*;
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);
}
}
}
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);
}
}
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());
}
}
}
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.*;
System.out.println("obj2"+obj2);
}
catch(Exception e)
{
System.out.println("the error is : "+e);
}
}
}
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.
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
Application
JDBC-Driver
Manager
ODBC Driver ODBC
Database
Manager
ODBC libraries
Application
JDBC
DBMS Vendor Client
Socket
Side Libraries base DBMS
Connection
on C language Server
2
Prepared By: Shiba R. Tamrakar
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).
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
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
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.
5
Prepared By: Shiba R. Tamrakar
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.*;
ResultSet r;
try
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection c=DriverManager.getConnection("jdbc:odbc:mydsn");
Statement st=c.createStatement( );
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);
import java.sql.*;
static Connection c;
int ch;
/* For Mysql
Class.forName("com.mysql.jdbc.Driver").newInstance( );
c = DriverManager.getConnection("jdbc:mysql://localhost/cba?user=shiba&password=pword");
*/
c=DriverManager.getConnection("jdbc:oracle:oci8:@cba","scott","tiger");
*/
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
try
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");
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:
case 6:
System.out.println("Thank you");
System.exit(0);
default:
System.out.println("Invalid Choice");
}while(ch!=6);
catch(Exception e){ }
try
ResultSet r;
int row=0;
Statement st=c.createStatement( );
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){ }
for(int k=1;k<25;k++)
System.out.println( );
try
int row;
Statement ins_st;
ins_st=c.createStatement( );
System.out.println("4032,shiba");
c.commit( );
catch(SQLException e)
System.out.println("Error in insert"+e);
10
Prepared By: Shiba R. Tamrakar
try
int row;
Statement modi_st;
modi_st=c.createStatement( );
c.commit( );
}catch(SQLException e)
try
System.out.println("4032,cba");
int row;
Statement del_st;
del_st=c.createStatement( );
if (row>0)
c.commit( );
else
11
Prepared By: Shiba R. Tamrakar
catch(SQLException e)
/*
*/
Oracle Handout (SSI book) and Complete Reference of Oracle 9i, Oracle Press
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.
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.
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 bidirectional 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
Overview
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
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.
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.
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
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.
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.
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
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.
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,
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.
Sample Code
//AddServer.java
import java.rmi.*;
//AddServerImpl.java
import java.rmi.*;
import java.rmi.server.*;
public class AddServerImpl extends UnicastRemoteObject implements AddServer
{
return fno+sno;
}
}
//RmiServer.java
import java.rmi.*;
import java.net.*;
//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);
}
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