You are on page 1of 66

www.csetube.

in

tu

be

.in

CS2309 JAVA LAB


LAB MANUAL

se

III YEAR B.E (COMPUTER SCIENCE AND

.c

ENGINEERING)

Prepared by
S.VARADHARAJAN
ASSISTANT PROFESSOR

1
www.csetube.in

www.csetube.in

CS2309

JAVA LAB

LTPC
0032

1. Develop Rational number class in Java. Use JavaDoc comments for documentation. Your
implementation should use efficient representation for a rational number, i.e. (500 / 1000)
should be represented as ().
2. Develop Date class in Java similar to the one available in java.util package. Use JavaDoc
comments.
3. Implement Lisp-like list in Java. Write basic operations such as 'car', 'cdr', and 'cons'. If L is

.in

a list [3, 0, 2, 5], L.car () returns 3, while L.cdr () returns [0, 2, 5].
4. Design a Java interface for ADT Stack. Develop two different classes that implement this
interface, one using array and the other using linked-list. Provide necessary exception

be

handling in both the implementations.

5. Design a Vehicle class hierarchy in Java. Write a test program to demonstrate


polymorphism.

tu

6. Design classes for Currency, Rupee, and Dollar. Write a program that randomly generates
Rupee and Dollar objects and write them into a file using object serialization. Write another

se

program to read that file, convert to Rupee if it reads a Dollar, while leave the value as it is if
it reads a Rupee.

7. Design a scientific calculator using event-driven programming paradigm of Java.

.c

8. Write a multi-threaded Java program to print all numbers below 100,000 that are both
prime and fibonacci number (some examples are 2, 3, 5, 13, etc.). Design a thread that

generates prime numbers below 100,000 and writes them into a pipe. Design another thread

that generates fibonacci numbers and writes them to another pipe. The main thread should
read both the pipes to identify numbers common to both.

9. Develop a simple OPAC system for library using even-driven and concurrent programming
paradigms of Java. Use JDBC to connect to a back-end database.
10. Develop multi-threaded echo server and a corresponding GUI client in Java.
11. [Mini-Project] Develop a programmer's editor in Java that supports syntax highlighting,
compilation support, debugging support, etc.
TOTAL= 45

PERIODS

2
www.csetube.in

www.csetube.in

REQUIREMENTS

HARDWARE:

Pentium IV with 2 GB RAM,


160 GB HARD Disk,
Monitor 1024 x 768 colour
60 Hz.

.in

30 Nodes

SOFTWARE:

be

Windows /Linux operating system


JDK 1.6(or above)

.c

se

tu

30 user license

3
www.csetube.in

www.csetube.in

TABLE OF CONTENTS

Rational number

Date class in Java

Implement Lisp-like list in Java.

Java interface for ADT Stack using array and the sing linked-

Polymorphism

object serialization

scientific calculator

se

be

list.

tu

.in

LIST OF EXPERIMENTS

Multi-threaded Java program

Fibonacci number (some examples are 2, 3, 5, 13, etc.).

.c

prime numbers below 100,000 and writes them into a pipe

A Simple OPAC system for library

Main thread should read both the pipes.

10
11

Multi-threaded echo server GUI client.


[Mini-Project] programmers editor.

4
www.csetube.in

www.csetube.in

Ex No1:

Rational Numbers

AIM
To write a Java Program to develop a class for Rational numbers.

ALGORITHM:

.in

Step 1:-Declare a class called Rational and invoke a function called gcd(a,b).
Step 2:-Find out the reminder when a is divided by b and pass it as a parameter to the function.
Step 3:-Create an object for the class and declare the required string and integer variables.

be

Step 4:-Create an object of class DataInputStream .Read the numbers through the ReadLine() method
into the object.

Step 5:-Convert the input accepted into Integers through the parseInt method and store them in

tu

variables a and b.

Step 6:-store the value returned by the function GCD in variable l.

se

Step 7:-Divide a by l and b by l and store them in variables x and y.

.c

Program:-

import java.io.*;

class rational1

public rational1(){}

public long gcd(long a,long b)


{

if(b==0)
return a;
else
return gcd(b,a%b);
}
}
public class rational
5
www.csetube.in

www.csetube.in

{
public static void main(String args[])throws IOException
{
/**
* create and initialize a new Rational object
*/
rational1 r=new rational1();
/**

.in

* The Numerator and Denominator part of Rational


*/
long a,b,x,y;

be

String str;

DataInputStream in= new DataInputStream(System.in);


System.out.println("Enter the value for A");

tu

str=in.readLine();
a=Integer.parseInt(str);

str=in.readLine();

se

System.out.println("Enter the value for B");

.c

b=Integer.parseInt(str);

long l=r.gcd(a,b);

System.out.println();

System.out.println("The GCD of the number is:"+l);


x=a/l;

y=b/l;

System.out.println();
System.out.println("The resultant value is: "+x+"/"+y);

}
}

6
www.csetube.in

www.csetube.in

Output

Enter the value for A

.in

500
Enter the value for B

be

1000

The GCD of the number is:500

.c

se

tu

The resultant value is: 1/2

Result
Thus the above program was executed and verified successfully.

7
www.csetube.in

www.csetube.in

Ex No 2:

Date Class in Java

AIM
To design a Date class in Java.

ALGORITHM:Step 1: Declare a class called Date example and create an object called date.

.in

Step 2:- Display the Date and Time through these objects with the Methods in Date Class.
Step 3:- Declare two objects called start time and end time for this class .

Step 4:- Create another object called changed object and display the changed time with the calculation

be

Step 5:- In the main function create object for the class Date and display the time and date

.c

se

tu

accordingly.

8
www.csetube.in

www.csetube.in

SOURCE CODE

import java.util.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class DateExample {
private static void DateExample() {
Date date = new Date();

.in

System.out.println("Current Date and Time is : " + date);


System.out.println();

Date particulardate1 = new Date(2000,3,12);


Date particulardate2 = new Date(2000,4,12,9,10);
System.out.println();

be

System.out.println("Date object showing specific date and time");

tu

System.out.println("First Particular date : " + particulardate1);

System.out.println();

se

System.out.println("Second Particular date: " + particulardate2);

System.out.println("Demo of getTime() method returning milliseconds");


System.out.println();

.c

Date strtime = new Date();

System.out.println("Start Time: " + strtime);

Date endtime = new Date();

System.out.println("End Time is: " + endtime);


long elapsed_time = endtime.getTime() - strtime.getTime();

System.out.println("Elapsed Time is:" + elapsed_time + "milliseconds");


System.out.println();
System.out.println("Changed date object using setTime() method");
System.out.println();
Date chngdate = new Date();
System.out.println("Date before change is: " + chngdate);
chngdate.setHours(12);
System.out.println("Now the Changed date is: " + chngdate);
System.out.println();
}
9
www.csetube.in

www.csetube.in

public static void main(String[] args) {


System.out.println();
DateExample();
}
}

D:\java>java DateExample

be

Current Date and Time is : Thu May 05 09:56:18 IST 2011

.in

OUTPUT

tu

Date object showing specific date and time

First Particular date : Thu Apr 12 00:00:00 IST 3900

se

Second Particular date: Sat May 12 09:10:00 IST 3900

.c

Demo of getTime() method returning milliseconds

Start Time: Thu May 05 09:56:18 IST 2011

End Time is: Thu May 05 09:56:18 IST 2011

Elapsed Time is:0 milliseconds

Changed date object using setHours() method

Date before change is: Thu May 05 09:56:18 IST 2011


Now the Changed date is: Thu May 05 12:56:18 IST 2011

Result
Thus the above program was executed and verified successfully.

10
www.csetube.in

www.csetube.in

3.Implement Lisp-like list in Java.

Aim:
To Implement basic operations such as 'car', 'cdr', and 'cons' using Lisp-like list in Java. If L is a list
[3, 0, 2, 5], L.car() returns 3, while L.cdr() returns [0,2,5]

.c

se

tu

be

.in

Procedure:

11
www.csetube.in

www.csetube.in

Program:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.StringTokenizer;

.in

import java.util.logging.Logger;

public class LispCommands {

be

private String[] tokenList;

private static Logger LOGGER = Logger.getLogger(LispCommands.class.getName());

se

tu

public LispCommands() {

private void car() {

.c

LOGGER.info(tokenList[0]);

private void cdr() {

List<String> list = Arrays.asList(tokenList);

ArrayList<String> slist = new ArrayList<String>(list);


slist.remove(0);
display(slist);

private void cons(String args) {


List<String> arrayList = new ArrayList<String>(Arrays.asList(tokenList));
arrayList.add(args);
Collections.reverse(arrayList);
display(arrayList);
12
www.csetube.in

www.csetube.in

private void parse(String args) {


ArrayList<String> tokenList = new ArrayList<String>();
if(args != null){
StringTokenizer tokens = new StringTokenizer(args,"[]");
while (tokens.hasMoreElements()) {
StringTokenizer commaTokens = new StringTokenizer(tokens.nextToken(),",");

.in

while (commaTokens.hasMoreElements()) {
String token = commaTokens.nextToken();

be

if(token != null && !token.trim().equals("")){

tokenList.add(token.trim());
}

se

tu

.c

this.tokenList = tokenList.toArray(new String[0]);

private void display(Object result) {


System.out.println();

if(result instanceof String){


LOGGER.info(result.toString());

} else if(result.getClass().getName().equals("java.util.ArrayList")){
LOGGER.info(result.toString());
}

}
public static void main(String[] args) {
LispCommands L = new LispCommands();
L.parse("[3, 0, 2, 5]");
L.car();
13
www.csetube.in

www.csetube.in

L.cdr();
L.cons("7");
}}

.c

se

tu

be

.in

Output:

Result:

Thus the above program was executed and verified successfully

14
www.csetube.in

www.csetube.in

Ex.No:4

Implementation of Stack ADT

AIM
To write a Java Program to design an interface for Stack ADT.and implement Stack ADT
using both Array and Linked List.

.c

se

tu

be

.in

Procedure:

15
www.csetube.in

www.csetube.in

Program:
public class ADTArray implements ADTStack
{
Object[] array;
int index;

.in

public ADTArray() {
this.array = new Object[128];
this.index = 0;
}

tu

se

//@Override
public void push(Object item) {
array[index] = item;
index++;
}

be

//@Override
public Object pop() {
index--;
return array[index];
}

.c

public static void main(String[] args) {


ADTStack stack = new ADTArray();
stack.push("Hi");
stack.push(new Integer(100));

System.out.println(stack.pop());
System.out.println(stack.pop());

public class ADTList implements ADTStack {

private StackElement top;


private int count = 0;

public void push(Object obj) {


StackElement stackElement = new StackElement(obj);
stackElement.next = top;
top = stackElement;
count++;
16
www.csetube.in

www.csetube.in

}
//@Override
public Object pop() {
if (top == null) return null;
Object obj = top.value;
top = top.next;
count--;
return obj;
}

.in

class StackElement {
Object value;
StackElement next;

be

public StackElement(Object obj) {


value = obj;
next = null;
}
}

se

tu

public static void main(String[] args) {


ADTStack stack = new ADTList();
stack.push("Hi");
stack.push(new Integer(100));

.c

System.out.println(stack.pop());
System.out.println(stack.pop());
}

public interface ADTStack {


public void push (Object item);
public Object pop ();
}

17
www.csetube.in

www.csetube.in

Output:-

C:\>java ADTArray
100
Hi

.c

se

tu

be

C:\>java ADTStack
Exception in thread main java.lang.NoSuchMethodError:main

.in

C:\>java ADTList
100
Hi

Result:
Thus the above program was executed and verified successfully.

18
www.csetube.in

www.csetube.in

Ex no: 5

Polymorphism

Aim:To develop a vehicle class hierarchy in Java to demonstrate the concept of polymorphism.

Algorithm:-

.in

Step 1:-Declare a super class called vehicle with data elements doors,wheels and seats.

Step 2:-Derive another class called car and invoke a function tostring() to display the variables.

be

Step 3:-Derive another class called motorcycle with same data and method called setseats() .

Step 4:-Declare another sub class called Truck with 2 constructors and finally assign values to

tu

variables.

se

Step 5:-In the main function, create an object for class motorcycle and display all details of sub classes

.c

through object.

19
www.csetube.in

www.csetube.in

Sourcecode:-

//This is the class that will be inherited


public class Vehicle
{
public int doors;
public int seats;

.in

public int wheels;


Vehicle()
{

be

wheels=4;
doors=4;
seats=4;

tu

//This class inherits Vehicle.java


public class Car extends Vehicle

public String toString()


{

.c

se

return "This car has "+seats+" Seats, "+doors+" Doors "+

"and "+wheels+" wheels.";

//This class inherits Vehicle.java


public class MotorCycle extends Vehicle
{
MotorCycle()
{
wheels=2;
doors=0;
seats=1;
}
20
www.csetube.in

www.csetube.in

void setSeats(int num)


{
seats=num;
}
public String toString()
{
return "This motorcycle has "+seats+" Seats, "+doors+" Doors "+
"and "+wheels+" wheels.";

.in

}
}
//This class inherits Vehicle.java

be

public class Truck extends Vehicle


{
boolean isPickup;

tu

Truck()
{

se

isPickup=true;
}
Truck(boolean aPickup)

.c

{
this();

isPickup=aPickup;

Truck(int doors, int seats, int inWheels, boolean isPickup)

this.doors=doors;
this.seats=seats;
wheels=inWheels;
this.isPickup=isPickup;

}
public String toString()
{
return "This "+(isPickup?"pickup":"truck")+
" has "+seats+" Seats, "+doors+" Doors "+"and "+wheels+" wheels.";
21
www.csetube.in

www.csetube.in

}
}
//This class tests the classes that inherit Vehicle.java
public class VehiclesTest
{
public static void main(String args[])
{
MotorCycle mine = new MotorCycle();

.in

System.out.println(mine);
Car mine2 = new Car();
System.out.println(mine2);

be

mine2.doors=2;
System.out.println(mine2);

System.out.println(mine3);
Truck mine4 = new Truck(false);

se

mine4.doors=2;

tu

Truck mine3 = new Truck();

System.out.println(mine4);

.c

22
www.csetube.in

www.csetube.in

Output

This motorcycle has 1 Seats, 0 Doors and 2 wheels


This car has 4 Seats, 4 Doors and 4 wheels
This car has 4 Seats, 2 Doors and 4 wheels
This pickup has 4 Seats, 4 Doors and 4 wheels

.c

se

tu

be

.in

This truck has 4 Seats, 2 Doors and 4 wheels

Result:

Thus the above program was executed and verified successfully.

23
www.csetube.in

www.csetube.in

Ex No:-6

Object Serialization

Aim:-To write a Java Program to randomly generate objects and write them into a file using concept

.in

of Object Serialization.

Algorithm:-

be

Step 1:Declare a class called Currency .Open a file in output mode with a name.

tu

Step 2:-Write new data into the object using writeobject() method.

Step 3:-Similarly create an input stream object .Read it both in terms of Dollars and Rupees.close the

se

output object.

.c

Step 4:-derive a class called Dollar which implements serializable interface.Invoke a constructor and

function to display the data.

Step 5:Similarly declare a class called Rupee with private variables and use print function to display

the variables.

Step 6: terminate the execution. The output is displayed as dollar to rupee conversion and vice versa.

Sourcecode:-

// Currency conversion
import java.io.*;
public class Currency
{
24
www.csetube.in

www.csetube.in

public static void main(String args[])


{
Dollar dr=new Dollar('$',40);
dr.printDollar();
Rupee re=new Rupee("Rs.",50);
re.printRupee();
try
{

FileOutputStream fos=new FileOutputStream(f);


ObjectOutputStream oos=new ObjectOutputStream(fos);

be

oos.writeObject(dr);

.in

File f=new File("rd.txt");

oos.writeObject(re);
oos.flush();

tu

oos.close();

Dollar d1;
d1=(Dollar)ois.readObject();

Rupee r1;

.c

d1.printDollar();

se

ObjectInputStream ois=new ObjectInputStream(new FileInputStream("rd.txt"));

r1=(Rupee)ois.readObject();

ois.close();

r1.printRupee();

catch(Exception e)
{
}

}
class Dollar implements Serializable
{
private float dol;
private char sym;
25
www.csetube.in

www.csetube.in

public Dollar(char sm,float doll)


{
sym=sm;
dol=doll;
}
void printDollar()
{

.in

System.out.print(sym);
System.out.println(dol);
}

be

}
class Rupee implements Serializable
{

tu

private String sym;


private float rs;

se

public Rupee(String sm,float rup)


{

rs=rup;
}

void printRupee()

.c

sym=sm;

System.out.print(sym);

System.out.println(rs);
}
}

Output:-

26
www.csetube.in

www.csetube.in

E:\java>java Currency
$40.0
Rs.50.0
$40.0

.c

se

tu

be

.in

Rs.50.0

Result:
Thus the above program was executed and verified successfully.

27
www.csetube.in

www.csetube.in

EX NO: 7

Scientific Calculator

AIM:
To design a scientific calculator using event-driven programming paradigm of Java.

ALGORITHM:

calculator

.in

Step1: Define a class CalcFrame for creating a calculator frame and added windolistener to close the

Step2: create instance of object for View menu and various other objects

Step3: add a listener to receive item events when the state of an item changes

be

Step4: Define the methods for all operations of stientific calculator

tu

Step5::Get the input and display the result

/** Scientific calculator*/

se

PROGRAM

.c

import java.awt.*;
import java.awt.event.*;
// class CalcFrame for creating a calculator frame and added windolistener to
// close the calculator
class CalcFrame extends Frame {
CalcFrame( String str) {
// call to superclass
super(str);
// to close the calculator(Frame)
addWindowListener(new WindowAdapter() {
public void windowClosing (WindowEvent we) {
System.exit(0);
}
});
}
}

// main class Calculator implemnets two


// interfaces ActionListener
// and ItemListener
public class Calculator implements ActionListener, ItemListener {
// creating instances of objects
28
www.csetube.in

www.csetube.in

be

// main function
public static void main (String args[]) {
// constructor
Calculator calc = new Calculator();
calc.makeCalculator();
}

.in

CalcFrame fr;
TextField display;
Button key[] = new Button[20]; // creates a button object array of 20
Button clearAll, clearEntry, round;
Button scientificKey[] = new Button[10]; // creates a button array of 8
// declaring variables
boolean addButtonPressed, subtractButtonPressed, multiplyButtonPressed;
boolean divideButtonPressed, decimalPointPressed, powerButtonPressed;
boolean roundButtonPressed = false;
double initialNumber;// the first number for the two number operation
double currentNumber = 0; // the number shown in the screen while it is being pressed
int decimalPlaces = 0;

.c

se

tu

public void makeCalculator() {


// size of the button
final int BWIDTH = 25;
final int BHEIGHT = 25;
int count =1;
// create frame for the calculator
fr = new CalcFrame("Scientific Calculator");
// set the size
fr.setSize(300,350);
fr.setBackground(Color.blue);;
fr.setLayout(null);
// set the initial numbers that is 1 to 9
for (int row = 0; row < 3; ++row) {
for (int col = 0; col < 3; ++col) {
// this will set the key from 1 to 9
key[count] = new Button(Integer.toString(count));
key[count].addActionListener(this);
// set the boundry for the keys
key[count].setBounds(30*(col + 1), 30*(row + 4),BWIDTH,BHEIGHT);
key[count].setBackground(Color.yellow);
// add to the frame
fr.add(key[count++]);
}
}
// Now create, addlistener and add to frame all other keys
//0
key[0] = new Button("0");
key[0].addActionListener(this);
key[0].setBounds(30,210,BWIDTH,BHEIGHT);
29
www.csetube.in

.c

se

tu

be

key[0].setBackground(Color.yellow);
fr.add(key[0]);
//decimal
key[10] = new Button(".");
key[10].addActionListener(this);
key[10].setBounds(60,210,BWIDTH,BHEIGHT);
key[10].setBackground(Color.yellow);
fr.add(key[10]);
//equals to
key[11] = new Button("=");
key[11].addActionListener(this);
key[11].setBounds(90,210,BWIDTH,BHEIGHT);
key[11].setBackground(Color.yellow);
fr.add(key[11]);
//multiply
key[12] = new Button("*");
key[12].addActionListener(this);
key[12].setBounds(120,120,BWIDTH,BHEIGHT);
key[12].setBackground(Color.yellow);
fr.add(key[12]);
//divide
key[13] = new Button("/");
key[13].addActionListener(this);
key[13].setBounds(120,150,BWIDTH,BHEIGHT);
key[13].setBackground(Color.yellow);
fr.add(key[13]);
//addition
key[14] = new Button("+");
key[14].addActionListener(this);
key[14].setBounds(120,180,BWIDTH,BHEIGHT);
key[14].setBackground(Color.yellow);
fr.add(key[14]);
//subtract
key[15] = new Button("-");
key[15].addActionListener(this);
key[15].setBounds(120,210,BWIDTH,BHEIGHT);
key[15].setBackground(Color.yellow);
fr.add(key[15]);
//reciprocal
key[16] = new Button("1/x");
key[16].addActionListener(this);
key[16].setBounds(150,120,BWIDTH,BHEIGHT);
key[16].setBackground(Color.yellow);
fr.add(key[16]);
//power
key[17] = new Button("x^n");
key[17].addActionListener(this);
key[17].setBounds(150,150,BWIDTH,BHEIGHT);
key[17].setBackground(Color.yellow);
fr.add(key[17]);

.in

www.csetube.in

30
www.csetube.in

www.csetube.in

.c

se

tu

be

.in

//change sign
key[18] = new Button("+/-");
key[18].addActionListener(this);
key[18].setBounds(150,180,BWIDTH,BHEIGHT);
key[18].setBackground(Color.yellow);
fr.add(key[18]);
//factorial
key[19] = new Button("x!");
key[19].addActionListener(this);
key[19].setBounds(150,210,BWIDTH,BHEIGHT);
key[19].setBackground(Color.yellow);
fr.add(key[19]);
// CA
clearAll = new Button("CA");
clearAll.addActionListener(this);
clearAll.setBounds(30, 240, BWIDTH+20, BHEIGHT);
clearAll.setBackground(Color.yellow);
fr.add(clearAll);
// CE
clearEntry = new Button("CE");
clearEntry.addActionListener(this);
clearEntry.setBounds(80, 240, BWIDTH+20, BHEIGHT);
clearEntry.setBackground(Color.yellow);
fr.add(clearEntry);
// round
round = new Button("Round");
round.addActionListener(this);
round.setBounds(130, 240, BWIDTH+20, BHEIGHT);
round.setBackground(Color.yellow);
fr.add(round);
// set display area
display = new TextField("0");
display.setBounds(30,90,150,20);
display.setBackground(Color.white);

// key for scientific calculator


// Sine
scientificKey[0] = new Button("Sin");
scientificKey[0].addActionListener(this);
scientificKey[0].setBounds(180, 120, BWIDTH + 10, BHEIGHT);
scientificKey[0].setVisible(true);
scientificKey[0].setBackground(Color.yellow);
fr.add(scientificKey[0]);
// cosine
scientificKey[1] = new Button("Cos");
scientificKey[1].addActionListener(this);
scientificKey[1].setBounds(180, 150, BWIDTH + 10, BHEIGHT);
scientificKey[1].setBackground(Color.yellow);
scientificKey[1].setVisible(true);
31
www.csetube.in

www.csetube.in

.c

se

tu

be

.in

fr.add(scientificKey[1]);
// Tan
scientificKey[2] = new Button("Tan");
scientificKey[2].addActionListener(this);
scientificKey[2].setBounds(180, 180, BWIDTH + 10, BHEIGHT);
scientificKey[2].setBackground(Color.yellow);
scientificKey[2].setVisible(true);
fr.add(scientificKey[2]);
// PI
scientificKey[3] = new Button("Pi");
scientificKey[3].addActionListener(this);
scientificKey[3].setBounds(180, 210, BWIDTH + 10, BHEIGHT);
scientificKey[3].setBackground(Color.yellow);
scientificKey[3].setVisible(true);
fr.add(scientificKey[3]);
// aSine
scientificKey[4] = new Button("aSin");
scientificKey[4].addActionListener(this);
scientificKey[4].setBounds(220, 120, BWIDTH + 10, BHEIGHT);
scientificKey[4].setBackground(Color.yellow);
scientificKey[4].setVisible(true);
fr.add(scientificKey[4]);
// aCos
scientificKey[5] = new Button("aCos");
scientificKey[5].addActionListener(this);
scientificKey[5].setBounds(220, 150, BWIDTH + 10, BHEIGHT);
scientificKey[5].setBackground(Color.yellow);
scientificKey[5].setVisible(true);
fr.add(scientificKey[5]);
// aTan
scientificKey[6] = new Button("aTan");
scientificKey[6].addActionListener(this);
scientificKey[6].setBounds(220, 180, BWIDTH + 10, BHEIGHT);
scientificKey[6].setBackground(Color.yellow);
scientificKey[6].setVisible(true);
fr.add(scientificKey[6]);
// E
scientificKey[7] = new Button("E");
scientificKey[7].addActionListener(this);
scientificKey[7].setBounds(220, 210, BWIDTH + 10, BHEIGHT);
scientificKey[7].setBackground(Color.yellow);
scientificKey[7].setVisible(true);
fr.add(scientificKey[7]);
// to degrees
scientificKey[8] = new Button("todeg");
scientificKey[8].addActionListener(this);
scientificKey[8].setBounds(180, 240, BWIDTH + 10, BHEIGHT);
scientificKey[8].setBackground(Color.yellow);
scientificKey[8].setVisible(true);
fr.add(scientificKey[8]);
32
www.csetube.in

www.csetube.in

// to radians
scientificKey[9] = new Button("torad");
scientificKey[9].addActionListener(this);
scientificKey[9].setBounds(220, 240, BWIDTH + 10, BHEIGHT);
scientificKey[9].setBackground(Color.yellow);
scientificKey[9].setVisible(true);
fr.add(scientificKey[9]);
fr.add(display);
fr.setVisible(true);
} // end of makeCalculator

.c

se

tu

be

.in

public void actionPerformed(ActionEvent ae) {


String buttonText = ae.getActionCommand();
double displayNumber = Double.valueOf(display.getText()).doubleValue();
// if the button pressed text is 0 to 9
if((buttonText.charAt(0) >= '0') & (buttonText.charAt(0) <= '9')) {
if(decimalPointPressed) {
for (int i=1;i <=decimalPlaces; ++i)
currentNumber *= 10;
currentNumber +=(int)buttonText.charAt(0)- (int)'0';
for (int i=1;i <=decimalPlaces; ++i) {
currentNumber /=10;
}
++decimalPlaces;
display.setText(Double.toString(currentNumber));
}
else if (roundButtonPressed) {
int decPlaces = (int)buttonText.charAt(0) - (int)'0';
for (int i=0; i< decPlaces; ++i)
displayNumber *=10;
displayNumber = Math.round(displayNumber);
for (int i = 0; i < decPlaces; ++i) {
displayNumber /=10;
}
display.setText(Double.toString(displayNumber));
roundButtonPressed = false;
}
else {
currentNumber = currentNumber * 10 + (int)buttonText.charAt(0)-(int)'0';
display.setText(Integer.toString((int)currentNumber));
}
}
// if button pressed is addition
if(buttonText == "+") {
addButtonPressed = true;
initialNumber = displayNumber;
currentNumber = 0;
decimalPointPressed = false;
}
33
www.csetube.in

www.csetube.in

// if button pressed is subtract


if (buttonText == "-") {
subtractButtonPressed = true;
initialNumber = displayNumber;
currentNumber = 0;
decimalPointPressed = false;
}

.in

// if button pressed is divide


if (buttonText == "/") {
divideButtonPressed = true;
initialNumber = displayNumber;
currentNumber = 0;
decimalPointPressed = false;
}

se

tu

be

// if button pressed is multiply


if (buttonText == "*") {
multiplyButtonPressed = true;
initialNumber = displayNumber;
currentNumber = 0;
decimalPointPressed = false;
}

.c

// if button pressed is reciprocal


if (buttonText == "1/x") {
// call reciprocal method
display.setText(reciprocal(displayNumber));
currentNumber = 0;
decimalPointPressed = false;
}

// if button is pressed to change a sign


//
if (buttonText == "+/-") {
// call changesign meyhod to change the
// sign
display.setText(changeSign(displayNumber));
currentNumber = 0;
decimalPointPressed = false;
}
// factorial button
if (buttonText == "x!") {
display.setText(factorial(displayNumber));
currentNumber = 0;
decimalPointPressed = false;
}

34
www.csetube.in

www.csetube.in

// power button
if (buttonText == "x^n") {
powerButtonPressed = true;
initialNumber = displayNumber;
currentNumber = 0;
decimalPointPressed = false;
}

.in

// now for scientific buttons


if (buttonText == "Sin") {
display.setText(Double.toString(Math.sin(displayNumber)));
currentNumber = 0;
decimalPointPressed = false;
}

be

if (buttonText == "Cos") {
display.setText(Double.toString(Math.cos(displayNumber)));
currentNumber = 0;
decimalPointPressed = false;
}

se

tu

if (buttonText == "Tan") {
display.setText(Double.toString(Math.tan(displayNumber)));
currentNumber = 0;
decimalPointPressed = false;
}

.c

if (buttonText == "aSin") {
display.setText(Double.toString(Math.asin(displayNumber)));
currentNumber = 0;
decimalPointPressed = false;

if (buttonText == "aCos") {
display.setText(Double.toString(Math.acos(displayNumber)));
currentNumber = 0;
decimalPointPressed = false;

if (buttonText == "aTan") {
display.setText(Double.toString(Math.atan(displayNumber)));
currentNumber = 0;
decimalPointPressed = false;

}
// this will convert the numbers displayed to degrees
if (buttonText == "todeg")
display.setText(Double.toString(Math.toDegrees(displayNumber)));
// this will convert the numbers display
// ed to radians
35
www.csetube.in

www.csetube.in

if (buttonText == "torad")
display.setText(Double.toString(Math.toRadians(displayNumber)));
if (buttonText == "Pi") {
display.setText(Double.toString(Math.PI));
currentNumber =0;
decimalPointPressed = false;
}

be

if (buttonText == ".") {
String displayedNumber = display.getText();
boolean decimalPointFound = false;
int i;
decimalPointPressed = true;
// check for decimal point

.in

if (buttonText == "Round")
roundButtonPressed = true;
// check if decimal point is pressed

tu

for (i =0; i < displayedNumber.length(); ++i) {

se

if(displayedNumber.charAt(i) == '.') {
decimalPointFound = true;
continue;
}

.c

if(buttonText == "CA"){
// set all buttons to false
resetAllButtons();
display.setText("0");
currentNumber = 0;

if (!decimalPointFound)
decimalPlaces = 1;

if (buttonText == "CE") {
display.setText("0");
currentNumber = 0;
decimalPointPressed = false;

}
if (buttonText == "E") {
display.setText(Double.toString(Math.E));
currentNumber = 0;
decimalPointPressed = false;
36
www.csetube.in

www.csetube.in

.in

// the main action


if (buttonText == "=") {
currentNumber = 0;
// if add button is pressed
if(addButtonPressed)
display.setText(Double.toString(initialNumber + displayNumber));
// if subtract button is pressed
if(subtractButtonPressed)
display.setText(Double.toString(initialNumber - displayNumber));
// if divide button is pressed
if (divideButtonPressed) {
// check if the divisor is zero
if(displayNumber == 0) {
MessageBox mb = new MessageBox ( fr, "Error ", true, "Cannot divide by
zero.");

be

mb.show();
}
else
display.setText(Double.toString(initialNumber/displayNumber));

tu

.c

se

// if multiply button is pressed


if(multiplyButtonPressed)
display.setText(Double.toString(initialNumber * displayNumber));
// if power button is pressed
if (powerButtonPressed)
display.setText(power(initialNumber, displayNumber));
// set all the buttons to false
resetAllButtons();

}
} // end of action events

public void itemStateChanged(ItemEvent ie)


{
} // end of itemState
// this method will reset all the button
// Pressed property to false
public void resetAllButtons() {
addButtonPressed = false;
subtractButtonPressed = false;
multiplyButtonPressed = false;
divideButtonPressed = false;
decimalPointPressed = false;
powerButtonPressed = false;
roundButtonPressed = false;
}

37
www.csetube.in

www.csetube.in

.in

public String factorial(double num) {


int theNum = (int)num;
if (theNum < 1) {
MessageBox mb = new MessageBox (fr, "Facorial Error", true,
"Cannot find the factorial of numbers less than 1.");
mb.show();
return ("0");
}
else {
for (int i=(theNum -1); i > 1; --i)
theNum *= i;
return Integer.toString(theNum);
}
}

se

tu

be

public String reciprocal(double num) {


if (num ==0) {
MessageBox mb = new MessageBox(fr,"Reciprocal Error", true,
"Cannot find the reciprocal of 0");
mb.show();
}
else
num = 1/num;
return Double.toString(num);
}

public String power (double base, double index) {


return Double.toString(Math.pow(base, index));

.c

}
}

public String changeSign(double num) {


return Double.toString(-num);

class MessageBox extends Dialog implements ActionListener {


Button ok;
MessageBox(Frame f, String title, boolean mode, String message) {
super(f, title, mode);
Panel centrePanel = new Panel();
Label lbl = new Label(message);
centrePanel.add(lbl);
add(centrePanel, "Center");
Panel southPanel = new Panel();
ok = new Button ("OK");
ok.addActionListener(this);
southPanel.add(ok);
add(southPanel, "South");
pack();
addWindowListener (new WindowAdapter() {
public void windowClosing (WindowEvent we) {
38
www.csetube.in

www.csetube.in

System.exit(0);
}
});
}
public void actionPerformed(ActionEvent ae) {
dispose();
}
}

.c

se

tu

be

.in

OUTPUT:

RESULT:
Thus a scientific calculator using even-driven programming paradigm of Java is
developed.

39
www.csetube.in

www.csetube.in

EX NO:-8

Multithreading

Aim:To write a multi-threaded Java program to print all numbers below 100,000 that are both prime
and Fibonacci number (some examples are 2, 3, 5, 13, etc.). Design a thread that generates prime
numbers below 100,000 and writes them into a pipe. Design another thread that generates fibonacci

.in

numbers and writes them to another pipe.The main thread should read both the pipes to identify
numbers common to both.

.c

se

tu

be

Procedure:

40
www.csetube.in

www.csetube.in

Program:
import java.io.IOException;
import java.io.PipedWriter;
public class FibonacciGenerator extends Thread {
private PipedWriter fibWriter = new PipedWriter();

.in

public PipedWriter getPipedWriter() {


return fibWriter;
}

be

@Override
public void run() {
super.run();
generateFibonacci();

se

private int f(int n) {


if (n < 2) {
return n;
}
else {
return f(n-1)+ f(n-2);
}
}

tu

/*do {

.c

public void generateFibonacci() {

fibValue = f(i);

System.out.println("From Fibo : " + fibValue);


try {
fibWriter.write(fibValue);
} catch (IOException e) {
e.printStackTrace();
}

i++;
} while(fibValue < 10000);
*/
for (int i = 2, fibValue = 0; (fibValue = f(i)) < 10000; i++) {
//System.out.println("From Fibo : " + fibValue);
try {
fibWriter.write(fibValue);
} catch (IOException e) {
// TODO Auto-generated catch block

41
www.csetube.in

www.csetube.in

e.printStackTrace();
}
}
//suspend();
}
public static void main(String[] args) {
new FibonacciGenerator().generateFibonacci();
}

.in

import java.io.IOException;
import java.io.PipedReader;

be

class Receiver extends Thread {


private PipedReader fibReader;
private PipedReader primeReader;

tu

public Receiver(FibonacciGenerator fib, PrimeGenerator prime)


throws IOException {

se

fibReader = new PipedReader(fib.getPipedWriter());


primeReader = new PipedReader(prime.getPipedWriter());
}

.c

public void run() {

int prime = 0;
int fib = 0;
try {
prime = primeReader.read();
fib = fibReader.read();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
while (true) {
//System.out.println("FROM PRIME PIPE ::" + prime);
//System.out.println("FROM FIB PIPE::" + fib);
try {
if (prime == fib) {
System.out.println("MATCH ::" + prime);
prime = primeReader.read();
fib = fibReader.read();
} else if (fib < prime) {
fib = fibReader.read();
} else {
prime = primeReader.read();
}
} catch (IOException e) {

42
www.csetube.in

www.csetube.in

System.exit(-1);
}
}
}
}

public class PrimeGenerator extends Thread {

be

private PipedWriter primeWriter = new PipedWriter();

se

tu

public PipedWriter getPipedWriter() {


return primeWriter;
}

@Override
public void run() {
super.run();
generatePrime();
}

.in

import java.io.IOException;
import java.io.PipedWriter;

.c

public void generatePrime() {


for (int i = 2; i < 10000; i++) {
if (isPrime(i)) {
try {
//System.out.println("From Prime : " + i);
primeWriter.write(i);
} catch (IOException e) {
e.printStackTrace();
}

}
}
//suspend();

private boolean isPrime(int n) {


boolean prime = true;
int sqrtValue = (int) Math.sqrt(n);
for (int i = 2; i <= sqrtValue; i++) {
if (n%i==0) {
prime = false;
}
}

43
www.csetube.in

www.csetube.in

return prime;
}

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


PrimeGenerator gene = new PrimeGenerator();
gene.generatePrime();
}

.in

import java.io.IOException;

be

public class Main {

se

tu

/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
FibonacciGenerator fibonacciGenerator = new FibonacciGenerator();
PrimeGenerator primeGenerator = new PrimeGenerator();
Receiver receiver = new Receiver(fibonacciGenerator, primeGenerator);

.c

fibonacciGenerator.start();
primeGenerator.start();
receiver.start();

/*fibonacciGenerator.stop();
primeGenerator.stop();
receiver.stop();*/

//fibonacciGenerator.run();

Output:
C:\jdk1.5\bin>javac FibonacciGenerator.java
C:\jdk1.5\bin>javac PrimeGenerator.java
C:\jdk1.5\bin>javac Receiver.java
C:\jdk1.5\bin>javac Main.java
44
www.csetube.in

www.csetube.in

MATCH ::2
MATCH ::3
MATCH ::5
MATCH ::13
MATCH ::89
MATCH ::233
MATCH ::1597

.c

se

tu

be

.in

C:\jdk1.5\bin>

Result:
Thus the above program was executed and verified successfully.

45
www.csetube.in

www.csetube.in

Ex.No: 9

A Simple OPAC system for library

Aim:To develop a simple OPAC System for library management system using event-driven and
concurrent programming paradigms and java database connectivity.

Algorithm:-

.in

Step 1:Initiate a class and declare the driver for the Driver name required to connect to the database.

be

Step 2:-Enclose the coding in a try block to handle errors and trap the exception in a catch block.

tu

Step 3:-Establish the connection object to connect to the backend.

se

Step 4:-Create an object for Statement object using createStatement() object.

.c

Step 5:-Issue a query through executeQuery() method.

Program

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

public class Datas extends JFrame implements ActionListener {


JTextField id;
JTextField name;
JButton next;
JButton addnew;
JPanel p;
static ResultSet res;
static Connection conn;
static Statement stat;
public Datas()
46
www.csetube.in

www.csetube.in

be

super("Our Application");
Container c = getContentPane();
c.setLayout(new GridLayout(5,1));
id = new JTextField(20);
name = new JTextField(20);
next = new JButton("Next BOOK");
p = new JPanel();
c.add(new JLabel("ISBN",JLabel.CENTER));
c.add(id);
c.add(new JLabel("Book Name",JLabel.CENTER));
c.add(name);
c.add(p);
p.add(next);
next.addActionListener(this);
pack();
setVisible(true);
addWindowListener(new WIN());

.in

tu

.c

se

public static void main(String args[]) {


Datas d = new Datas();
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn = DriverManager.getConnection("jdbc:odbc:custo"); // cust is the DSN
Name
stat = conn.createStatement();
res = stat.executeQuery("Select * from stu"); // Customers is
the table name
res.next();

}
catch(Exception e) {
System.out.println("Error" +e);
}
d.showRecord(res);
}

public void actionPerformed(ActionEvent e) {


if(e.getSource() == next) {
try {
res.next();
}
catch(Exception ee) {}
showRecord(res);
}
}
public void showRecord(ResultSet res) {
try {
47
www.csetube.in

www.csetube.in

id.setText(res.getString(2));
name.setText(res.getString(3));
}
catch(Exception e) {}
}//end of the main

.in

//Inner class WIN implemented


class WIN extends WindowAdapter {
public void windowClosing(WindowEvent w) {
JOptionPane jop = new JOptionPane();
jop.showMessageDialog(null,"Database","Thanks",JOptionPane.QUESTION_MESSAGE);
}
} //end of the class

se

tu

be

.c

Output:

48
www.csetube.in

.c

se

tu

be

.in

www.csetube.in

49
www.csetube.in

www.csetube.in

Concurrent

tu

be

.in

import java.sql.*;
import java.sql.DriverManager.*;
class Ja
{
String bookid,bookname;
int booksno;
Connection con;
Statement stmt;
ResultSet rs;
Ja()
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:co");
}
catch(Exception e)
{
System.out.println("connection error");
}
}

se

void myput()
{
try
{

.c

stmt=con.createStatement();
rs=stmt.executeQuery("SELECT * FROM opac");
while(rs.next())
{
booksno=rs.getInt(1);
bookid=rs.getString(2);
bookname=rs.getString(3);
System.out.println("\n"+ booksno+"\t"+bookid+"\t"+bookname);
}
rs.close();
stmt.close();
con.close();

}
catch(SQLException e)
{
System.out.println("sql error");
}

}
}
class prog1
{
public static void main(String arg[])
50
www.csetube.in

www.csetube.in

{
Ja j=new Ja();
j.myput();
}
}

.c

se

tu

be

.in

Output:

Result:
Thus the above program was executed and verified successfully.

51
www.csetube.in

www.csetube.in

Ex.No:

10 Multi-threaded echo server GUI clients

Aim:To develop a Java Program that supports multithreaded echo server and a GUI client.

.c

se

tu

be

.in

Procedure:

Program:

/**************PROGRAM FOR MULTI-THREADED ECHO SERVER********************/


/******************************* chatclient .java**********************************/

import java.awt.*;
import java.awt.event.*;
import java.io.*; import java.net.*;
class chatclient extends Frame implements ActionListener,Runnable
{
TextArea ta;
TextField tf;
BufferedReader br;
PrintWriter pw;
public static void main(String args[])
{
52
www.csetube.in

www.csetube.in

.c

se

tu

be

}
chatclient(String title,String address,int port)
{
super(title);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}
);
ta=new TextArea(10,60);
ta.setEditable(false);
add(ta,BorderLayout.CENTER);
tf=new TextField(" ",10);
tf.addActionListener(this);
add(tf,BorderLayout.SOUTH);
try
{
Socket s=new Socket(address,port);
InputStream is=s.getInputStream();
InputStreamReader isr=new InputStreamReader(is);
br=new BufferedReader(isr);
OutputStream os=s.getOutputStream();
pw=new PrintWriter(os,true);
}
catch(Exception e)
{
System.out.println(e);
}

.in

chatclient cc=new chatclient("ChatClient",args[0],4040);


cc.show();
cc.setSize(300,400);

Thread thread=new Thread(this);


thread.start();
}
public void actionPerformed(ActionEvent ae)
{
try { String str=tf.getText();
pw.println(str); tf.setText(" ");
}
catch(Exception e)
{
System.out.println(e);
}
}
public void run()
{
53
www.csetube.in

www.csetube.in

tu

be

.in

try
{
while(true)
{
String str=br.readLine();
ta.append(str+"\n");
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}

.c

se

/*************************** chatserver.java***********************************/
import java.net.*;
import java.util.*;
class chatserver
{
static Vector serverthreads;
public static void main(String args[])
{
try
{
serverthreads=new Vector();
ServerSocket ss=new ServerSocket(4040);
while(true)
{
Socket s=ss.accept();
serverthread st=new serverthread(s);
st.start();
serverthreads.addElement(st);
}
}
catch(Exception e)
{
System.out.println(e);
}
}
public synchronized static void echoAll(String str)
{
54
www.csetube.in

www.csetube.in

tu

be

.in

Enumeration e=serverthreads.elements();
while(e.hasMoreElements())
{
try
{
serverthread st=(serverthread)e.nextElement();
st.echo(str);
}
catch(Exception ae)
{
System.out.println(ae);
}
}
}
}

.c

se

/****************************** serverthread.java*********************************/
import java.io.*;
import java.net.*;
class serverthread extends Thread
{
private BufferedReader br;
private PrintWriter pw;
public serverthread(Socket socket)
{
try
{
InputStream is=socket.getInputStream();
InputStreamReader isr=new InputStreamReader(is);
br=new BufferedReader(isr); OutputStream os=socket.getOutputStream();
pw=new PrintWriter(os,true);
}
catch(Exception e)
{
System.out.println(e);
}
}
public void run()
{
try
{
while(true)
{
55
www.csetube.in

www.csetube.in

String str=br.readLine();
chatserver.echoAll(str);

se

tu

be

.in

}
}
catch(Exception e)
{
System.out.println(e);
}
}
public void echo(String str)
{
try
{
pw.println(str);
}
catch(Exception e)
{
System.out.println(e);
}
}
}

.c

OUTPUT:

D:\ Java\jdk1.5.0_03\bin>javac ServerThread.java

D:\ Java\jdk1.5.0_03\bin>javac chatserver.java

D:\Java\jdk1.5.0_03\bin>java chatserver
D:\Java\jdk1.5.0_03\bin>javac chatclient.java

D:\Java\jdk1.5.0_03\bin>java chatclient 192.168.15.143


D:\Java\jdk1.5.0_03\bin>java chatclient 192.168.15.143
D:\Java\jdk1.5.0_03\bin>java chatclient 192.168.15.143

56
www.csetube.in

.c

se

tu

be

.in

www.csetube.in

Result:
Thus the above program was executed and verified successfully.

57
www.csetube.in

www.csetube.in

MiniProject
Aim:

To Develop a programmer's editor in Java that supports syntax highlighting,


compilation support, debugging support, etc
Program:

.c

se

tu

be

.in

/*********************** PROGAMMERS EDITOR IN JAVA************************/ /*


Client Frame Design with width=600 & height=500*/
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.InputStreamReader;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.text.Element;
import java.util.StringTokenizer;
public class Client implements ActionListener,MouseListener,MouseMotionListener
{
/************ Components *****************/
JFrame frame;
JTextArea jta1;
public JTextArea jta2;
JTextArea jta3;
JButton jb1;
JButton jb2;
JButton jb3;
JButton jb4;
JLabel jl1;
JLabel jl2;
JLabel jl3;
JScrollPane jsp1;
JScrollPane jsp2;
JScrollPane jsp3;
JTabbedPane jtp1;
JTabbedPane jtp2;
JTabbedPane jtp3;
JMenuBar jm;
JMenu open;

58
www.csetube.in

.c

se

tu

be

JMenu exit;
JMenu file;
JMenu help;
JMenu compile;
JMenu run;
JMenu opt;
/************ Variables *****************/
String line;
String option;
String className;
String pureFile;
File f2;
File f3;
public Client()
{
frame=new JFrame("XDoS Compiler");
frame.setLayout(null);
frame.setBounds(300,10,200,200);
frame.setSize(900,650);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jta1=new JTextArea(300,400);
jsp1=new JScrollPane(jta1);
jsp1.setBounds(10, 10, 670, 200);
jsp1.setEnabled(false);
Border etchedBdr1 = BorderFactory.createEtchedBorder();
jta1.setBorder(etchedBdr1); //frame.add(jsp1);
jta2=new JTextArea(300,400);
jsp2=new JScrollPane(jta2);
jsp2.setBounds(10, 280, 670, 150);
Border etchedBdr2 = BorderFactory.createEtchedBorder();
jta2.setBorder(etchedBdr2);
jta2.setEditable(false);
//frame.add(jsp2);
jta3=new JTextArea(300,400);
jsp3=new JScrollPane(jta3);
jsp3.setBounds(10, 450, 670, 150);
Border etchedBdr3 = BorderFactory.createEtchedBorder();
jta3.setBorder(etchedBdr3);
//frame.add(jsp3);
jl1=new JLabel();
jl1.setBounds(500, 380, 670, 150);
frame.add(jl1);
jl2=new JLabel();
jl2.setBounds(550, 380, 670, 150);
frame.add(jl2);
jl3=new JLabel();
jl3.setBounds(600, 380, 670, 150);
frame.add(jl3);
jb1=new JButton("Browse");
jb1.setBounds(50, 235, 100, 20);
jb1.addActionListener(this);
//frame.add(jb1);

.in

www.csetube.in

59
www.csetube.in

be

.c

se

tu

jb2=new JButton("compile");
jb2.setBounds(200, 235, 100, 20);
jb2.addActionListener(this);
//frame.add(jb2); jb3=new JButton("Send");
jb3.setBounds(550, 235, 100, 20);
jb3.addActionListener(this);
//frame.add(jb3);
jb4=new JButton("Run");
jb4.setBounds(400, 235, 100, 20);
jb4.addActionListener(this);
//frame.add(jb4);
jtp1=new JTabbedPane();
jtp1.addTab( "untitled.java", jsp1 );
jtp1.setBounds(10, 40, 670, 400);
UIManager.put("TabbedPane.selected", Color.green);
jtp1.set ForegroundAt(0,Color.BLUE);
jtp1.setBackgroundAt(0,Color.BLUE);
frame.add(jtp1); jtp2=new JTabbedPane();
jtp2.addTab( "Result", jsp2 );
jtp2.setBounds(10, 450, 670, 150);
frame.add(jtp2); jtp3=new JTabbedPane();
jtp3.addTab( "Reply", jsp3 );
jtp3.setBounds(700, 40, 180, 560);
frame.add(jtp3); jm=new JMenuBar();
file=new JMenu("File");
file.setMnemonic('F');
opt=new JMenu("Option");
opt.setMnemonic('O');
opt.setEnabled(false);
jm.add(file);

.in

www.csetube.in

jm.add(opt);
compile=new JMenu("Compile");
compile.setMnemonic('C');
Action action3 = new AbstractAction("Compile")
{
public void actionPerformed(ActionEvent e)
{
compile();
}
};
JMenuItem item3 = file.add(action3);
opt.add(item3);
run=new JMenu("Run");
run.setMnemonic('R');
Action action4 = new AbstractAction("Run")
{
public void actionPerformed(ActionEvent e)
{
run();
}
};

60
www.csetube.in

JMenuItem item4 = file.add(action4);


opt.add(item4); help=new JMenu("Help");
jm.add(help); open=new JMenu("open");
Action action1 = new AbstractAction("Open")
{
public void actionPerformed(ActionEvent e)
{ open(); } };
JMenuItem item1 = file.add(action1);
file.add(item1); exit=new JMenu("Exit");
Action action2 = new AbstractAction("Exit")
{
public void actionPerformed(ActionEvent e)
{
System.exit(0); } };
JMenuItem item2 = file.add(action2);

.c

se

tu

be

file.add(item2);
jm.setBounds(5, 0, 880, 30);
frame.add(jm);
frame.setResizable(false);
frame.setVisible(true);
jta1.addMouseListener(this);
jta1.addMouseMotionListener(this);
jtp1.addMouseListener(this); jtp2.addMouseListener(this);
}
public void mouseClicked(MouseEvent ew)
{
if(ew.getSource()==jta1)
{
jl3.setText("Line-No: "+Integer.toString(getCurrentLineNumber()));
}
else if(ew.getSource()==jtp2)
{
if(jtp1.isShowing())
{
frame.remove(jtp1);
jtp2.setBounds(10, 40, 670, 560);
jl1.setBounds(500, 535, 670, 150);
jl2.setBounds(550, 535, 670, 150);
jl3.setBounds(600, 535, 670, 150);
jta2.addMouseMotionListener(this);
jl3.setText("Line-No: "+Integer.toString(getCurrentLineNumber()));
}
else { frame.add(jtp1);
jtp2.setBounds(10, 450, 670, 150);
jl1.setBounds(500, 380, 670, 150);
jl2.setBounds(550, 380, 670, 150);
jl3.setBounds(600, 380, 670, 150);
jta2.removeMouseMotionListener(this);
}}
else if(ew.getSource()==jtp1)

.in

www.csetube.in

61
www.csetube.in

www.csetube.in

be

.c

se

tu

}
else { frame.add(jtp2); frame.add(jtp3);
jtp1.setBounds(10, 40, 670, 400);
jl1.setBounds(500, 380, 670, 150);
jl2.setBounds(550, 380, 670, 150);
jl3.setBounds(600, 380, 670, 150); } } }
public void mouseEntered(MouseEvent ew)
{} public void mouseExited(MouseEvent ew) {}
public void mousePressed(MouseEvent ew) {}
public void mouseReleased(MouseEvent ew) {}
public void mouseMoved(MouseEvent e)
{ jl1.setText("X-: "+Integer.toString(e.getX()));
jl2.setText("Y-: "+Integer.toString(e.getY())); }
public void mouseDragged(MouseEvent e) {}
public void actionPerformed(ActionEvent ae) {}
public void open()
{
JFileChooser fileChooser = new JFileChooser();
fileChooser.addChoosableFileFilter(new MyFilter());
int select=fileChooser.showOpenDialog(frame);
if(select==JFileChooser.APPROVE_OPTION) {
File file=fileChooser.getSelectedFile();
String filename=fileChooser.getSelectedFile().getName();
try { FileInputStream fis=new FileInputStream(file);
int n=fis.available(); byte dat[]=new byte[n];
fis.read(dat); String data=new String(dat);
jtp1.setTitleAt(0, filename);
jta1.setText(data); opt.setEnabled(true); }
catch(Exception e)
{ e.printStackTrace(); } }

.in

{
if(jtp2.isShowing())
{ frame.remove(jtp2);
frame.remove(jtp3); jtp1.setBounds(10, 40, 870, 560);
jl1.setBounds(500, 535, 670, 150);
jl2.setBounds(550, 535, 670, 150);
jl3.setBounds(600, 535, 670, 150);

}
public int getCurrentLineNumber()
{
int line;
int caretPosition = jta1.getCaretPosition();
Element root = jta1.getDocument().getDefaultRootElement();
line = root.getElementIndex(caretPosition) + 1; return line;
}
public void compile() { try { jtp2.setTitleAt(0,"Compile");
String ta1=jta1.getText().trim();
StringBuffer sb=new StringBuffer(ta1);
int id1=ta1.indexOf("public class");
int id2=ta1.indexOf(" ",id1+13);

62
www.csetube.in

www.csetube.in

tu

be

.in

String name=ta1.substring(id1, id2).trim();


StringTokenizer st3=new StringTokenizer(name,"\n");
System.out.println(st3.countTokens());
String word=st3.nextToken().toString().trim(); System.out.println(word+"*");
StringTokenizer st4=new StringTokenizer(word," "); System.out.println(st4.countTokens());
st4.nextToken(); st4.nextToken();
pureFile=st4.nextToken().toString().trim();
className=pureFile+".java"; //System.out.println(st4.nextElement().toString().trim()+"*");
FileOutputStream f=new FileOutputStream(className);
f.write(ta1.getBytes());
f.close();
f2=new File(className); f3=new File(pureFile+".class");
System.out.println(f2.getAbsolutePath());
String path=f2.getAbsolutePath(); int a1=path.indexOf("\\");
int a2=path.lastIndexOf("\\");
System.out.println(a1+" "+a2);
String colan=path.substring(0, a1).trim();
String location=path.substring(0, a2+1).trim();
System.out.println(colan);
System.out.println(location);
compiler(className); }

.c

se

catch (Exception err)


{ err.printStackTrace();
} //option=JOptionPane.showInputDialog(null,"Enter Destination System
Name","Destination",1).toString(); //System.out.println(option); // jta2.setText(line); }
public void run() { jtp2.setTitleAt(0,"Run");
runer(pureFile); }
public static void main(String args[])
{
try
{
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
}
catch (Exception e) { } new Client(); }
public void compiler(String name)
{ try { jta2.setText("");
jta2.append("Compilation Started.....\n");
jta2.append("Proceed.....\n");
jta2.setForeground(Color.blue);
String callAndArgs= "cmd /c compile.bat "+name; Process p =Runtime.getRuntime().exec(callAndArgs);
BufferedReader br=new BufferedReader(new InputStreamReader(p.getInputStream()));
String str=br.readLine();
while(str!=null)
{
System.out.println(str);
str=br.readLine(); }
File f1 = new File("error.txt");
FileReader fr = new FileReader(f1);
BufferedReader br1 = new BufferedReader(fr);

63
www.csetube.in

www.csetube.in

.c

se

tu

be

.in

StringBuffer sb1 = new StringBuffer();


String eachLine = br1.readLine();
while (eachLine != null)
{
jta2.setForeground(Color.RED);
sb1.append(eachLine);
sb1.append("\n");
eachLine= br1.readLine(); }
jta2.append(sb1.toString());
//input.close(); if(f1.length()==0)
{
jta2.append("Compiled Successfully........\n");
jta2.append("Done........"); } } catch(Exception e)
{ e.printStackTrace(); } }
public void runer(String name)
{
try { jta3.setText("");
String callAndArgs= "cmd /c run.bat "+name;
Process p =Runtime.getRuntime().exec(callAndArgs);
BufferedReader br=new BufferedReader(new InputStreamReader(p.getInputStream())); String
str=br.readLine(); while(str!=null)
{
System.out.println(str); str=br.readLine();
}
File f1 = new File("output.txt");
FileReader fr = new FileReader(f1);
BufferedReader br1 = new BufferedReader(fr);
StringBuffer sb1 = new StringBuffer();
String eachLine = br1.readLine();
while (eachLine != null)
{
sb1.append(eachLine);
sb1.append("\n");
eachLine = br1.readLine();
}
String sp=sb1.toString();
StringBuffer st=new StringBuffer(sp);
System.out.println(st.length()); int indx=sp.indexOf(">"); int r=1;
while(indx != -1)
{
System.out.println(Integer.toString(indx)+"*");
System.out.println(st);
st.insert(indx+r, "\n");
indx=sp.indexOf(">",indx+1);
r++;
System.out.println(Integer.toString(indx)+"#");
}
jta2.setText(st.toString()); f2.deleteOnExit();
f3.deleteOnExit(); }
catch(Exception e)
{ e.printStackTrace(); } } }

64
www.csetube.in

www.csetube.in

be

.c

se

tu

/* Test Frame Design */


import javax.swing.*;
import java.awt.*;
public class Test {
public Test() { JFrame f = new JFrame("Test");
f.setLayout(new FlowLayout());
JTextField jt1 = new JTextField(25);
f.add(jt1); f.setVisible(true);
f.setSize(200,200);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String args[])
{
new Test();
}
}

.in

class MyFilter extends javax.swing.filechooser.FileFilter


{
public boolean accept(File file)
{
return file.isDirectory() || file.getName().endsWith(".java");
}
public String getDescription()
{ return "*.java"; } }

OUTPUT:

D:\ Java\jdk1.5.0_03\bin>javac Client.java


D:\ Java\jdk1.5.0_03\bin>javac Test.java
D:\ Java\jdk1.5.0_03\bin>java Test
D:\ Java\jdk1.5.0_03\bin>java Client

65
www.csetube.in

.c

se

tu

be

.in

www.csetube.in

Result:
Thus the above program was executed and verified successfully.

66
www.csetube.in

You might also like