Sunteți pe pagina 1din 135

JAVA PROGRAMMING

(Laboratory manual, Examples and Exercises)

for
MCA Year

Y.Sri Lalitha Associate Professor


N.V.Ganapathi Raju Associate Professor

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.

The Java API is grouped into libraries (packages) of related components.

The "Hello World" Application


Follow the given steps to create a standalone Java application.

1. Create a Java Source File


Using a text editor, create a file named HelloWorldApp.java with the following Java
code:
/** The HelloWorldApp class implements an application that simply displays "Hello
World!" to the standard output. */

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.

At command prompt type, javac HelloWorldApp.java


If the compilation succeeds, the compiler creates a file named HelloWorldApp.class in
the same directory (folder) as the Java source file (HelloWorldApp.java). This class file
contains Java bytecode, which is a platform-independent code interpreted by the Java
runtime system.

3. Run the Application


Run the program using the Java interpreter.
At command Prompt type, C:\>java HelloWorldApp

OUTPUT:

Command Line Arguments


Java application can accept any number of arguments from the command line
C:\> java Sort friends.txt
In the Java language, when you invoke an application, the runtime system passes the
command-line arguments to the application's main method via an array of Strings. Each
String in the array contains one of the command line arguments. In the previous example,
the command-line arguments passed to the Sort application are an array that contains a
single string: "friends.txt".

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.

Program on Array Manipulation


The following program uses two arrays and copies one array to another.
class ArrCopy
{
public static void main(String []r)
{
int arr1[]={1,2,3,4};
int arr2[]={22,33,44,55,66,77,44};
System.out.println("Contents of Array one & two before copy ");
for(int i=0;i<arr1.length;i++)
System.out.print(" " + arr1[i]);
System.out.println(" ");
for(int i=0;i<arr2.length;i++)
System.out.print(" " + arr2[i]);
System.out.println(" ");
//Three elements from position 1 of arr1[] are copied to arr2[] from position 2
System.arraycopy(arr1,1,arr2,2,3);
System.out.println("Contents of Array two after copy ");
for(int i=0;i<arr2.length;i++)
System.out.print(" " + arr2[i]);
}
}

OUTPUT:

Program on Labelled loops:

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.

Super class reference variable Vs Subclass reference Variable

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 myexception extends Exception{


int value;
myexception(int a){
value = a;
System.out.println("The basic pay less than 3000 is not allowed in our organisation");
}
}

class Throwsdemo{
String name;
int basicpay;
float hra, gross;

Throwsdemo(String s, int bp){


name = s;
basicpay = bp;
}

void compute() throws myexception{


if(basicpay < 3000)
throw new myexception(basicpay);
hra = basicpay * 20/100;
gross = basicpay + hra;
}

void display(){
System.out.println("Name : " + name);
System.out.println("Basic: " + basicpay);
System.out.println("Hra : " + hra);
System.out.println("Gross: " + gross);
}

public static void main(String args[]){


Throwsdemo x,y;
x = new Throwsdemo("sai",7000);
y = new Throwsdemo("lalitha",2000);
try {
x.compute();
x.display();
y.compute();
y.display();
} catch(myexception e){ System.out.println("caught my exception");}
}
}

OUTPUT:
Multi Threading

Definition: A thread is a single sequential flow of control within a program. A


thread is considered as lightweight process because it runs within the context of a
full-blown program and takes advantage of the resources allocated for that
program and the program's environment. When multiple threads are there within a
single program then it is called Multithreading.

The following figure shows the concept of thread


Single thread Multiple threads in a single program

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

Subclassing Thread and Overriding run()


The SimpleThread class Example:
public class SimpleThread extends Thread {
public SimpleThread(String str) {
super(str);
}
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(i + " " + getName());
try {
sleep((long)(Math.random() * 1000));
} catch (InterruptedException e) {}
}
System.out.println("DONE! " + getName());
}}
The TwoThreadsTest class provides a main method that creates two SimpleThread
threads: one is named "Simla" and the other is named "Goa". (If you can't decide on
where to go for vacation you can use this program to help you decide--go to the place
whose thread prints "DONE!" first.)
public class TwoThreadsTest {
public static void main (String[] args) {
new SimpleThread("Simla").start();
new SimpleThread("Goa").start();
}
}
OUTPUT:

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;

public class Clock extends Applet implements Runnable {


private Thread clockThread = null;
public void start() {
if (clockThread == null) {
clockThread = new Thread(this, "Clock");
clockThread.start();
}
}
public void run(){
Thread myThread = Thread.currentThread()
while (clockThread == myThread){
repaint();
try {
Thread.sleep(1000);
} catch (InterruptedException e){
// the VM doesn't want us to sleep anymore,
// so get back to work
}
}
}
public void paint(Graphics g) {
// get the time and convert it to a date
Calendar cal = Calendar.getInstance();
Date date = cal.getTime();
// format it and display it
DateFormat dateFormatter = DateFormat.getTimeInstance();
g.drawString(dateFormatter.format(date), 5, 10);
}
// overrides Applet's stop method, not Thread's
public void stop() {
clockThread = null;
}
}

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.

Making a Thread Not Runnable


A thread becomes Not Runnable when one of these events occurs:
Its sleep method is invoked.
The thread calls the wait method to wait for a specific condition to be satisifed.
The thread is blocking on I/O

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 generates an integer between 0 and 9 (inclusive), stores it in a CubbyHole


object, and prints the generated number. To make the synchronization problem more
interesting, the Producer sleeps for a random amount of time between 0 and 100
milliseconds before repeating the number generating cycle:
public class CubbyHole {
private int contents;
private boolean available = false;

public synchronized int get() {


while (available == false) {
try {
wait();
} catch (InterruptedException e) { }
}
available = false;
notifyAll();
return contents;
}
public synchronized void put(int value) {
while (available == true) {
try {
wait();
} catch (InterruptedException e) { }
}
contents = value;
available = true;
notifyAll();
}
}

public class Producer extends Thread {


private CubbyHole cubbyhole;
private int number;

public Producer(CubbyHole c, int number) {


cubbyhole = c;
this.number = number;
}

public void run() {


for (int i = 0; i < 10; i++) {
cubbyhole.put(i);
System.out.println("Producer #" + this.number
+ " put: " + i);
try {
sleep((int)(Math.random() * 100));
} catch (InterruptedException e) { }
}
}
}
The Consumer, being ravenous, consumes all integers from the CubbyHole (the exact
same object into which the Producer put the integers in the first place) as quickly as they
become available.

public class Consumer extends Thread {


private CubbyHole cubbyhole;
private int number;
public Consumer(CubbyHole c, int number) {
cubbyhole = c;
this.number = number;
}

public void run() {


int value = 0;
for (int i = 0; i < 10; i++) {
value = cubbyhole.get();
System.out.println("Consumer #" + this.number
+ " got: " + value);
}
}
}

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.

public class ProducerConsumerTest {


public static void main(String[] args) {
CubbyHole c = new CubbyHole();
Producer p1 = new Producer(c, 1);
Consumer c1 = new Consumer(c, 1);
p1.start();
c1.start();
}
}
The Output
Here's the output of ProducerConsumerTest.
Producer #1 put: 0
Consumer #1 got: 0
Producer #1 put: 1
Consumer #1 got: 1
Producer #1 put: 2
Consumer #1 got: 2
Producer #1 put: 3
Consumer #1 got: 3
Producer #1 put: 4
Consumer #1 got: 4
Producer #1 put: 5
Consumer #1 got: 5
Producer #1 put: 6
Consumer #1 got: 6
Producer #1 put: 7
Consumer #1 got: 7
Producer #1 put: 8
Consumer #1 got: 8
Producer #1 put: 9
Consumer #1 got: 9

Creating and Using Packages

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.

Accessing Package Members


Only public package members are accessible outside the package in which they are
defined. To use a public package member from outside its package, you must either
refer to the member by its
1. long (disambiguated) name,
2. import the package member, or
3. import the member's entire package.

Each is appropriate for different situations, as explained in the following sections.

1. Referring to a Package Member by Name


You can refer to classes and interfaces by name specified in their declarations, if the
code you are writing is in the same package as that member or if the member's package
has been imported.
However, if you are trying to use a member from a different package and that package
has not been imported, then you must use the member's long name, which includes the
package name. This is the long name for the Rectangle class declared in the graphics
package in the previous example:
graphics.Circle
You could use this long name to create an instance of graphics.Rectangle:
graphics.Circle myCir = new graphics.Circle();

2. Importing a Package Member


To import a specific member into the current file, put an import statement at the
beginning of your file before any class or interface definitions (but after the package
statement, if there is one).
import graphics.Circle;
Now you can refer to the Circle class by its short name:
Circle myCircle = new Circle();

3. Importing an Entire Package


To import all of the classes and interfaces contained in a particular package, use the
import statement with the asterisk * wildcard character:
import graphics.*;
The asterisk in the import statement can be used only to specify all of the classes within a
package, as shown here. With the import statement, you can import only a single package
member or an entire package.

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> javac –d . circle.java


D:\lal> javac –d . rect.java
D:\lal> javac –d . Poly.java
D:\lal> move *.java temp

D:\lal>dir

Volume in drive D is DISK1_VOL2


Volume Serial Number is 6BAF-ECBC
Directory of D:\lal

. <DIR> 11-10-02 8:57a .


.. <DIR> 11-10-02 8:57a ..
TEMP <DIR> 11-10-02 9:13a temp
GEOMETRY <DIR> 11-10-02 9:02a geometry
0 file(s) 0 bytes
4 dir(s) 2,965,553,152 bytes free

D:\lal>dir geometry

Volume in drive D is DISK1_VOL2


Volume Serial Number is 6BAF-ECBC
Directory of D:\lal\geometry

. <DIR> 11-10-02 9:02a .


.. <DIR> 11-10-02 9:02a ..
CIRCLE~1 CLA 388 11-10-02 9:05a circle.class
OVAL~1 CLA 386 11-10-02 9:05a oval.class
POLYGON <DIR> 11-10-02 9:16a polygon
2 file(s) 774 bytes
3 dir(s) 2,965,553,152 bytes free

D:\lal>dir geometry\polygon

Volume in drive D is DISK1_VOL2


Volume Serial Number is 6BAF-ECBC
Directory of D:\lal\geometry\polygon

. <DIR> 11-10-02 9:16a .


.. <DIR> 11-10-02 9:16a ..
POLY~1 CLA 374 11-10-02 9:16a Poly.class
RECT~1 CLA 376 11-10-02 9:36a rect.class
2 file(s) 750 bytes
2 dir(s) 2,965,553,152 bytes free

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

The package java.awt provides the primary facilities of the AWT:


1. Managing the layout of components within container objects.
2. Support for event handling that is essential for user interaction in GUI-based
systems.
3. Rendering graphics in GUI components using color, fonts, images and polygons.

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:

FlowLayout : Lays out the components in row-major order: in rows growing


from left to right, and rows placed top to bottom in the container. This is the default
layout manager for the panel and Applet classes. It is a default layout for an Applet.

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.

BorderLayout : Up to five components can be placed in a container in locations


specified by the following directions: north, south, west, east and center. This is the
default layout manager for window and its subclasses.

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

public static void main(String args[])


{
flAsmd sd = new flAsmd();
}
}

OUTPUT:
Note : This output is obtained after implementing Action Listeners.

2. An Example of GridLayout
import java.awt.*;
import java.awt.event.*;

public class glAsmd extends Frame{


glAsmd(){
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 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:

Note: This output is obtained after implementing Action Listeners.


3. An Example of BorderLayout
import java.awt.*;
import java.applet.*;

//<applet code=button width=200 height=200></applet>

public class button extends Applet{


Button b1,b2,b3,b4,b5;
public void init(){
b1 = new Button("North");
b2 = new Button("West");
b3 = new Button("South");
b4 = new Button("East");
b5 = new Button("Center");

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:

4. An Example of CardLayout with implementation of ActionListener.


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

public class CrdLytDemo extends Frame implements ActionListener{


List plist, slist, mlist;
Button fb, pb, nb, lb;
Panel sp, bp;
CardLayout cl;
CrdLytDemo(){
setTitle("Hyderabad");
cl = new CardLayout();
plist = new List(4); slist = new List(4); mlist = new List(4);
sp = new Panel(); bp = new Panel();
plist.setBackground(Color.red);
plist.setForeground(Color.yellow);
plist.setFont(new Font("Times New Roman", Font.BOLD, 14));
plist.add("Public Gardens");
plist.add("Zoo Park");
plist.add("Indira Park");
plist.add("Sanjivayya Park");
plist.add("Lumbini Park");
plist.add("Chiran Gardens");
plist.add("Ocean Park");

mlist.setFont(new Font("Arial", Font.ITALIC, 14));


mlist.setBackground(new Color(180,180,240));
mlist.setForeground(Color.green);
mlist.add("Charminar");
mlist.add("Qutumbminar");
mlist.add("Golkonda");
mlist.add("Buddha Statue");
mlist.add("Falaknama");

slist.setFont(new Font("Century", Font.BOLD|Font.ITALIC, 14));


slist.setBackground(Color.blue);
slist.setForeground(Color.green);
slist.add("Tank Bund");
slist.add("Birla Temple ");
slist.add("Birla Planetorium");
slist.add("Ramoji Film City");
slist.add("Salarjung Museum");
slist.add("Birla Science Museum");

sp.setLayout(cl);
// adding lists to panel sp
sp.add("a",plist);
sp.add("b",slist);
sp.add("c",mlist);

fb = new Button("First"); pb = new Button("Previous");


nb = new Button("Next"); lb = new Button("Last");

bp.add(fb); bp.add(pb); bp.add(nb); bp.add(lb); //adding buttons to panel bp

fb.addActionListener(this); pb.addActionListener(this);
nb.addActionListener(this); lb.addActionListener(this);

add(sp,"North"); add(bp,"South");
addWindowListener(new w());
}

public void actionPerformed(ActionEvent e)


{
String Str = e.getActionCommand();
if(Str.equals("First"))
cl.first(sp);
else if(Str.equals("Next"))
cl.next(sp);
else if(Str.equals("Last"))
cl.last(sp);
else if(Str.equals("Previous"))
cl.previous(sp);
}

public static void main(String args[])


{
CrdLytDemo cld = new CrdLytDemo();
cld.setSize(300,300);
cld.setVisible(true);
}
}

class w extends WindowAdapter{


public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}

OUTPUT:

Note : In the output the other lists items are hidden.

5. An example of Grid bag layout with applets


//<applet code=Gblay width=200 height=200></applet>
import java.awt.*;
import java.applet.*;
public class Gblay extends Applet
{
GridBagLayout gbl=new GridBagLayout();
GridBagConstraints gbc=new GridBagConstraints();
public void init()
{
setLayout(gbl);
gbc.fill=GridBagConstraints.BOTH;
gbc.insets=new Insets(5,5,5,5);
gbc.weightx=1.0;
gbc.weighty=1.0;

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:

2. GUI Control Components:


GUI control components are the primary elements of a graphical user interface that
enable interaction with the user. They are all concrete sub classes of the Component
Object
class.
Font Layout
AWT Event Font Color Graphics Component
Metrics Manager

GUI Component Hierarchy


Text Checkbox
Container Button Label List Choice Checkbox
Component Group

Panel Text Field

Applet Text Area

Window

Frame

Dialog

The following three steps are essential in making use of a GUI control component:
Fle Dialog

1. A GUI control component is created by calling the appropriate constructor.


2. The GUI control component is added to a container using a layout manager.
3. Listeners are registered with the GUI component, so that they can receive events
when these occur. GUI components generate particular events in response to user
actions.

GUI Control components :


Button, Canvas, Checkbox, Choice, Label, List, Scrollbar, TextField and TextArea.

Button A button with a textual label, designed to invoke action when


pushed.
Canvas A generic component for drawing and designing new GUI
components.
Checkbox A checkbox with a textual label that can be toggled on and off.
Checkboxes can be grouped together to represent radio buttons.
Choice A component that provides a pop-up menu of choices. Only
the current choice is visible in the Choice Component
Label A label is a component that displays a single line of read-only,
non-selectable text.
List A component that defines a scrollbar list of text items.
Scrollbar A slider to denote a position or a value.
TextField A component that implements a single line of optionally
editable text.
TextArea A component that implements multiple lines of optionally
editable text.

Overview of Event Handling:


GUI applications are event-driven. User interaction with the GUI results in events being
generated to inform the application of user actions. Clicking a button, closing a window,
or hitting a key results in an appropriate event being sent to the application. Since the
user actions can take place in any arbitrary order, the events also occur in arbitrary order
and the application must be able to handle them whey they occur.

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.

AWT Event Heirarchy

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.

Examples on various GUI control components with event handling.

1. Button with ActionListener interface.


import java.awt.*;
import java.awt.event.*;
class ButFrame extends Frame implements WindowListener, ActionListener{
Button b;
ButFrame(){
b = new Button("Click to Change the Color");
setLayout(new FlowLayout());
add(b);
b.addActionListener(this);
addWindowListener(this);
}
public static void main(String args[])
{
ButFrame bf = new ButFrame();
bf.setSize(200,200);
bf.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{Color b =getBackground();
if (b!=Color.blue)
setBackground(Color.blue);
else
setBackground(Color.red);
}
public void windowOpened(WindowEvent we){}
public void windowClosed(WindowEvent we){}
public void windowIconified(WindowEvent we){}
public void windowDeiconified(WindowEvent we){}
public void windowActivated(WindowEvent we){}
public void windowDeactivated(WindowEvent we){}
public void windowClosing(WindowEvent we){System.exit(0);}
}

OUTPUT:
2. An Example on CheckGroup using Applet.
import java.awt.*;
import java.applet.*;
//<applet code = ChGrp width=300 height=300></applet>

public class ChGrp extends Applet {


public void init(){
CheckboxGroup p = new CheckboxGroup();
Checkbox FC = new Checkbox("First Class",p,false);
Checkbox SC = new Checkbox("Sleeper Coach");
Checkbox GC = new Checkbox("General Coach",false);
add(FC);
add(SC);
add(GC);

SC.setCheckboxGroup(p);
SC.setState(true);
GC.setCheckboxGroup(p);
}
}

OUTPUT:
3. An Example of Canvas.
import java.awt.*;
import java.applet.*;

//<applet code=CanFrame width=300 height=300></applet>

public class CanFrame extends Applet{


public void init(){
DrReg r = new DrReg();
add(r);
}
}
class DrReg extends Canvas{
public DrReg(){setSize(200,200);}

public void paint(Graphics g)


{
g.setColor(Color.pink);
g.drawRect(0,0,40,60);
g.setColor(Color.blue);
g.drawString("sai", 10,25);
}
}
OUTPUT:

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

String[] fruit = {"Mango", "Apple", "Oranage", "Banana", "PineApple"};


fruitList = new List(fruit.length-1,false);
b1 = new Button("add");
lb1 = new Label("Text to add to the List");
lb2 = new Label("Text from the List");
lb3 = new Label("List Count");
lb4 = new Label("List Index");
tf1 = new TextField(20);
tf2 = new TextField(20);
tf3 = new TextField(20);
tf4 = new TextField(20);

for(int i=0; i<fruit.length; i++)


fruitList.add(fruit[i]);

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

public void actionPerformed(ActionEvent e)


{
if (e.getActionCommand() == b1.getLabel().trim())
fruitList.add(tf1.getText());
else
tf2.setText(fruitList.getSelectedItem()+ " is selected");
repaint();
}

public void itemStateChanged(ItemEvent ie)


{
tf1.setText("");
tf2.setText("");
tf3.setText("");
tf4.setText("");
tf3.setText(String.valueOf(fruitList.getItemCount()));
tf4.setText(String.valueOf(fruitList.getSelectedIndex()));
}
}
OUTPUT:

5. An Example on TextField and TextArea

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

public void actionPerformed(ActionEvent ae)


{
prevText = ta.getText() + "\n" ;
tf.setText(" ");}

public static void main(String args[])


{
TextEventEx obj = new TextEventEx();
}
}

class MyWinAdapt extends WindowAdapter{


public void windowClosing(WindowEvent w)
{
System.exit(1);
}
}

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

class ScrbarHandler implements AdjustmentListener


{
//Scrbar sc;
//ScrbarHandler(Scrbar s){ sc = s;}
public void adjustmentValueChanged(AdjustmentEvent e)
{
// sc.
tf.setText(e.getValue() + " ");
repaint();
}
}
}
//<applet code = Scrbar width =200 height = 300></applet>

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

Menu submenu=new Menu("Submenu");


MenuShortcut sc1=new MenuShortcut(79);
MenuShortcut sc2=new MenuShortcut('S');
MenuShortcut sc3=new MenuShortcut(77);
MenuItem open=new MenuItem("Open",sc1);

MenuItem save=new MenuItem("Save",sc2);


MenuItem close=new MenuItem("Close");
MenuItem exit=new MenuItem("Exit");
MenuItem cut=new MenuItem("Cut");
MenuItem copy=new MenuItem("cOpy");
MenuItem paste=new MenuItem("Paste");

CheckboxMenuItem ci=new CheckboxMenuItem();


MenuItem i1=new MenuItem("Item 1");
MenuItem i2=new MenuItem("Item 2");
MenuItem i3=new MenuItem("Item 3");

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.*;

class METest extends Frame implements MouseListener, MouseMotionListener{


String msg;
METest() {
msg = " ";
setSize(300,300);
setVisible(true);
addMouseListener(this);
addMouseMotionListener(this);
addWindowListener(new W());
}
public void mouseClicked(MouseEvent e) {
setBackground(Color.cyan);
msg = "clicked";
repaint();
}
public void mouseEntered(MouseEvent e) {
setBackground(Color.blue);
msg = "entered";
repaint();
}
public void mouseExited(MouseEvent e) {
setBackground(Color.red);
msg = "exited";
repaint();
}
public void mousePressed(MouseEvent e) {
setBackground(Color.yellow);
msg = "pressed";
repaint();
}
public void mouseReleased(MouseEvent e) {
setBackground(Color.pink);
msg = "released";
repaint();
}
public void mouseDragged(MouseEvent e) {
setBackground(Color.gray);
msg = "dragged";
repaint();
}
public void mouseMoved(MouseEvent e) {
setBackground(Color.green);
msg = "moved";
repaint();
}
public void paint(Graphics g) {
g.drawString(msg, 200,200);
}
public static void main(String args[]) {
METest m = new METest();
}
class W extends WindowAdapter{
public void windowClosing(WindowEvent we) {
System.exit(0);
}
}
}
OUTPUT:

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.*;

class KEvents extends Frame implements KeyListener{


String msg=" ";
KEvents()
{
setSize(300,300);
setVisible(true);
addKeyListener(this);
addWindowListener(new W());
}
public void keyPressed(KeyEvent e)
{
setBackground(Color.yellow);
msg = "KeyPressed";
repaint();
}
public void keyTyped(KeyEvent e)
{
setBackground(Color.red);
msg = "KeyTyped";
repaint();
}
public void keyReleased(KeyEvent e)
{
setBackground(Color.pink);
msg = "KeyRelased";
repaint();
}

public static void main(String args[])


{
new KEvents();
}
public void paint(Graphics g){
g.setFont(new Font("Times new Roman", Font.BOLD, 20));
g.drawString(msg,40,40);
}
class W extends WindowAdapter
{
public void windowClosing(WindowEvent we)
{ System.exit(0);}
}
}
OUTPUT:
10. An Example of Notepad Program

import java.awt.*;
import java.awt.event.*;
import java.io.*;

clsass MenuDemo1 extends Frame


{
String filename;
TextArea ta1;

MenuDemo1(String s1)
{
super(s1);

//creating and adding textarea


ta1 = new TextArea();
add(ta1);

MenuBar mb = new MenuBar();


Menu Ops, ed,sub;
MenuItem n,o,s,c,a,ac;
MenuShortcut ns,os,ss,cs;

Ops = new Menu("File");


ed = new Menu("Edit");
sub = new Menu("Special");

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

a = new MenuItem("SAve as");


ac = new MenuItem("close as");

// adding menuitems to menu


Ops.add(n);
Ops.addSeparator();
Ops.add(o);
Ops.add(s);
Ops.addSeparator();
Ops.add(c);

sub.add(a);
sub.add(ac);
ed.add(sub);

//adding menu to menubar


mb.add(Ops);
mb.add(ed);

// adding menubar to frame


setMenuBar(mb);

//adding actionlisteners
n.addActionListener(new New());
o.addActionListener(new Open());
s.addActionListener(new Save());
c.addActionListener(new Close());

addWindowListener(new MyWindowAdapter());
}

public static void main(String args[])


{
MenuDemo1 f = new MenuDemo1("Files");
f.setSize(200,200);
f.pack();
f.setVisible(true);
f.setResizable(false);
f.setLocation(100,50);
f.requestFocus();
}

class New implements ActionListener{


public void actionPerformed(ActionEvent e)
{
ta1.setVisible(true);
ta1.requestFocus();
ta1.setText("");
setTitle("Untitiled");
}
}

class Open implements ActionListener


{
public void actionPerformed(ActionEvent e)
{
ta1.setVisible(true);
FileDialog f1 = new FileDialog(MenuDemo1.this, "OpenFile", FileDialog.LOAD);
f1.show();

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;

while((line = br.readLine())!= null)


{
sb.append(line + "\n");
ta1.setFont(new Font("Times New Roman", Font.BOLD,12));
ta1.setText(sb.toString());
}
br.close();
}catch(Exception e){System.out.println("File error");}
}

class Save implements ActionListener{


public void actionPerformed(ActionEvent e)
{
FileDialog f1 = new FileDialog(MenuDemo1.this, "Save File", FileDialog.SAVE);
f1.show();
if(f1.getFile()!=null)
{
filename = f1.getDirectory() + f1.getFile();
setTitle(filename);
// SaveFile();

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

class Close implements ActionListener


{
public void actionPerformed(ActionEvent e)
{
setTitle("");
ta1.setText("");
ta1.setVisible(false);
}
}
class MyWindowAdapter extends WindowAdapter{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
}

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;

public class Simple extends Applet {


StringBuffer buffer;
public void init() {
buffer = new StringBuffer();
addItem("initializing... ");
}
public void start() {
addItem("starting... ");
}

public void stop() {


addItem("stopping... ");
}

public void destroy() {


addItem("preparing for unloading...");
}

void addItem(String newWord) {


System.out.println(newWord);
buffer.append(newWord);
repaint();
}

public void paint(Graphics g) {


//Draw a Rectangle around the applet's display area.
g.drawRect(0, 0, size().width - 1, size().height - 1);

//Draw the current string inside the rectangle.


g.drawString(buffer.toString(), 5, 15);
}
}

OUTPUT:

Methods for Drawing and Event Handling in Applets


The Simple applet defines its onscreen appearance by overriding the paint method:
class Simple extends Applet {
...
public void paint(Graphics g) { . . . }
...
}
The paint method is one of two display methods an applet can override:

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.

To react to an event, an applet must override either the appropriate event-specific


method or the handleEvent method.
Applets inherit from the AWT Container class. This means that they are designed to
hold Components -- user interface objects such as buttons, labels, pop-up lists, and
scrollbars. Like other Containers, applets use layout managers to control the positioning
of Components.

Methods for Adding UI Components

The AWT supplies the following UI components


i. Buttons (java.awt.Button)
ii. Checkboxes (java.awt.Checkbox)
iii. Single-line text fields (java.awt.TextField)
iv. Larger text display and editing areas (java.awt.TextArea)
v. Labels (java.awt.Label)
vi. Lists (java.awt.List)
vii. Pop-up lists of choices (java.awt.Choice)
viii. Sliders and scrollbars (java.awt.Scrollbar)
ix. Drawing areas (java.awt.Canvas)
x. Menus (java.awt.Menu, java.awt.MenuItem, java.awt.CheckboxMenuItem)
xi. Containers (java.awt.Panel, java.awt.Window and its subclasses)

It's easy to add components to applets and to use layout managers to control the
components onscreen positions.

An example of adding AWT components to applets

//<applet code=AwtCom width=300 height=300></applet>


import java.awt.*;
import java.applet.*;
public class AwtCom extends Applet
{
public void init()
{
Label one=new Label("one ",Label.RIGHT);
Button b=new Button("Click");
Checkbox cb=new Checkbox("select",true);
CheckboxGroup cbg=new CheckboxGroup();
Checkbox c1=new Checkbox("male",cbg,true);
Checkbox c2=new Checkbox("female",cbg,false);
Choice ch=new Choice();
ch.addItem("dos");
ch.addItem("nt");
List l=new List(3,true);
l.add("c");
l.add("C++");
l.add("java");
Scrollbar s=new Scrollbar(Scrollbar.HORIZONTAL,4,5,0,100);
TextField t= new TextField(10);
TextArea ta =new TextArea(10,10);
add(ta); add(s); add(t); add(l); add(ch);add(c1); add(c2);add(cb);
add(b);add(one);
}
}

OUTPUT:

An example to print a scrolling string


import java.awt.*;
import java.applet.*;
//<applet code= Banner height=200 width=200></applet>
public class Banner extends Applet implements Runnable{
Thread t;
String s=" WELCOME ";
public void start(){
t=new Thread(this);
t.start();
}
public void paint(Graphics g){
g.drawString (s,10,10);
showStatus(s);
}
public void run(){
while(true){
repaint();
try{
char w=s.charAt(0);
s=s.substring(1,s.length());
s+=w;
Thread.sleep(100);
}catch (Exception e){}
}

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

Test Driving an Applet

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.

What Kind of Value Should Each Parameter Take?


Parameter values are all strings. Whether or not the user puts quotation marks around a
parameter value, that value is passed to your applet as a string. However, your applet can
interpret the string in many ways.
Applets typically interpret a parameter value as one of the following types:
An URL
An integer
A floating-point number
A boolean value -- typically "true"/"false" or "yes"/"no"
A String -- for example, the string to use as a window title
A list of any of the above

What Should the Default Value of Each Parameter Be?


Applets should attempt to provide useful default values for each parameter, so that the
applet will execute even if the user doesn't specify a parameter or specifies it incorrectly.
For example, an animation applet should provide a reasonable setting for the number of
images it displays per second.

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

<APPLET CODE=AppletButton.class CODEBASE=example


WIDTH=350 HEIGHT=60>
<PARAM NAME=windowClass VALUE=BorderWindow>
<PARAM NAME=windowTitle VALUE="BorderLayout">
<PARAM NAME=buttonText VALUE="Click here to see a BorderLayout in action">
</APPLET>

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.

Writing the Code to Support Parameters


Applets use the Applet getParameter method to get user-specified values for applet
parameters. The getParameter method is defined as follows:
public String getParameter(String name)

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

String windowWidthString = getParameter("WINDOWWIDTH");


if (windowWidthString != null) {
try {
requestedWidth = Integer.parseInt(windowWidthString);
} catch (NumberFormatException e) {
//Use default width.
}
}

String windowHeightString = getParameter("WINDOWHEIGHT");


if (windowHeightString != null) {
try {
requestedHeight = Integer.parseInt(windowHeightString);
} catch (NumberFormatException e) {
//Use default height.
}
}

Threads in Applets

import java.applet.*;
import java.awt.*;
// <applet code = Dots width=250 height =300></applet>

public class Dots extends Applet implements Runnable{


Thread t;
Color f;
int rc,gc,bc;
public void init()
{
t = new Thread(this);
t.start();
}

public void run()


{
try{
while(true){
repaint();
Thread.sleep(200);
}
}catch(Exception e){}
}
public void update(Graphics g){
paint(g);
}

public void paint(Graphics g){


Dimension d = getSize();
int x = (int)(Math.random() * d.width);
int y = (int)(Math.random() * d.height);
rc=(int) Math.floor(Math.random() * 256);
gc=(int) Math.floor(Math.random() * 256);
bc=(int) Math.floor(Math.random() * 256);
g.setColor(new Color(rc,gc,bc));
g.fillRect(x,y,3,3);
}
}

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.*;

/* <Applet code="DrawImage" width=350 height=250>


<param name="file" value="bld.jpg"> </applet>*/
public class DrawImage extends Applet{
Image image;

public void init(){


image = getImage(getDocumentBase(), getParameter("file"));
}
public void paint(Graphics g){
g.drawImage(image,0,0,this);
}
}

OUTPUT:

2. An Example on different Draw methods of Graphic class

//arcs.polygons,lines,rectangles,ovals
import java.applet.*;
import java.awt.*;

public class shapes extends Applet{


public void paint(Graphics g)
{
int[] xpts = {10, 30,40,50, 70, 50, 40, 30};
int[] ypts = {100,90,70,90,100,110,130,110};
int n = xpts.length;
Polygon star = new Polygon(xpts,ypts,n);
g.setColor(Color.blue);
g.drawPolygon(star);

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.

Methods of Color class:

Color getColor() int getGreen()


Color brighter() int getBlue()
Color darker() int getRGB()
int getRed()

An example on Color class:


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

class scroll extends Frame implements AdjustmentListener{


Label r,g,b;
Scrollbar rsb,gsb,bsb;
Panel p;
Canvas c;
scroll(){
p = new Panel();
p.setLayout(new GridLayout(3,2));
p.add(r= new Label("red"));
p.add(rsb = new Scrollbar(Scrollbar.HORIZONTAL,0,0,0,255));
rsb.setBlockIncrement(16);
rsb.addAdjustmentListener(this);

p.add(g= new Label("green"));


p.add(gsb = new Scrollbar(Scrollbar.HORIZONTAL,0,0,0,255));
gsb.setBlockIncrement(16);
gsb.addAdjustmentListener(this);

p.add(b= new Label("blue"));


p.add(bsb = new Scrollbar(Scrollbar.HORIZONTAL,0,0,0,255));
bsb.setBlockIncrement(16);
bsb.addAdjustmentListener(this);

add(p,"North");
c = new Canvas();
c.setBackground(Color.black);
add(c,"Center");
addWindowListener(new w());
}

public void adjustmentValueChanged(AdjustmentEvent ae)


{
r.setText("Red " + rsb.getValue());
g.setText("Green " + gsb.getValue());
b.setText("Blue " + bsb.getValue());
c.setBackground(new Color(rsb.getValue(), gsb.getValue(), bsb.getValue()));
repaint();
}

public static void main(String args[])


{
scroll sc = new scroll();
sc.setSize(300,300);
sc.setVisible(true);
}
}

class w extends WindowAdapter{


public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}

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:

Similarly, a program can send information to an external destination by opening a stream


to a destination and writing the information out 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.

 Using the Data Sink Streams


 Using the Processing Streams

Using the Data Sink Streams

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.

Sink Type Character Streams Byte 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.

StringReader and StringWriter


StringBufferInputStream
Use StringReader to read characters from a String as it lives in memory. Use
StringWriter to write to a String. StringWriter collects the characters written to it in
a StringBuffer, which can then be converted to a String. StringBufferInputStream
is similar to StringReader, except that it reads bytes from a StringBuffer.

FileReader and FileWriter


FileInputStream and FileOutputStream
Collectively called file streams, these streams are used to read from or write to a file on
the native file system. We see an example that uses FileReader and FileWriter to copy
the contents of one file into another.

PipedReader and PipedWriter


PipedInputStream and PipedOutputStream
Implement the input and output components of a pipe. Pipes are used to channel the
output from one program (or thread) into the input of another.

Overview of I/O Streams


Character Streams
Reader and Writer are the abstract super classes for character streams in java.io.
Reader provides the API and partial implementation for readers--streams that read 16-bit
characters--and Writer provides the API and partial implementation for writers--streams
that write 16-bit characters.
The figure shows the class hierarchies for the Reader and Writer classes.

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.

Understanding the I/O Superclasses


Reader and InputStream define similar APIs but for different data types. For example,
Reader contains these methods for reading characters and arrays of characters:
int read() int read(char cbuf[])
int read(char cbuf[], int offset, int length)
InputStream defines the same methods but for reading bytes and arrays of bytes:
int read() int read(byte cbuf[])
int read(byte cbuf[], int offset, int length)

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.*;

public class Copy {


public static void main(String[] args) throws IOException {
File inputFile = new File("Griet.txt");
File outputFile = new file("Grietagain.txt");

FileReader in = new FileReader(inputFile);


FileWriter out = new FileWriter(outputFile);
int c;
while ((c = in.read()) != -1)
out.write(c);
in.close();
out.close();
}
}
This program is very simple. It opens a FileReader on Griet.txt and opens a
FileWriter on Grietagain.txt. The program reads characters from the reader as long
as there's more input in the input file. When the input runs out, the program closes both
the reader and the writer.

Here is the content of the file “Griet.txt”:


So she went into the garden to cut a cabbage-leaf, to
make an apple-pie; and at the same time a great
she-bear, coming up the street, pops its head into the
shop. 'What! no soap?' So he died, and she very
imprudently married the barber; and there were
present the Picninnies, and the Joblillies, and the
Garyalies, and the grand Panjandrum himself, with the
little round button at top, and they all fell to playing
the game of catch as catch can, till the gun powder ran
out at the heels of their boots.

Here is another version of this program, CopyBytes, which uses FileInputStream and
FileOutputStream in place of FileReader and FileWriter.
import java.io.*;

public class CopyBytes {


public static void main(String[] args) throws IOException {
File inputFile = new File("Griet.txt");
File outputFile = new File("Grietoutagain.txt");

FileInputStream in = new FileInputStream(inputFile);


FileOutputStream out = new FileOutputStream(outputFile);
int c;

while ((c = in.read()) != -1)


out.write(c);

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.*;

public class RhymingWords {


public static void main(String[] args) throws IOException {

FileReader words = new FileReader("words.txt");


// do the reversing and sorting
Reader rhymedWords = reverse(sort(reverse(words)));
// write new list to standard out
BufferedReader in = new BufferedReader(rhymedWords);
String input;
while ((input = in.readLine()) != null)
System.out.println(input);
in.close();
}
public static Reader reverse(Reader source) throws IOException {
BufferedReader in = new BufferedReader(source);
PipedWriter pipeOut = new PipedWriter();
PipedReader pipeIn = new PipedReader(pipeOut);
PrintWriter out = new PrintWriter(pipeOut);
new ReverseThread(out, in).start();
return pipeIn;
}
public static Reader sort(Reader source) throws IOException {
BufferedReader in = new BufferedReader(source);
PipedWriter pipeOut = new PipedWriter();
PipedReader pipeIn = new PipedReader(pipeOut);
PrintWriter out = new PrintWriter(pipeOut);

new SortThread(out, in).start();


return pipeIn;
}
}

ReverseThread.java
import java.io.*;

public class ReverseThread extends Thread {


private PrintWriter out = null;
private BufferedReader in = null;

public ReverseThread(PrintWriter out, BufferedReader in) {


this.out = out;
this.in = in;
}

public void run() {


if (out != null && in != null) {
try {
String input;
while ((input = in.readLine()) != null) {
out.println(reverseIt(input));
out.flush();
}
out.close();
} catch (IOException e) {
System.err.println("ReverseThread run: " + e);
}
}
}

private String reverseIt(String source) {


int i, len = source.length();
StringBuffer dest = new StringBuffer(len);

for (i = (len - 1); i >= 0; i--)


dest.append(source.charAt(i));
return dest.toString();
}
}

SortedThread.java
import java.io.*;
public class SortThread extends Thread {
private PrintWriter out = null;
private BufferedReader in = null;

public SortThread(PrintWriter out, BufferedReader in) {


this.out = out;
this.in = in;
}

public void run() {


int MAXWORDS = 50;

if (out != null && in != null) {


try {
String[] listOfWords = new String[MAXWORDS];
int numwords = 0;

while ((listOfWords[numwords] = in.readLine()) != null)


numwords++;
quicksort(listOfWords, 0, numwords-1);
for (int i = 0; i < numwords; i++)
out.println(listOfWords[i]);
out.close();
} catch (IOException e) {
System.err.println("SortThread run: " + e);
}
}
}

private static void quicksort(String[] a, int lo0, int hi0) {


int lo = lo0;
int hi = hi0;

if (lo >= hi)


return;

String mid = a[(lo + hi) / 2];


while (lo < hi) {
while (lo<hi && a[lo].compareTo(mid) < 0)
lo++;
while (lo<hi && a[hi].compareTo(mid) > 0)
hi--;
if (lo < hi) {
String T = a[lo];
a[lo] = a[hi];
a[hi] = T;
}
}
if (hi < lo) {
int T = hi;
hi = lo;
lo = T;
}
quicksort(a, lo0, lo);
quicksort(a, lo == lo0 ? lo+1 : lo, hi0);
}
}

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.

Using Streams to Wrap Other Streams


The reverse method contains some other interesting code; in particular, these two
statements:
BufferedReader in = new BufferedReader(source);
...
PrintWriter out = new PrintWriter(pipeOut);
The first line opens a BufferedReader on source, the argument to reverse (a Reader).
This essentially "wraps" source in a BufferedReader. The program reads from the
BufferedReader, which in turn reads from source. The program does this so that it can
use BufferedReader's convenient readLine method. Similarly, the PipedWriter is
wrapped in a PrintWriter so that the program can use PrintWriter's convenient
println method. You will often see streams wrapped in this way so as to combine the
various features of the many streams.
Using the Processing Streams
Processing streams perform some sort of operation, such as buffering or character
encoding, as they read and write. Like the data sink streams, java.io often contains pairs
of streams: one that performs a particular operation during reading and another that
performs the same operation (or reverses it) during writing. This table gives java.io's
processing streams.

Process CharacterStreams Byte Streams


BufferedReader, BufferedInputStream,
Buffering
BufferedWriter BufferedOutputStream

FilterReader, FilterInputStream,
Filtering
FilterWriter FilterOutputStream

Converting between InputStreamReader,


Bytes and Characters OutputStreamWriter

Concatenation SequenceInputStream

ObjectInputStream,
Object Serialization
ObjectOutputStream

DataInputStream,
Data Conversion
DataOutputStream

Counting LineNumberReader LineNumberInputStream

Peeking Ahead PushbackReader PushbackInputStream

Printing PrintWriter PrintStream

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.

InputStreamReader and OutputStreamWriter


A reader and writer pair that forms the bridge between byte streams and character
streams. An InputStreamReader reads bytes from an InputStream and converts them to
characters using either the default character-encoding or a character-encoding specified
by name. Similarly, an OutputStreamWriter converts characters to bytes using either
the default character-encoding or a character-encoding specified by name and then writes
those bytes to an OutputStream. You can learn the name of the default character-
encoding by calling System.getProperty("file.encoding").
SequenceInputStream
Concatenates multiple input streams into one input stream.

ObjectInputStream and ObjectOutputStream


Used to serialize objects.

DataInputStream and DataOutputStream


Read or write primitive Java data types in a machine-independent format.

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.

Example on Sequence Input Streams


Concatenate.java

import java.io.*;

public class Concatenate {


public static void main(String[] args) throws IOException {
ListOfFiles mylist = new ListOfFiles(args);

SequenceInputStream s = new SequenceInputStream(mylist);


int c;

while ((c = s.read()) != -1)


System.out.write(c);
s.close();
}
}
The first thing that the Concatenate utility does is create a ListOfFiles object named
mylist which is initialized from the command line arguments entered by the user. The
command line arguments list the files to be concatenated together. mylist is used to
initialize the SequenceInputStream which uses mylist to get a new InputStream for
every filename listed by the user.

ListofFiles.java

import java.util.*;
import java.io.*;

public class ListOfFiles implements Enumeration {


private String[] listOfFiles;
private int current = 0;

public ListOfFiles(String[] listOfFiles) {


this.listOfFiles = listOfFiles;
}

public boolean hasMoreElements() {


if (current < listOfFiles.length)
return true;
else
return false;
}

public Object nextElement() {


InputStream in = null;

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;

while ((input = dis.readLine()) != null) {


. . . // do something interesting here
}
You might do this so that you can use the more convenient readXXX methods, such as
readLine, implemented by DataInputStream.

How to Use DataInputStream and DataOutputStream


This is an example of using DataOutputStream and DataInputStream with two
filtered streams that can read and write primitive Java data types.
The example below uses DataOutputStream's specialized writeXXX methods to write
the employee data according to the type of data being written. DataOutputStream, like
other filtered output streams, must be attached to some other OutputStream. In this case,
it's attached to a FileOutputStream that's set up to write to a file named passed as
command line argument.
// create a class dataoutDemo for DataOutputStream
import java.io.*;
class Employee
{
String s1 = new String();
byte b1;
int i1; float f1;

Employee(String s, byte b, int i,float f)


{s1 = s; b1 = b; f1 = f; i1 = i;}

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

Employee e[] = new Employee[5];


e[0] = new Employee("sai",(byte) 34,6,25000f);
e[1] = new Employee("gai",(byte) 35,5,22000f);
e[2] = new Employee("lai",(byte) 36,5,23000f);
e[3] = new Employee("rai",(byte) 37,6,21000f);
e[4] = new Employee("vai",(byte) 38,5,24000f);

for(int i = 0; i<5; i++){


dos.writeUTF(e[i].s1);
dos.writeByte(e[i].b1);
dos.writeFloat(e[i].f1);
dos.writeInt(e[i].i1);
}
dos.close();
}
}

DataInputStream also must be attached to some other InputStream; in this case, a


FileInputStream set up to read the file just written. DataInpDemo then just reads the
data back in using DataInputStream's specialized readXXX methods.

// Create a file dataInpDemo for DataInputStream


import java.io.*;
class dataInpDemo{
public static void main(String args[]) throws IOException{
DataInputStream dis = new DataInputStream(new FileInputStream(args[0]));
String s1; float f1; int i1; byte b1;
System.out.println("Name \tAge\tHeight\tsalary");
while(dis.available() > 0) {
s1 = dis.readUTF();
b1 = dis.readByte();
f1 = dis.readFloat();
i1 = dis.readInt();
System.out.println(s1 + "\t" + b1 + "\t" + i1 +"\t"+f1);
}
dis.close();
}
}
Output:
C:\>javac dataInpDemo.java
C:\>java dataInpDemo Data.txt
Name Age Height Salary
Rama 34 6 25000.0
Ravi 35 5 22000.0
Geetha 36 5 23000.0
Sannu 37 6 21000.0
Gunnu 38 5 24000.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();
}
}

//Create a file oisDemo for ObjecInputStream


import java.io.*;

class stud implements Serializable


{
byte b1; String s1; int i1; float f1;
stud()
{ this("sai", (byte) 24, 16, 22500f);}

stud(String s, byte b, int il, float f)


{ s1= s; b1=b; i1=il; f1= f;}
}

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

Working with Random Access Files


The character and byte streams are all sequential access streams. In contrast,
RandomAccessFile lets you randomly access the contents of a file. The
RandomAccessFile class implements both the DataInput and DataOutput interfaces
and therefore can be used for both reading and writing. RandomAccessFile is similar to
FileInputStream and FileOutputStream in that you specify a file on the native file
system to open when you create it.
When you create a RandomAccessFile, you must indicate whether you will be just
reading the file or also writing to it. (You have to be able to read a file in order to write
it.) The following line of Java code creates a RandomAccessFile to read the file named
farrago.txt:
new RandomAccessFile("farrago.txt", "r");
And this one opens the same file for both reading and writing:
new RandomAccessFile("farrago.txt", "rw");

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.

The following is an example on Random Access Files.


import java.io.*;
class rafDemo
{
public static void main(String args[]) throws Exception
{
RandomAccessFile raf = new RandomAccessFile(args[0], args[1]);
BufferedReader brl = new BufferedReader(new InputStreamReader(System.in));
long myFilePointer = raf.length();
String s1; StringBuffer sb = new StringBuffer(25);
while(args[1].equals("rw"))
{
myFilePointer = raf.getFilePointer();
System.out.println("\nEnter data (~for exit)" + myFilePointer);
s1=brl.readLine();

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

while(raf.getFilePointer() < myFilePointer)


{
s1 = raf.readLine();
System.out.println("\t" + s1);
}
brl.close();
raf.close();
}
}

Writing Filters for Random Access Files


RandomAccessFile doesn't inherit from the InputStream or OutputStream hence you
can't apply the same filters to RandomAccessFiles that you can to streams. However,
RandomAccessFile does implement the DataInput and DataOutput interfaces, so if you
design a filter that works for either DataInput or DataOutput, it will work on some
sequential access files (the ones that implemented DataInput or DataOutput) as well as
any RandomAccessFile.
The following is a list of steps to take when writing your own filtered input and output
streams:
Create a subclass of FilterInputStream and FilterOutputStream. Input and output
streams often come in pairs, so it's likely that you will need to create both input and
output versions of your filter stream.
Override the read and write methods.
Override any other methods that you might need.
Make sure the input and output streams work together.
Both the input and the output stream use a checksum class to compute a checksum on the
data written to or read from the stream. The checksum is used to determine whether the
data read by the input stream matches that written by the output stream.
Four classes and one interface make up this example program:
The filtered input and output stream subclasses--CheckedOutputStream and
CheckedInputStream.
The Checksum interface and the Adler32 class compute a checksum for the streams.
The CheckedIOTest class defines the main method for the program.
The CheckedIOTest example implements two filtered streams, CheckedInputStream
and CheckedOutputStream, that compute a checksum as data is read from or written to
the stream.
//Adler32.java
public class Adler32 implements Checksum {
private int value = 1;

/** BASE is the largest prime number smaller than 65536


* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */
private static final int BASE = 65521;
private static final int NMAX = 5552;
/*** Update current Adler-32 checksum given the specified byte. */
public void update(int b) {
int s1 = value & 0xffff;
int s2 = (value >> 16) & 0xffff;
s1 += b & 0xff;
s2 += s1;
value = ((s2 % BASE) << 16) | (s1 % BASE);
}
/*** Update current Adler-32 checksum given the specified byte array. */
public void update(byte[] b, int off, int len) {
int s1 = value & 0xffff;
int s2 = (value >> 16) & 0xffff;
while (len > 0) {
int k = len < NMAX ? len : NMAX;
len -= k;
while (k-- > 0) {
s1 += b[off++] & 0xff;
s2 += s1;
}
s1 %= BASE;
s2 %= BASE;
}
value = (s2 << 16) | s1;
}
/*** Reset Adler-32 checksum to initial value. */
public void reset() {
value = 1;
}
/*** Returns current checksum value. */
public long getValue() {
return (long)value & 0xffffffff;
}
}

//CheckedInputStream
import java.io.FilterInputStream;
import java.io.InputStream;
import java.io.IOException;

public class CheckedInputStream extends FilterInputStream {


private Checksum cksum;
public CheckedInputStream(InputStream in, Checksum cksum) {
super(in);
this.cksum = cksum;
}
public int read() throws IOException {
int b = in.read();
if (b != -1) {
cksum.update(b);
}
return b;
}

public int read(byte[] b) throws IOException {


int len;
len = in.read(b, 0, b.length);
if (len != -1) {
cksum.update(b, 0, len);
}
return len;
}

public int read(byte[] b, int off, int len) throws IOException {


len = in.read(b, off, len);
if (len != -1) {
cksum.update(b, off, len);
}
return len;
}

public Checksum getChecksum() {


return cksum;
}
}

//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 {

Adler32 inChecker = new Adler32();


Adler32 outChecker = new Adler32();
CheckedInputStream in = null;
CheckedOutputStream out = null;
try {
in = new CheckedInputStream(
new FileInputStream("farrago.txt"),
inChecker);
out = new CheckedOutputStream(
new FileOutputStream("outagain.txt"),
outChecker);
} catch (FileNotFoundException e) {
System.err.println("CheckedIOTest: " + e);
System.exit(-1);
} catch (IOException e) {
System.err.println("CheckedIOTest: " + e);
System.exit(-1);
}

int c;
while ((c = in.read()) != -1)
out.write(c);

System.out.println("Input stream check sum: " +


inChecker.getValue());
System.out.println("Output stream check sum: " +
outChecker.getValue());

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.

Networking Classes in the JDK:

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:

As in the previous diagram, a URL has two main components:


 Protocol identifier
 Resource name

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.

Filename The pathname to the file on the machine.

Port
The port number to which to connect (typically optional).
Number

A reference to a named anchor within a resource that usually


Reference
identifies a specific location within a file (typically optional).

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:

Reading Directly from a URL

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.*;

public class URLReader {


public static void main(String[] args) throws Exception {
URL yahoo = new URL("http://www.yahoo.com/");
BufferedReader in = new BufferedReader(
new InputStreamReader(
yahoo.openStream()));

String inputLine;

while ((inputLine = in.readLine()) != null)


System.out.println(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();

} catch (MalformedURLException e) { // new URL() failed


...
} catch (IOException e) { // openConnection() failed
...
}

The openConnection method creates a new URLConnection, initializes it, connects to


the URL, and returns the URLConnection object. If something goes wrong--for example,
the Yahoo server is down--then the openConnection method throws an IOException.
Now after successful connection, you can use the URLConnection object to perform
actions such as reading from or writing to the connection.

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.

Additionally, java.net includes the ServerSocket class, which implements a socket


that servers can use to listen for and accept connections to clients. This lesson shows you
how to use the Socket and ServerSocket classes.

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.

Reading from and Writing to a Socket

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.

Steps to write a client program

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

PrintWriter pw = new PrintWriter(cs.getOutputStream(),true);


String in, out;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the file name in the server");
String s = br.readLine();
File f = new File(s);

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

A datagram is an independent, self-contained message sent over the network whose


arrival, arrival time, and content are not guaranteed.
The DatagramPacket and DatagramSocket classes in the java.net package implement
system-independent datagram communication using UDP.

Writing a Datagram Client and Server

The example featured in this section consists of two applications: a client and a server.
Example:

The following Example illustrates the use of DatagramSocket and DatagramPacket. It


includes one application that transmits a datagram and another application that executes
an infinite loop to receive and display datagrams.

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;

public static int cp=789,sp=790;


public static void main(String[] args)throws IOException
{
byte b[] = new byte[1024];
dc = new DatagramSocket(sp);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

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;

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


{
dc = new DatagramSocket(cp);
System.out.println("Client is waiting");
System.out.println("press Ctrl-C to exit");

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.

2. Write a program to depicit Dynamic binding in java

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.

4. Design a class to represent a bank account. Include the following members:


Data members Methods:-
a. Name of the depositor 1) To assign initial values
b. Account number 2) To deposit an amount
c. Type of account 3) To withdrawn amount
d. Balance amount in the after checking balance
account 4) To display the name and
balance

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.

Input Output Packages.

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:

1. Write a program to simulate a calculator.


2. Using the methods in the Graphics class draw a fish.
3. Draw a clock to know the current time in the frame.
4. Draw a Rectangle, an ellipse, circle, arc and give different colors.
5. Draw the following figures using Applets.
A. Polygon
B. Rectangle
C. Circle
D. Cube
6. Write a program to draw Ovals and filled ovals.

7. Draw arcs in the form of a Rainbow colors.

8. Write a program to draw.


A. Rectangles, squares and polygons.
B. Filled rectangles, squares and polygons.
C. Different colored boundary to components in B.

9. Write a program to
A. Draw Rounded rectangle. B. Half filled rectangle

10. Do the following.


A. Create a frame with flow layout.
B. Create two panels and add the panels to the frame.
C. Each panel contains three buttons. The panel uses folw layout.

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.

S-ar putea să vă placă și