Documente Academic
Documente Profesional
Documente Cultură
for
MCA Year
Department of MCA
Gokaraju Rangaraju Institute of Engineering and Technology
Hyderabad.
Contents
Unit I
Introduction to Java
What is Java?
Java Features
Java Platform
The "Hello World" Application
Command Line Arguments
Arrays
Labeled loops
Unit-II
Object Oriented Programming
Inheritance
Interface
Exceptions
Multi Threading
Life Cycle of a thread
Synchronization of Threads
Creating and Using Packages
Accessing Package members
Unit – III
Abstract Window Toolkit
AWT Introduction
Layout Managers
GUI Control Components
Overview of Event Handling
Examples on GUI components with Event handling
Applets
Overview of an Applet
HelloWorld Applet
Methods for Drawing and Handling Events in Applets
Methods for add user interfaces to applets.
What applets can and can’t do.
Threads in Applets
Graphics Class
Font Class
Color Class
Unit – IV
Input/output
Introduction
Character Streams
Reader classes
Writer classes
Byte Streams
Input Stream
Output Stream
Understanding the I/O super classes.
Pipe Streams
Data Input and Output Streams.
Object serialization
Working with Random Access files
Writing filters for Random Access files
File class
Unit – V
Networking
Networking Basics.
Networking classes in JDK
URL
Parsing an URL
Reading Directly from an URL
Connecting to an URL
Sockets
Client Server Programming using Sockets
Reading from and Writing to a Socket
Datagrams
Client Server Programming using Datagrams.
Unit – I
Introduction to Java
What is Java?
Java is a programming language and also a software platform.
Java Features
Java is a high-level programming language that satisfies the following:
-neutral
-oriented
-performance
Java program is both compiled and interpreted. With a compiler, you translate a Java
program into an intermediate code called Java bytecode(platform-independent code).
This code is interpreted by the Java interpreter. With an interpreter, each Java bytecode
instruction is parsed and run on the computer. Compilation happens just once;
interpretation occurs each time the program is executed. The following figure illustrates
how this works.
Java Platform
A platform is the hardware or software environment in which a program runs. The Java
platform is a software-only platform that runs on top of different hardware-based
platforms.
The Java platform has two components:
The Java Virtual Machine (Java VM)
The Java Application Programming Interface (Java API)
Java VM is the base for the Java platform and is ported onto various hardware-based
platforms. The Java API is a large collection of ready-made software components that
provide many useful capabilities, such as graphical user interface (GUI) widgets.
class HelloWorldApp {
public static void main(String[] args) {
System.out.println("Hello World!");
//Display the string.
}
}
2. Compile the Source File
Compile the source file using the Java compiler.
OUTPUT:
Example :
This application displays each of its command-line arguments on a line by itself:
class Echo
{
public static void main (String[] args)
{
for (int i = 0; i < args.length; i++)
System.out.println(args[i]);
}
}
OUTPUT:
Arrays:
An array is a data structure, which defines an ordered collection of a fixed number of
homogeneous data elements. In java arrays are objects. Arrays can be primitive data
types or reference types. Each array object has an instance variable & length, which
specifies the number of elements the array can accommodate.
OUTPUT:
In Java, we can give a label to a block of statements. A label is any valid Java variable
name. To give a label to a loop, place it before the loop with a colon at the end.
class labelContinue
{
public static void main(String args[])
{
int sum = 0;
loop1: for(int i = 0; i< 5; i++)
{
for(int j=0; j< 5; j++)
{
if (j==3)
{ System.out.println(" ");
continue loop1;
}
sum += i;
System.out.print(" "+ sum);
}
}
}
}
OUTPUT:
Unit-II
Object Oriented Programming
Inheritance
The mechanism of deriving a new class from old one is called Inheritance. As in C++
Java also supports different types of inheritance except multiple inheritance. The multiple
inheritance is achieved in java using a concept called Interface. The constructor in
derived class uses the super keyword to pass values that are required by the base
constructor. A subclass constructor is used to construct the instance variables of both the
subclass and the super class. The types of inheritance supported by java are as follows.
1. Single Inheritance
In Single inheritance any Subclass will have only one Super class.
2. Hierarchical Inheritance
One Super class will have many Subclasses derived from it.
3. Multilevel Inheritance
Subclass is derived from a Super class, which is a Subclass to another Super class.
class Circle{
int length;
public void circle_area(int x)
{
length = x;
System.out.println("The area of Circle : "+ Math.round(Math.PI*length*length));
}
}
class Square extends Circle
{
public void square_area(int x)
{
length =x;
System.out.println("The area of square: "+length*length);
}
}
public class RefVar{
public static void main(String args[]) {
Square sq = new Square();
Circle ci;
ci = sq;
ci.circle_area(7);
sq.square_area(15);
//ci.square_area(10);
/*The above statement raises compile time error as superclass does not have any idea of
what methods and variables are added to the subclass*/
}
}
OUTPUT:
Interfaces:
Achieving Multiple Inheritance using Interface
What Is an Interface?
An interface is a named collection of method definitions (without implementations). An
interface can also include constant declarations. Often interfaces are treated as an
alternative to multiple class inheritance.
A class inherits only constants from an interface.
A class cannot inherit method implementations from an interface.
The interface hierarchy is independent of the class hierarchy. Classes that implement the
same interface may or may not be related through the class hierarchy.
Defining an Interface
Defining an interface is similar to creating a new class. An interface definition has two
components: the interface declaration and the interface body.
interfaceDeclaration {
interfaceBody
}
The interfaceDeclaration declares various attributes about the interface, such as its name,
whether it extends another interface etc. The interfaceBody contains the constant and
method declarations within the interface.
Implementation of Interface
To use an interface, you write a class that implements the interface. All the methods that
are declared in the interface should be defined in the class that implements the interface.
You can use interface names anywhere as you use any other data type name.
Example:
Exceptions:
Handling Errors with Exceptions
Definition: An exception is an event that occurs during the execution of a program that
disrupts the normal flow of instructions.
Exceptions are part of the inheritance hierarchy and are derived from the Throwable
class. An exception is an instance of the Throwable class. The Exception hierarchy is
given below.
In Java{,} Exceptions are handled via five key words : try, catch, throw, throws and
finally.
Try : Program statements that we want to monitor for exceptions is contained within try
block.
Catch: Catches the exception thrown and handles it.
Throws: If a method is capable of causing an exception that is does not handle, it must
specify this behavior so that callers of the method can guard themselves against that
exception. This is done using throws clause in declaration.
Finally : Any code that absolutely must be executed before a method returns is put in a
finally block.
Throw: This is used to manually throw the exception(usually, used in user defined
exceptions).
An Example on Exception
import java.io.*;
public class DivideExcep
{
public static void main(String[] s)
{
int k,i=3, j=0;
try
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int x = Integer.parseInt(br.readLine());
System.out.println(x);
k = i/j;
}
catch(NumberFormatException e)
{
System.out.println("number format exeception");
}
catch(IOException ioe)
{
System.out.println("IOException has occured.");
}
catch(ArithmeticException ex)
{
System.out.println("Divide By Zero occured.");
}
finally
{
System.out.println("Finally block is executed.");
}
}
}
OUTPUT:
An Example User Defined Exception
The following program is an example for user defined exception. It raises myexception
when the basic pay of an employee is less than Rs. 3000/-.
class Throwsdemo{
String name;
int basicpay;
float hra, gross;
void display(){
System.out.println("Name : " + name);
System.out.println("Basic: " + basicpay);
System.out.println("Hra : " + hra);
System.out.println("Gross: " + gross);
}
OUTPUT:
Multi Threading
The Web browser is an example of a multithreaded application. Within the Web browser
you can scroll a page while it's downloading an applet or image, play animation and
sound concurrently, print a page in the background while you download a new page.
Creating a Thread
Threads are implemented in the form of objects that contain a method called run(). The
run() method specifies the behavior of the thread.
There are two techniques for providing a run method for a thread:
Subclassing Thread and Overriding run()
Implementing the Runnable Interface
Looks like I'm going to Goa!!) Notice how the output from each thread is intermingled
with the output from the other. This is because both SimpleThread threads are running
concurrently. Thus, both run methods are running at the same time and each thread is
displaying its output at the same time as the other.
Implementing the Runnable Interface
The Clock applet uses a different technique than SimpleThread for providing the run
method for its thread. Instead of subclassing Thread, Clock implements the Runnable
interface (and therefore implements the run method defined in it). Clock then creates a
thread with itself as the Thread's target. When created in this way, the Thread gets its run
method from its target. The code that accomplishes this is shown in bold here:
import java.awt.Graphics;
import java.util.*;
import java.text.DateFormat;
import java.applet.Applet;
The Clock applet's run method loops until the browser asks it to stop. During each
iteration of the loop, the clock repaints its display. The paint method figures out what
time it is, formats it in a localized way, and displays it.
The Life Cycle of a Thread
The following diagram shows the states that a Java thread can be in during its life. It also
illustrates which method calls cause a transition to another state. This figure is not a
complete finite state diagram, but rather an overview of the more interesting and common
facets of a thread's life.
A thread arranges for its own death by having a run method that terminates naturally. For
example, the while loop in this run method is a finite loop-- it will iterate 100 times and
then exit.
public void run() {
int i = 0;
while (i < 100) {
i++;
System.out.println("i = " + i);
}
}
Note:
We can set Numeric Priorities to threads between MIN_PRIORITY and
MAX_PRIORITY (constants defined in the Thread class). The Java runtime supports a
very simple, deterministic scheduling algorithm known as fixed priority scheduling.
When all the runnable threads in the system have the same priority, the scheduler chooses
the next thread to run in a simple, non-preemptive, round-robin scheduling order.
Synchronizing Threads:
So far, we have seen examples of independent, asynchronous threads. However, there are
many interesting situations where separate, concurrently running threads do share data
and must consider the state and activities of other threads. One such set of programming
situations are known as producer/consumer scenarios where the producer generates a
stream of data, which is then consumed by a consumer.
For example, imagine a Java application where one thread (the producer) writes data to a
file while a second thread (the consumer) reads data from the same file. These examples
use concurrent threads that share a common resource (ie., a file). As the threads share a
common resource, they must be synchronized in some way.
Example:
The Producer and Consumer in this example share data through a common CubbyHole
object. And you will note that neither the Producer nor the Consumer makes any effort
whatsoever to ensure that the Consumer is getting each value produced once and only
once.
The Main Program
Here's a small stand-alone Java application that creates a CubbyHole object, a Producer, a
Consumer, and then starts both the Producer and the Consumer.
A package is a collection of related classes and interfaces that provides access protection
and namespace management.
Creating a Package:
1. Declare the package statement at the beginning of every source file that defines a
class or interface that is to be a member of the graphics package.
Ex: Following code appears in the source file Circle.java and puts the Circle class in the
graphics package:
package graphics;
public class Circle extends Graphic implements Draggable { . . .
}
2. Define the class that is to be put in the package and declare it public.
3. Compile the file with the following command, the circle.java file.
C:\> javac –d . Circle.java
This will create the directory graphics and places the circle.class file in the graphics
directory.
The scope of the package statement is the entire source file, so all classes and interfaces
defined in Circle.java are also members of the graphics package.
If you do not use a package statement, your class or interface ends up in the default
package, which is a package that has no name.
Example:
circle.java
package geometry;
public class circle
{
public circle()
{ System.out.println("Circle object created");
}
}
class oval
{
oval()
{ System.out.println("Oval object created");
}
}
Poly.java
package geometry.polygon;
public class Poly
{
public Poly()
{
System.out.println("Polygon object created");
}
}
rect.java
package geometry.polygon;
public class rect
{
public rect()
{
System.out.println("Rectangle object created");
}
}
D:\lal>dir
D:\lal>dir geometry
D:\lal>dir geometry\polygon
runpack.java
import geometry.*;
import geometry.polygon.*;
class runpack{
public static void main(String args[])
{
circle c = new circle();
// oval v = new oval();
/*oval object can't be created as it's access modifier
is declared as default.*/
rect r = new rect();
Poly p = new Poly();
}
}
D:\lal>javac runpack.java
D:\lal>java runpack
Circle object created
Rectangle object created
Polygon object created
Unit – III
Abstract Window Toolkit
AWT Introduction:
The Java Foundation Classes(JFC) provide two frameworks for building GUI-based
applications. The Abstract Windowing Toolkit(AWT) relies on the underlying windowing
system on a specific platform to present its GUI components. The other GUI toolkit in
the JFC, called Swing, implements a new set of lightweight GUI components that are
written in Java and have a pluggable look and feel. They are lightweight because they are
not dependent on the underlying windowing system.
The Component Hierarchy of AWT
Object
GUI Control
Com ponent {abstract} Components
(are concrete
Container subclasses of
this class.)
Panel
Applet
W indow
dialog
Fram e
1. Layout Managers:
The Layout manager implements a layout policy that defines spatial relationships
between components in a container. These relationships or constraints specify the
placement and sizes of components, including resizing of the GUI, is taken care of by
layout managers in Java. A layout manager works in conjunction with a container
holding the components.
A component can be a container, with other components embedded in it. The Java
provides five layout managers. They are summarized as follows:
GridLayout : Lays out the components in a specified rectangular grid, from left
to right in each row, and filling rows from top to bottom in the container.
CardLayout : Components are handled as a stack of indexed cards with only the
top component being visible in the container.
GridBagLayout : Customizable and flexible layout manager that lays out the
components in a rectangular grid. A component can occupy multiple cells in the grid.
1. An Example of FlowLayout
import java.awt.*;
import java.awt.event.*;
public class flAsmd extends Frame{
flAsmd(){
Button b1,b2,b3,b4;
TextField t1,t2,t3;
Label l1,l2,l3;
Frame f1 = new Frame();
b1= new Button("Addition");
b2 = new Button("Substraction");
b3 = new Button("Multiplication");
b4 = new Button("Division");
l1 = new Label("Number 1 : ");
l2 = new Label("Number 2 : ");
l3 = new Label("Result : ");
t1 = new TextField(10);
t2 = new TextField(10);
t3 = new TextField(10);
f1.setLayout(new FlowLayout());
f1.add(l1);
f1.add(t1);
f1.add(l2);
f1.add(t2);
f1.add(l3);
f1.add(t3);
f1.add(b1);
f1.add(b2);
f1.add(b3);
f1.add(b4);
f1.setSize(600,200);
f1.setVisible(true);
}
OUTPUT:
Note : This output is obtained after implementing Action Listeners.
2. An Example of GridLayout
import java.awt.*;
import java.awt.event.*;
f1.setLayout(new GridLayout(5,2));
f1.add(l1); f1.add(t1);
f1.add(l2); f1.add(t2);
f1.add(l3); f1.add(t3);
f1.add(b1); f1.add(b2);
f1.add(b3); f1.add(b4);
f1.setSize(600,200);
f1.setVisible(true);
}
public static void main(String args[])
{
glAsmd sd = new glAsmd();
}
}
OUTPUT:
setLayout(new BorderLayout());
b1.setBackground(Color.red);
add(b1,"North");
b2.setBackground(Color.cyan);
add(b2,"West");
b3.setBackground(Color.pink);
add(b3,"South");
b4.setBackground(Color.blue);
add(b4,"East");
b5.setBackground(Color.green);
add(b5,"Center");
}
}
OUTPUT:
sp.setLayout(cl);
// adding lists to panel sp
sp.add("a",plist);
sp.add("b",slist);
sp.add("c",mlist);
fb.addActionListener(this); pb.addActionListener(this);
nb.addActionListener(this); lb.addActionListener(this);
add(sp,"North"); add(bp,"South");
addWindowListener(new w());
}
OUTPUT:
addComponent(0,0,1,1,new Button("7"));
addComponent(0,1,1,1,new Button("8"));
addComponent(0,2,1,1,new Button("9"));
addComponent(0,3,1,1,new Button("-"));
addComponent(0,4,1,1,new Button("%"));
addComponent(1,0,1,1,new Button("4"));
addComponent(1,1,1,1,new Button("5"));
addComponent(1,2,1,1,new Button("6"));
addComponent(1,3,3,1,new Button("+"));
addComponent(1,4,1,1,new Button("/"));
addComponent(2,0,1,1,new Button("1"));
addComponent(2,1,1,1,new Button("2"));
addComponent(2,2,1,1,new Button("3"));
addComponent(2,4,2,1,new Button("x"));
addComponent(3,0,1,2,new Button("0"));
addComponent(3,2,1,1,new Button("."));
}
public void addComponent(int r,int co,int h,int w,Component c)
{
gbc.gridx=co;
gbc.gridy=r;
gbc.gridwidth=w;
gbc.gridheight=h;
gbl.setConstraints(c,gbc);
add(c);
}
OUTPUT:
Window
Frame
Dialog
The following three steps are essential in making use of a GUI control component:
Fle Dialog
Event handling in Java is based on the event delegation model. Its principle elements are:
Event classes that can encapsulate information about different types of user interaction.
Event source objects that inform event listeners about events when these occur and
supply the necessary information about these events.
Event listener objects that are informed by an event source when designated events
occur, so that they can take appropriate action.
Event Object
AWTEvent
AdjustmentEv ComponentEv
ActionEvent ItemEvent TextEvent
ent ent
ContainerEve
nt
FocusEvent
InputEvent
MouseEvent
KeyEvent
PaintEvent
WindowEvent
Handling events in a GUI application, using the event delegation model, can be divided
into the following two tasks
Setting up the propagation of events from event sources to event listeners.
Providing the appropriate actions in event listeners to deal with the events.
OUTPUT:
2. An Example on CheckGroup using Applet.
import java.awt.*;
import java.applet.*;
//<applet code = ChGrp width=300 height=300></applet>
SC.setCheckboxGroup(p);
SC.setState(true);
GC.setCheckboxGroup(p);
}
}
OUTPUT:
3. An Example of Canvas.
import java.awt.*;
import java.applet.*;
4. An Example on ListItem
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
//<applet code= ListDemo width=200 height=400></applet>
public class ListDemo extends Applet implements ActionListener, ItemListener{
Button b1;
List fruitList;
TextField tf1,tf2,tf3,tf4;
Label lb1,lb2,lb3,lb4;
public void init(){
add(fruitList);
add(b1);
add(lb1);
add(tf1);
add(lb2);
add(tf2);
add(lb3);
add(tf3);
add(lb4);
add(tf4);
b1.addActionListener(this);
fruitList.addActionListener(this);
fruitList.addItemListener(this);
}
import java.awt.*;
import java.awt.event.*;
public class TextEventEx extends Frame implements TextListener, ActionListener
{
TextField tf;
TextArea ta;
String prevText = "";
public TextEventEx()
{
tf = new TextField(30);
ta = new TextArea(" ",15,40,TextArea.SCROLLBARS_NONE);
ta.setFont(new Font("Courier",Font.ITALIC|Font.BOLD, 20));
ta.setEditable(false);
addWindowListener(new MyWinAdapt());
tf.addTextListener(this);
tf.addActionListener(this);
add("South",tf);
add("Center",ta);
setSize(500,500);
setVisible(true);
}
public void textValueChanged(TextEvent te)
{ ta.setText( prevText + tf.getText() );}
OUTPUT:
6. Scrollbar Example
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class Scrbar extends Applet
{
Label lb = new Label("The count");
TextField tf = new TextField(5);
Scrollbar sb = new Scrollbar(Scrollbar.VERTICAL, 15,10,1,300);
public void init()
{
add(lb); add(tf); add(sb);
sb.addAdjustmentListener(new ScrbarHandler());
}
OUTPUT:
7. An Example on Menusystem
import java.awt.*;
class Menusystem extends Frame
{
Menusystem()
{
setTitle("menubar");
MenuBar mbar=new MenuBar();
Menu file=new Menu("File");
Menu edit=new Menu("Edit");
submenu.add(i1);
submenu.add(i2);
submenu.add(i3);
file.add(open);
file.addSeparator();
file.add(save);
file.addSeparator();
file.add(close);
file.addSeparator();
file.add(exit);
edit.add(cut);
edit.addSeparator();
edit.add(copy);
edit.addSeparator();
edit.add(paste);
edit.add(submenu);
mbar.add(file);
mbar.add(edit);
setMenuBar(mbar);
}
public static void main(String args[])
{
Menusystem ms=new Menusystem();
ms.setBounds(100,100,400,200);
ms.setVisible(true);
}
}
OUTPUT:
8. An Example on MouseEvents
import java.awt.*;
import java.awt.event.*;
Figure 1 :When mouse moved on the Figure 2 : When mouse moved out of
window window
9. An Example On KeyEvents
import java.awt.*;
import java.awt.event.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
MenuDemo1(String s1)
{
super(s1);
ns = new MenuShortcut('N');
os = new MenuShortcut('O');
n = new MenuItem("New",ns);
o = new MenuItem("Open",os);
s = new MenuItem("Save");
c = new MenuItem("Close");
sub.add(a);
sub.add(ac);
ed.add(sub);
//adding actionlisteners
n.addActionListener(new New());
o.addActionListener(new Open());
s.addActionListener(new Save());
c.addActionListener(new Close());
addWindowListener(new MyWindowAdapter());
}
if(f1.getFile()!=null)
{
filename = f1.getDirectory() + f1.getFile();
setTitle(filename);
OpenFile();
}
ta1.requestFocus();
}
}
void OpenFile()
{
BufferedReader br;
StringBuffer sb = new StringBuffer();
try{
br = new BufferedReader(new FileReader(filename));
String line;
try
{
DataOutputStream dos = new DataOutputStream(new FileOutputStream(filename));
String line = ta1.getText();
BufferedReader br = new BufferedReader(new StringReader(line));
while((line = br.readLine())!=null)
{ dos.writeBytes(line+"\r\n"); }
dos.close();
}catch(Exception e1){System.out.println("File error");}
ta1.requestFocus();
}
}
}
OUTPUT:
APPLETS
Applet :
An Applet is a program that can be referenced by the HTML source code of a web page.
It is dynamically downloaded from a web server to a browser. The applet then executes
within the environment provided by the browser. Alternatively a tool such as an
appletviewer can be used to run it.
Overview of Applets
Every applet is implemented by creating a subclass of the Applet class. The following
figure shows the inheritance hierarchy of the Applet class.
An Example:HelloWorldApplet.java
import java.awt.*;
public class HelloWorldApplet extends Applet {
public void paint(Graphics g) {
g.drawString("Hello world!", 50, 25);
}
}
//HelloWorldApplet.html
/**<applet code="HelloWorldApplet.class" width=300 height=300></applet>*/
C:\>javac HelloWorldApplet.java
C:\>appletviewer HelloWorldApplet.html
OUTPUT:
A Simple Applet program
import java.applet.Applet;
import java.awt.Graphics;
OUTPUT:
Paint: The basic display method. Many applets implement the paint method to draw the
applet's representation within a browser page.
Update: A method you can use along with paint to improve drawing performance.
Applets inherit their paint and update methods from the Applet class, which inherits
them from the Abstract Window Toolkit (AWT) Component class.
Applets inherit a group of event-handling methods from the Component class. The
Component class defines several methods, such as action and mouseDown, for handling
particular types of events, and then one catch-all method called handleEvent.
It's easy to add components to applets and to use layout managers to control the
components onscreen positions.
OUTPUT:
}
}
OUTPUT:
What Applets Can and Can't Do
Every browser implements security policies to keep applets from compromising system
security. Current browsers impose the following restrictions on any applet that is loaded
over the network:
i. An applet cannot load libraries or define native methods.
ii. It cannot ordinarily read or write files on the host that's executing it.
iii. It cannot make network connections except to the host that it came from.
iv. It cannot start any program on the host that's executing it.
v. It cannot read certain system properties.
vi. Windows that an applet brings up look different than windows that an application
brings up.
vii. Applets can usually make network connections to the host they came from.
viii. Applets running within a Web browser can easily cause HTML documents to be
displayed.
ix. Applets can invoke public methods of other applets on the same page.
x. Applets that are loaded from the local file system (from a directory in the user's
class path) have none of the restrictions that applets loaded over the network do.
xi. Although most applets stop running once you leave their page, they don't have to.
Once you've written some code for your applet, you'll want to run your applet to test it.
To run an applet, you first need to add the applet to an HTML page, using the <Applet>
tag. You then specify the URL of the HTML page to your Java-enabled browser.
You include applets in HTML pages using the <APPLET> tag. When a browser
user visits a page that contains an applet, here's what happens:
The browser finds the class file for the applet's Applet subclass. The browser
brings the bytecodes over the network to the user's computer.
The browser creates an instance of the Applet subclass. When we refer to an
applet, we're generally referring to this instance.
The browser calls the applet's init method. This method performs any one-time
initialization that is required.
The browser calls the applet's start method. This method often starts a thread to
perform the applet's duties.
What Should the Applet Let the User Configure?
The parameters to your applet may contain
Resource locations of image and sound files (or)
Sometimes details of the applet's appearance or operation.
The following program uses AppletButton five times for five different examples,
one per layout manager the AWT provides. AppletButton's GUI is simple, consisting of
a button and a label that displays status. When the user clicks the button, the applet brings
up a window.
The AppletButton class is so flexible because it defines parameters that let the user
specify any or all of the following:
The type of window to bring up
The window's title
The window's height
The window's width
The label of the button that brings up the window
Here's what a typical <APPLET> tag for AppletButton looks like. You can see this applet
running at the URL Using Layout Managers
When the user doesn't specify a value for a parameter, AppletButton uses a reasonable
default value. For example, if the user doesn't specify the window's title, AppletButton
uses the window's type as the title.
The following is the code AppletButton uses to get its parameter values from the user.
Your applet might need to convert the string that getParameter returns into another
form, such as an integer. The java.lang package provides classes such as Integer that
you can use to help with converting strings to primitive types. Here's an example from
the AppletButton class of converting a parameter's value into an integer:
int requestedWidth = 0;
...
String windowWidthString = getParameter("WINDOWWIDTH");
if (windowWidthString != null) {
try {
requestedWidth = Integer.parseInt(windowWidthString);
} catch (NumberFormatException e) {
//Use default width.
}
}
Note that if the user doesn't specify a value for the WINDOWWIDTH parameter, the above
code uses a default value of 0, which the applet interprets as "use the window's natural
size." It's important that you supply default values wherever possible.
Besides using the getParameter method to get values of applet-specific parameters, you
can also use getParameter to get the values of attributes of the applet's <APPLET> tag.
An Example: AppletButton
Below is the AppletButton code that gets the applet's parameters.
String windowClass;
String buttonText;
String windowTitle;
int requestedWidth = 0;
int requestedHeight = 0;
...
public void init() {
windowClass = getParameter("WINDOWCLASS");
if (windowClass == null) {
windowClass = "TestWindow";
}
buttonText = getParameter("BUTTONTEXT");
if (buttonText == null) {
buttonText = "Click here to bring up a " + windowClass;
}
windowTitle = getParameter("WINDOWTITLE");
if (windowTitle == null) {
windowTitle = windowClass;
}
Threads in Applets
import java.applet.*;
import java.awt.*;
// <applet code = Dots width=250 height =300></applet>
OUTPUT:
Creating a User Interface
Most applets have a graphical user interface (GUI). Because the Applet class is a
subclass of the AWT Panel class and thus participates in the AWT event and drawing
model, creating an applet's GUI is just as easy as creating an application's GUI . In
addition to its graphical UI, an applet can use several other UI types, depending on the
kind of information it needs to give or get. Some applets play sounds, either to give the
user feedback or to provide ambiance. Applets can get configuration information from
the user through parameters that the applet defines. To give text information to the user,
an applet can use its GUI, display a short status string (for text that's not crucial), or
display to the standard output or standard error stream (for debugging purposes).
Graphics Class:
The Graphics class provided by Abstract Window Toolkit(AWT) encapsulates a set of
methods that can perform graphics output. This class allows us to draw strings, lines,
rectangles, ovals, strings, images, characters and arcs.
void drawArc(int x, int y, int width, int height, int degrees0, int degrees1)
void drawImage(Image img, int x, int y, ImageObserver io)
void drawLine(int x1, int y1, int x2, int y2)
void drawOval(int x, int y, int width, int height)
void drawPolygon(int x[], int y[], int n)
void drawPolyline(int x[], int y[], int n)
void drawRect(int x, int y, int width, int height)
void drawString(String s, int x, int y)
void fillArc(int x, int y, int width, int height, int degrees0, int degrees1)
void fillOval(int x, int y, int width, int height)
void fillPolygon(int x[], int y[], int n)
void fillRect(int x, int y, int width, int height)
Examples:
1. An Example on DrawImage
import java.applet.*;
import java.awt.*;
OUTPUT:
//arcs.polygons,lines,rectangles,ovals
import java.applet.*;
import java.awt.*;
g.setColor(Color.pink);
Rectangle bounds = star.getBounds();
g.drawRect(bounds.x,bounds.y, bounds.width, bounds.height);
g.setColor(Color.red);
g.drawArc(10,10,50,50,30,300);
g.fillArc(70,10,50,50,30,300);
g.setColor(Color.green);
g.drawLine(10,140,10,200);
g.setColor(Color.pink);
g.drawLine(10,140,70,200);
g.setColor(Color.cyan);
g.drawLine(10,140,70,140);
g.setColor(Color.blue);
g.drawOval(90, 70, 40,60);
g.fillOval(90,140, 40,60);
g.setColor(Color.pink);
g.drawOval(10,210, 50,50);
g.fillOval(90,210, 50,50);
}
}
//<applet code=shapes width=200 height = 400></applet>
OUTPUT:
Color Class
The Color class is in AWT package. Each instance of this class represents a particular
color.
Color(int red, int green, int blue) // int values range between 0 – 255.
Color(int rgb)// rgb components are specified in bits 23-16, 15-8, 7-0.
Color(float r, float g, float b) // float values range between 0.0 to 1.0.
add(p,"North");
c = new Canvas();
c.setBackground(Color.black);
add(c,"Center");
addWindowListener(new w());
}
OUTPUT:
Font Class
Font class: It is derived by AWT package. A font determines the size and appearance of
characters in a string.
Font(String n, int style, int ps)
Name identifies the font, (ex. Arial, Times new Roman etc.)
Style (BOLD, ITALIC, PLAIN).
Ps the point size of the font.
Methods:
void setFont(Font font)
Font getFont()
FontMetrics class: Allows you to get several metrics about the size of a font. This is also
derived by AWT package.
Methods:
FontMetrics getFontMetrics() int getHeight()
int charWidth(char c) int getLeading()
int getAscent() int stringWidth(String s)
int getDescent()
Unit – IV
Input/output
Introduction:
Often programs need to bring in information from an external source or send out
information to an external destination. The information can be anywhere: in a file, on
disk, somewhere on the network, in memory, or in another program. Also, it can be of
any type: objects, characters, images, or sounds.
To bring in information, a program opens a stream on an information source (a file,
memory, a socket) and reads the information serially, like this:
No matter where the information is coming from or going to and no matter what type of
data is being read or written, the algorithms for reading and writing data is pretty much
always the same.
Reading Writing
open a stream open a stream
while more information while more information
read information write information
close the stream close the stream
The java.io package contains a collection of stream classes that support these
algorithms for reading and writing. These classes are divided into two class hierarchies
based on the data type (either characters or bytes) on which they operate.
However, it's often more convenient to group the classes based on their purpose rather
than on the data type they read and write. Thus, we can cross-group the streams by
whether they read from and write to data "sinks" or process the information as its being
read or written.
Data sink streams read from or write to specialized data sinks such as strings, files, or
pipes. Typically, for each reader or input stream intended to read from a specific kind of
input source, java.io contains a parallel writer or output stream that can create it. The
following table gives java.io's data sink streams.
CharArrayReader, ByteArrayInputStream,
Memory
CharArrayWriter ByteArrayOutputStream
StringReader,
StringBufferInputStream
StringWriter
PipedReader, PipedInputStream,
Pipe
PipedWriter PipedOutputStream
FileReader, FileInputStream,
File
FileWriter FileOutputStream
Note that both the character stream group and the byte stream group contain parallel pairs
of classes that operate on the same data sinks.
These are described next:
CharArrayReader and CharArrayWriter
ByteArrayInputStream and ByteArrayOutputStream
These streams are used to read from and write to memory. You create these streams on an
existing array and then use the read and write methods to read from or write to the array.
Most programs should use readers and writers to read and write information. This is
because they both can handle any character in the Unicode character set (while the byte
streams are limited to ISO-Latin-1 8-bit bytes).
Byte Streams
Programs should use the byte streams, descendants of InputStream and OutputStream,
to read and write 8-bit bytes. InputStream and OutputStream provide the API and some
implementation for input streams (streams that read 8-bit bytes) and output streams
(streams that write 8-bit bytes). These streams are typically used to read and write binary
data such as images and sounds.
As with Reader and Writer, subclasses of InputStream and OutputStream provide
specialized I/O that falls into two categories: data sink streams and processing streams.
Following Figure shows the class hierarchies for the byte streams.
Note: The two of the byte stream classes, ObjectInputStream and
ObjectOutputStream, are used for object serialization.
Also, both Reader and InputStream provide methods for marking a location in the
stream, skipping input, and resetting the current position.
Writer and OutputStream are similarly parallel.
Writer defines these methods for writing characters and arrays of characters:
int write(int c) int write(char cbuf[])
int write(char cbuf[], int offset, int length)
And OutputStream defines the same methods but for bytes:
int write(int c) int write(byte cbuf[])
int write(byte cbuf[], int offset, int length)
All the streams --readers, writers, input streams, and output streams are automatically
opened when created. You can close any stream explicitly by calling its close method.
Or the garbage collector can implicitly close it, when the object is no longer referenced.
The following Copy program uses FileReader and FileWriter to copy the contents of a
file named Griet.txt into a file called Grietagain.txt:
import java.io.*;
Here is another version of this program, CopyBytes, which uses FileInputStream and
FileOutputStream in place of FileReader and FileWriter.
import java.io.*;
in.close();
out.close();
}
}
The output Generated will same as the above. We can see this in Grietoutagain.txt
Pipe Streams
Pipes are used to channel the output from one program (or thread) into the input of
another.
Consider a class that implements various String manipulation utilities such as sorting and
reversing text. It would be nice if the output of one of these methods could be used as the
input for another so that you could string a series of method calls together to perform
some higher-order function. For example, you could reverse each word in a list, sort the
words, and then reverse each word again to create a list of rhyming words.
Without pipe streams, the program would have to store the results somewhere (such as in
a file or in memory) between each step, as shown here:
With pipe streams, the output from one method could be piped into the next, as shown in
this figure:
First, let's look at the calling sequence of the reverse and sort methods from the main
method in the RhymingWords class:
RhymingWords.java
import java.io.*;
ReverseThread.java
import java.io.*;
SortedThread.java
import java.io.*;
public class SortThread extends Thread {
private PrintWriter out = null;
private BufferedReader in = null;
The innermost call to reverse takes a FileReader opened on the file words.txt that
contains a list of words. The return value of reverse is passed to sort, whose return
value is then passed to another call to reverse.
The connection forms a pipe, as illustrated here:
reverse starts a ReverseThread that writes its output to the PipedWriter and then
returns the PipedReader to the caller. The caller then arranges for a sorting thread to read
from it. The sort method is exactly the same, except that it creates and starts a
SortThread.
FilterReader, FilterInputStream,
Filtering
FilterWriter FilterOutputStream
Concatenation SequenceInputStream
ObjectInputStream,
Object Serialization
ObjectOutputStream
DataInputStream,
Data Conversion
DataOutputStream
Notice that many times, java.io contains character streams and byte streams that
perform the same processing but for the different data type. The processing streams are
briefly described here:
BufferedReader and BufferedWriter BufferedInputStream and
BufferedOutputStream
Buffer data while reading or writing, thereby reducing the number of accesses required
on the original data source. Buffered streams are typically more efficient than similar
nonbuffered streams.
FilterReader and FilterWriter FilterInputStream and FilterOutputStream
Abstract classes, like their parents. They define the interface for filter streams, which
filter data as it's being read or written.
LineNumberReader LineNumberInputStream
Keeps track of line numbers while reading.
PushbackReader PushbackInputStream
A filter that allows characters or bytes to be “unread” from an underlying input stream.
The number of Characters or bytes to be unread can optionally be specified.
PrintWriter PrintStream
Contain convenient printing methods. These are the easiest streams to write to, so you
will often see other write able streams wrapped in one of these.
import java.io.*;
ListofFiles.java
import java.util.*;
import java.io.*;
if (!hasMoreElements())
throw new NoSuchElementException("No more files.");
else {
String nextElement = listOfFiles[current];
current++;
try {
in = new FileInputStream(nextElement);
} catch (FileNotFoundException e) {
System.err.println("ListOfFiles: Can't open " + nextElement);
}
}
return in;
}
}
After the main method creates the SequenceInputStream, it reads from it one byte at a
time. When the SequenceInputStream needs an InputStream from a new source (such
as for the first byte read or when it runs off the end of the current input stream), it calls
nextElement on the Enumeration object to get the next InputStream. ListOfFiles
creates FileInputStream objects lazily, meaning that whenever SequenceInputStream
calls nextElement, ListOfFiles opens a FileInputStream on the next filename in the
list and returns the stream. When the ListOfFiles runs out of files to read (it has no
more elements), nextElement returns null, and the call to SequenceInputStream's read
method returns -1 to indicate the end of input.
Working with Filtered Streams
The java.io package contains filtered streams which are subclasses of either
FilteredInputStream or FilteredOutputStream :
DataInputStream and DataOutputStream
BufferedInputStream and BufferedOutputStream
LineNumberInputStream
PushbackInputStream
PrintStream (this is an output stream)
This section shows you how to use filtered streams through an example that uses a
DataInputStream and a DataOutputStream. In addition, this section shows you how to
write your own filtered streams.
Using Filtered Streams
To use a filtered input or output stream, attach the filtered stream to another input or
output stream. For example, you can attach a DataInputStream to the standard input
stream as in the following code:
DataInputStream dis = new DataInputStream(System.in);
String input;
void display()
{System.out.println("Name " + s1 +"\t age + b1" + "\n height " + i1 + " \t salary" + f1);}
}
class dataoutDemo{
public static void main(String args[]) throws IOException{
DataOutputStream dos = new DataOutputStream(new FileOutputStream(args[0]));
Object Serialization
ObjectInputStream and ObjectOutputStream, are specialized streams that let you read
and write objects. Reading and writing objects is a process known as object serialization.
The key to writing an object is to represent its state in a serialized form sufficient to
reconstruct the object as it is read.
Object serialization is essential to building all but the most transient applications. You
can use object serialization in the following ways:
Remote Method Invocation (RMI) communication between objects via sockets
Lightweight persistence--the archival of an object for use in a later invocation of the same
program
Serializing Objects
Reconstructing an object from a stream requires that the object first be written to a
stream. ObjectOutputStream is a processing stream, so it must be constructed on
another stream.
If an object refers to other objects, then all of the objects that are reachable from the first
must be written at the same time so as to maintain the relationships between them. Thus
the writeObject method serializes the specified object, traverses its references to other
objects recursively, and writes them all.
ObjectOutputStream stream implements the DataOutput interface that defines many
methods for writing primitive data types, such as writeInt, writeFloat, or writeUTF.
You can use these methods to write primitive data types to an ObjectOutputStream.
The writeObject method throws a NotSerializableException if it's given an object
that is not serializable. An object is serializable only if its class implements the
Serializable interface.
// create a file oosDemo for ObjectOutputStream
import java.io.*;
class oosDemo
{
public static void main(String args[]) throws Exception
{
stud x1 = new stud("keshava rao ", (byte) 50, 15, 12000f);
stud x2 = new stud("madava rao ", (byte) 55, 25, 15000f);
stud x3 = new stud("faju ", (byte) 56, 16, 18000f);
stud x4 = new stud("sheela ",(byte) 65,17, 21000f);
ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream(args[0]));
oos.writeObject(x2);
oos.writeObject(x4);
oos.writeObject(x1);
oos.writeObject(x3);
oos.flush();
oos.close();
}
}
class Furniture
{ String label;
Furniture(String s1){label = s1;}
}
class oisDemo
{
public static void main(String args[]) throws Exception
{
stud s;
Furniture f1;
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(args[0]));
for(int i=0; i< 4; i++)
{
Object o1;
o1 = ois.readObject();
{
s = (stud) o1;
System.out.println(s.s1 + "\t" + s.b1 + "\t" + s.i1 + "\t" + s.f1);
}
}
ois.close();
}
}
Output:
C:\>java oosDemo Data.text
C:\>java oisDemo Data.text
madava rao 55 25 15000.0
sheela 65 17 21000.0
keshava rao 50 15 12000.0
Sunny 56 16 18000.0
After the file has been opened, you can use the common readXXX or writeXXX methods
to perform I/O on the file. RandomAccessFile supports the notion of a file pointer. The
file pointer indicates the current location in the file. When the file is first created, the file
pointer is 0, indicating the beginning of the file. Calls to the readXXX and writeXXX
methods adjust the file pointer by the number of bytes read or written.
In addition to the normal file I/O methods that implicitly move the file pointer when the
operation occurs, RandomAccessFile contains three methods for explicitly manipulating
the file pointer.
skipBytes : Moves the file pointer forward the specified number of bytes.
seek : Positions the file pointer just before the specified byte.
getFilePointer : Returns the current byte location of the file pointer.
if(s1.equals("~")) break;
sb = sb.replace(0,10,s1);
raf.writeUTF(s1.trim() + "\n");
}
raf.seek(21);
System.out.println("\nData you entered " );
System.out.println("\nFile Size " + raf.length() + " FP@: " + raf.getFilePointer() +
" MYFP@: " + myFilePointer );
//CheckedInputStream
import java.io.FilterInputStream;
import java.io.InputStream;
import java.io.IOException;
//CheckedOutputStream.java
import java.io.*;
public class CheckedOutputStream extends FilterOutputStream {
private Checksum cksum;
public CheckedOutputStream(OutputStream out, Checksum cksum) {
super(out);
this.cksum = cksum;
}
public void write(int b) throws IOException {
out.write(b);
cksum.update(b);
}
public void write(byte[] b) throws IOException {
out.write(b, 0, b.length);
cksum.update(b, 0, b.length);
}
public void write(byte[] b, int off, int len) throws IOException {
out.write(b, off, len);
cksum.update(b, off, len);
}
public Checksum getChecksum() {
return cksum;
}
}
//CheckedIOTest.java
import java.io.*;
public class CheckedIOTest {
public static void main(String[] args) throws IOException {
int c;
while ((c = in.read()) != -1)
out.write(c);
in.close();
out.close();
}
}
Output:
C:\>java CheckedIOTest
Input stream check sum: 736868089
Output stream check sum: 736868089
In addition to the classes and interfaces discussed in above, java.io contains the
following classes and interfaces:
File
Represents a file on the native file system. You can create a File object for a file on the
native file system and then query the object for information about that file (such as its full
pathname).
FileDescriptor
Represents a file handle (or descriptor) to an open file or an open socket. You will not
typically use this class.
StreamTokenizer
Breaks the contents of a stream into tokens. Tokens are the smallest unit recognized by a
text-parsing algorithm (such as words, symbols, and so on). A StreamTokenizer object
can be used to parse any text file. For example, you could use it to parse a Java source
file into variable names, operators, and so on, or to parse an HTML file into HTML tags.
FilenameFilter
Used by the list method in the File class to determine which files in a directory to list.
The FilenameFilter accepts or rejects files based on their names. You could use
FilenameFilter to implement simple regular expression style file search patterns such
as foo*.
Unit V
Networking
Networking Basics:
Computers running on the Internet communicate to each other using either the Transport
Control Protocol (TCP) or the User Datagram Protocol (UDP), as this diagram illustrates:
When you write Java programs that communicate over the network, you are
programming at the application layer. Typically, you don't need to concern yourself with
the TCP and UDP layers. Instead, you can use the classes in the java.net package.
These classes provide system-independent network communication. However, to decide
which Java classes your programs should use, you do need to understand how TCP and
UDP differ.
Through the classes in java.net, Java programs can use TCP or UDP to communicate
over the Internet. The URL, URLConnection, Socket, and ServerSocket classes all use
TCP to communicate over the network. The DatagramPacket, DatagramSocket, and
MulticastSocket classes are for use with UDP.
Definitions:
TCP :TCP (Transport Control Protocol) is a connection-based protocol that provides a
reliable flow of data between two computers.
UDP: UDP (User Datagram Protocol) is a protocol that sends independent packets of
data, called datagrams, from one computer to another with no guarantees about arrival.
UDP is not connection-based like TCP.
Ports : : The TCP and UDP protocols use ports to map incoming data to a particular
process running on a computer.
Generally speaking, a computer has a single physical connection to the network. All data
destined for a particular computer arrives through that connection. However, the data
may be intended for different applications running on the computer. Through the use of
ports the computer knows to which application the data is to be forwarded.
Data transmitted over the Internet is accompanied by addressing information that
identifies the computer and the port for which it is destined. The computer is identified by
its 32-bit IP address, which IP uses to deliver data to the right computer on the network.
Ports are identified by a 16-bit number, which TCP and UDP use to deliver the data to the
right application.
In connection-based communication such as TCP, a server application binds a socket to a
specific port number. This has the effect of registering the server with the system to
receive all data destined for that port. A client can then rendezvous with the server at the
server's port, as illustrated here:
In datagram-based communication such as UDP, the datagram packet contains the port
number of its destination and UDP routes the packet to the appropriate application, as
illustrated in this figure:
Port numbers range from 0 to 65,535 because ports are represented by 16-bit numbers.
The port numbers ranging from 0 - 1023 are restricted; they are reserved for use by well-
known services such as HTTP and FTP and other system services. These ports are called
well-known ports. Your applications should not attempt to bind to them.
URL: URL is an acronym for Uniform Resource Locator and is a reference (an address)
to a resource on the Internet.
URLs have two main components: the protocol needed to access the resource and the
location of the resource.
The following is an example of a URL which addresses the Java Web site hosted by Sun
Microsystems:
Note that the protocol identifier and the resource name are separated by a colon and two
forward slashes. The protocol identifier indicates the name of the protocol to be used to
fetch the resource. The example uses the Hypertext Transfer Protocol (HTTP), which is
typically used to serve up hypertext documents. HTTP is just one of many different
protocols used to access different types of resources on the net. Other protocols include
File Transfer Protocol (FTP), Gopher, File, and News.
The resource name is the complete address to the resource. The format of the resource
name depends entirely on the protocol used, but for many protocols, including HTTP, the
resource name contains one or more of the components listed in the following table:
Host Name The name of the machine on which the resource lives.
Port
The port number to which to connect (typically optional).
Number
Parsing a URL :
import java.net.*;
import java.io.*;
class urlDemo
{
public static void main(String[] args)
{
URL u1 = null;
try
{
u1 = new URL("http://java.sun.com:80/tutorial/intro.html#DOWNLOADING");
dispDetails("Sun ", u1);
u1= new URL("http://192.1.2.200/");
dispDetails("Griet ", u1);
}
catch(MalformedURLException e)
{ System.out.println("MalformedURLException " +e.getMessage());}
}
static void dispDetails(String s1, URL u1)
{
System.out.println("\nDetails of = " +s1);
System.out.println("URL toString()= "+ u1);
System.out.println("Protocol = "+ u1.getProtocol());
System.out.println("Host = "+ u1.getHost());
System.out.println("filename = "+ u1.getFile());
System.out.println("Port = "+ u1.getPort());
System.out.println("Ref = "+ u1.getRef());
}
}
OUTPUT:
Java programs can read from a URL using the openStream() method.
Using URL's openStream() method to get a stream from which you can read the contents
of the URL. The openStream() method returns a java.io.InputStream object, so
reading from a URL is as easy as reading from an input stream.
The following small Java program uses openStream() to get an input stream on the URL
file:// /d:/lal/lal/kk
import java.net.*;
import java.io.*;
class urlReadTest{
public static void main(String[] args){
String inputLine;
URL u1 = null;
try {
u1 = new URL("file:///d:/lal/lal/features.txt");
DataInputStream dis = new DataInputStream(u1.openStream());
while((inputLine = dis.readLine()) !=null)
System.out.println(inputLine);
dis.close();
}catch(MalformedURLException e)
{ System.out.println("MalformedURLException " +e.getMessage());}
catch(IOException ioe)
{ System.out.println("IOException : "+ioe.getMessage());}
}
}
OUTPUT:
The following small Java program uses openStream() to get an input stream on the URL
http://www.yahoo.com/. It then opens a BufferedReader on the input stream and
reads from the BufferedReader thereby reading from the URL. Everything read is
copied to the standard output stream:
import java.net.*;
import java.io.*;
String inputLine;
in.close();
}
}
When you run the program, you should see, scrolling by in your command window, the
HTML commands and textual content from the HTML file located at
http://www.yahoo.com/. Alternatively, the program might hang or you might see an
exception stack trace. If either of the latter two events occurs, you may have to set the
proxy host so that the program can find the Yahoo server.
Connecting to a URL
The openConnection() method returns a URLConnection object that you can use for
more general communications with the URL, such as reading from it, writing to it, or
querying it for content and other information. When you connect to a URL, you are
initializing a communication link between your Java program and the URL over the
network.
For example, you can open a connection to the Yahoo site with the following code:
try {
URL yahoo = new URL("http://www.yahoo.com/");
URLConnection yahooConnection = yahoo.openConnection();
Sockets :
Definition: A socket is one endpoint of a two-way communication link between two
programs running on the network. A socket is bound to a port number so that the TCP
layer can identify the application that data is destined to be sent.
The client and server can now communicate by writing to or reading from their sockets.
On the server-side: The server runs on a specific computer and has a socket that is
bound to a specific port number. The server just waits, listening to the socket for a client
to make a connection request.
On the client-side: The client knows the hostname of the machine on which the server is
running and the port number to which the server is connected. To make a connection
request, the client tries to rendezvous with the server on the server's machine and port.
If everything goes well, the server accepts the connection. Upon acceptance, the server
gets a new socket bound to a different port. It needs a new socket (and consequently a
different port number) so that it can continue to listen to the original socket for
connection requests while tending to the needs of the connected client.
On the client side, if the connection is accepted, a socket is successfully created and the
client can use the socket to communicate with the server. Note that the socket on the
client side is not bound to the port number used to rendezvous with the server. Rather, the
client is assigned a port number local to the machine on which the client is running.
The java.net package in the Java platform provides a class, Socket, that implements
one side of a two-way connection between your Java program and another program on
the network. The Socket class sits on top of a platform-dependent implementation,
hiding the details of any particular system from your Java program. By using the
java.net.Socket class instead of relying on native code, your Java programs can
communicate over the network in a platform-independent fashion.
If you are trying to connect to the Web, the URL class and related classes
(URLConnection, URLEncoder) are probably more appropriate than the socket classes. In
fact, URLs are a relatively high-level connection to the Web and use sockets as part of
the underlying implementation.
Let's look at a simple example that illustrates how a program can establish a connection
to a server program using the Socket class and then, how the client can receive data from
the server through the socket.
1. Open a socket.
2. Open an input stream and output stream to the socket.
3. Read from and write to the stream according to the server's protocol.
4. Close the streams.
5. Close the socket.
Only step 3 differs from client to client, depending on the server. The other steps remain
largely the same.
Steps to write a server program
1. Gets the socket's input and output stream and opens readers and writers on them.
2. Initiates communication with the client by writing to the socket (shown in bold).
3. Communicates with the client by reading from and writing to the socket (the
while loop).
The example program implements a client, ClientSoc, that connects to the ServerSoc.
On the Server side the ServerSoc program accepts a file name and displays the contents
of the file on the client screen.
ClientSoc.java
import java.net.*;
import java.io.*;
class ClientSoc{
public static void main(String[] args)throws IOException {
Socket sc = null;
BufferedReader br = null;
try{
sc = new Socket(InetAddress.getLocalHost(),95);
br = new BufferedReader(new InputStreamReader(sc.getInputStream()));
}catch(Exception e){}
String input;
while((input = br.readLine())!=null)
System.out.println(input);
br.close();
sc.close();
}
}
ServerSoc.java
import java.net.*;
import java.io.*;
class ServerSoc{
public static void main(String[] args) throws IOException
{
ServerSocket sc = null;
try{
sc = new ServerSocket(95);
}catch(Exception e){e.printStackTrace();}
Socket cs = null;
try{
cs = sc.accept();
System.out.println("Connected to " + cs);
}catch(Exception e){ }
if(f.exists()){
BufferedReader b = new BufferedReader(new FileReader(s));
String input;
while((input = b.readLine())!=null) {
pw.write(input);
pw.flush();
}
b.close();
}
pw.close();
cs.close();
}
}
OUTPUT:
Example 2: The following program waits for the client to connect, and once the client
connects it gives the InetAddress of the client using Sockets.
Socket Client
import java.net.*;
import java.io.*;
class SocketClient{
public static void main(String[] args)
{
try{
Socket s = new Socket("System16",1234);
InputStream is = s.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
OutputStream os = s.getOutputStream();
PrintWriter pw = new PrintWriter(os);
pw.println(args[0]);
pw.flush();
String str = null;
while(!(str=br.readLine()).equals("quit"))
System.out.println(str);
}catch(Exception e){e.printStackTrace();}
}
}
Socket Server
import java.io.*;
import java.net.*;
public class SocketServer
{
public static void main(String args[])
{
try{
ServerSocket ss = new ServerSocket(1234,10);
while(true)
{
System.out.println("waiting for client requests");
Socket s = ss.accept();
InputStream is = s.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
OutputStream os = s.getOutputStream();
String str = br.readLine();
System.out.println(str);
PrintWriter pw = new PrintWriter(os);
pw.println("Hello " +str);
pw.println("U called from " + s.getInetAddress());
pw.println("Have a nice day\n");
pw.println("quit");
pw.flush();
}
}catch(Exception e){ e.printStackTrace();}
}
}
OUTPUT:
Datagrams
The example featured in this section consists of two applications: a client and a server.
Example:
The sender application is invoked with three command-line arguments. These are the
address and port of the server and a word. The word is sent to the server in a datagram
packet.
The receiver application is invoked with one command-line argument. This is the
software port to which it listens for incoming packets. When receives a packet, it
displays the enclosed word.
DGReceiver.java
import java.net.*;
class DGReceiver{
private final static int Bufsize=20;
public static void main(String args[])
{
try{
int port = Integer.parseInt(args[0]);
DatagramSocket ds = new DatagramSocket(port);
byte b[] = new byte[Bufsize];
while(true)
{
DatagramPacket dp = new DatagramPacket(b,b.length);
ds.receive(dp);
String str = new String(dp.getData());
System.out.println(str);
}
}catch(Exception e){e.printStackTrace();}
}
}
DGSender.java
import java.net.*;
class DGSender{
public static void main (String args[])
{ try{
InetAddress ia = InetAddress.getByName(aargs[0]);
int port = Integer.parseInt(args[1]);
DatagramSocket ds = new DatagramSocket();
byte b[] = args[2].getBytes();
DatagramPacket dp = new DatagramPacket(b,b.length,ia,port);
ds.send(dp);
}
catch(Exception e){e.printStackTrace();}
}
}
Example 3: The following program waits for the client to connect, and once the client
connects it gives displays the content typed on the server side to client.
Server Datagram
import java.net.*;
import java.io.*;
class ServerDg{
public static DatagramSocket dc;
System.out.println("Server is waiting");
InetAddress ia = InetAddress.getByName("System16");
while(true)
{ String str = br.readLine();
if((str == null)||str.equals("end")) break;
b = str.getBytes();
dc.send(new DatagramPacket(b,str.length(),ia,cp));
}
}
}
Client Datagram
import java.net.*;
import java.io.*;
class ClientDg{
public static DatagramSocket dc;
public static byte b[] = new byte[1024];
public static int cp=789,sp=790;
while(true)
{ DatagramPacket p = new DatagramPacket(b,b.length);
dc.receive(p);
String input = new String(p.getData(),0,p.getLength());
System.out.println(input);
}
}
}
OUTPUT:
EXERCISES
OOP & Packages
1. Writea program to depicit overloading, overriding.
3. Write a program to enter username, department, university, state and pincode and
store the information in the text areas. The state should be selected from the list
box.
5. Assume that a bank maintain two kinds of accounts for its customers. One called
savings account and the other current account. The saving account provides
compound and withdrawal facilities but no chequebook facility. The current
account provides chequebook facility but no interest. Current account holders
should also maintain a minimum balance and if the balance falls below this level,
a service charge is imposed. Create a class account that stores customer name,
account number and type of account. From this derive the classes’ current account
and savings account to make them more specific to their requirements. Include the
necessary methods in order to achieve the following tasks.
i. Accept deposit from the customer and update the balance
ii. Display the balance iii. Compute and deposit interest.
iv. Permit withdrawal and update the balance.
v. Check for the minimum balance, impose penalty if necessary and update the
balance.
6. Declare an interface called function that has a method named evaluator takes an
arbitrary int values as a parameter and returns an int value.
A. Create a class half that implements function. Make the implementation of the
method evaluate() return the value obtained by dividing the int argument by 2.
B. Create a method that takes an arbitrary array of int values as parameter and an
array that has the same length, but the value of an element in the array passed as
parameter.
Let the implementation of this method create an instance of half and use this
instance to calculate the values in the array to be returned.
7. Rewrite the method that operated on arrays from the above example. The method
should now take a function reference as an argument and use this instead of
creating an instance of half. Create a class called print that implements function,
and has an implementation that simply prints the int value gives as an argument
and returns the value. Now create a program that creates an array of the int values
from 1 to 10 and does the following:
a. Print the array using an instance of the print class and the method described
above.
b. Halves the values in the array and prints the values again, using the half and
print classes and the method describe above.
8. Define an interface reservation with one method void reserve. Use this for
overriding in class cinema and another class hotel in the main program. Declare a
reference variable of type interface and then call the reserve method from the
reference variable. Observe the result.
9. Create an inheritance hierarchy of reptiles snake, crocodile etc. In the base class,
provide methods that are common to all reptiles and override these i.e. the derived
classes to perform different behavior depending on the specific type of reptiles.
10. Create a package called wizard, which contains two other packages. Pandorasbox
and spells. The package Pandorasbox has a class called clown that implements an
interface Magic found in the same package. In addition the package Pandorasbox
has class called crafts and a sub package called articfacts containing a class called
ailment. The package spells has two classes: baldness and crafts. The class
baldness is a subclass of class ailment found in the sub package articfacts in the
package Pandorasbox.
Exceptions:
1. Write a program that creates 10 accounts and transfers funds among the accounts.
If a transaction amount is negative, the program raises a negative- amount
exception. If the accounts balance is less than the requested transaction amount,
an Insufficient – funds exception is raised.
2. Write a program that generates Invalidmarks exception whenever marks entered is
<0 and >100
3. Write a program that generates a custom exception if any of its command line
arguments are negative.
4. Write a program to find no.of non-numeric values in the command line
arguments. In case of numeric values compute the sum of all numbers.
4. Threads:
1. Create three classes: storage, counter and printer. The storage class should store
an integer. The counter class should create a thread that starts counting from
0(0,1,2,……) and stores each value in the storage class. The printer class should
create a thread that keeps reading the value in the storage class and printing it.
A. Create a program that creates an instance of the storage class and sets up a
counter and printer object to operate on it.
B. Modify the above exercise to ensure that each number is printed exactly
once, by adding suitable synchronization.
2. Write a program to alaunch 100 threads. Each thread is to add 1 to a variable sum.
The variable sum is zero initially. You need to pass sum by reference to each
thread. In order to pass it by reference, you need to define an Integer wrapper
object ot hold sum. Run the program with and without synchronization to see its
effect.
1. Write a program that reads text from a source using one encoding, and writes the
text to a destination using another encoding. The program should have four
optional arguments.
A. First argument, if present, should specify the encoding, of the source. The
default source encoding should be “8859-1”.
B. Second argument, if present, should specify the encoding of the
destination. The default destination encoding should be “UTF8”.
2. Write a program in java to concatenate two files.
3. Write a program in java to read a file and display no.of words, characters, and
lines in the file.
4. Write a program in java to copy one file to another file. Also handle all the
possible exceptions that can be raised in the process.
5. Write a program in java to use filter streams.
AWT:
9. Write a program to
A. Draw Rounded rectangle. B. Half filled rectangle
11. Write a program that shows some text in a text area. Make the size of the frame
containing the text area by 200 pixels. The text area should not have any
scrollbars and the text should not be editable. Make the text appear as yellow
lettering on black background.
12. Write a program that displays a button at the top of a framed window. The button
should cover the whole width of the window, but should be given its preferred
height whenever possible. The rest of the area of the window should be covered
by the text areas placed side by side, sharing the remaining area of the window
equally between them.
13. Write a program that displays a small button in each corner of a framed window.
The buttons should have their preferred size whenever possible. Leave the
remainder of the window black.
14. Write a program to display student exam scores the program prompts the user to
enter the user’s last name and password in a dialog box, upon receiving the
correct user name and the password. The program displays the student’s full name
and the exam score.
15. Create user interface that performs arithmetic. The interface contains labels and
text fields for Number1, Number2 and result. The result displays the result of the
Arithmetic operation between Number1, Number2. The program should have
four buttons labeled add, subtract, multiply and Divide. The program will also
create a menu to perform the same operation. The user can choose operations
either from menu or from buttons.
16. Write a program to add a check box group to select background colors.
17. Write an user interface to manage student information in a file. (inserting,
modifying, etc.)
Applet:
1. Create an applet that takes a string within the applet area. Make the applet provide
information about itself and its parameters using the standard facilities available
for applets.
2. Create an HTML document confirming to any HTML specification of your choice
to display the applet created in the string “An applet a day keeps the browser
awake”.
3. Write a program to open, read and display the file contents in a text area in an
applet.
4. Write a program to get character input from the keyboard and to put the character
where the mouse points.
5. Write an applet to accept a string and check whether it is a palindrome or not.
Networking:
1. Write a simple one to one chatting program using Sockets.
2. Modify the above program for one to many chatting.
3. Write a program that test’s whether a particular port is already in use in a
particular machine.
4. Use sockets to send objects from a client to a server, test the program by
reconstructing the object on server side.