Professional Documents
Culture Documents
in
tu
be
.in
se
.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
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.
.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:
.in
30 Nodes
SOFTWARE:
be
.c
se
tu
30 user license
3
www.csetube.in
www.csetube.in
TABLE OF CONTENTS
Rational number
Java interface for ADT Stack using array and the sing linked-
Polymorphism
object serialization
scientific calculator
se
be
list.
tu
.in
LIST OF EXPERIMENTS
.c
10
11
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.
se
.c
Program:-
import java.io.*;
class rational1
public rational1(){}
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
be
String str;
tu
str=in.readLine();
a=Integer.parseInt(str);
str=in.readLine();
se
.c
b=Integer.parseInt(str);
long l=r.gcd(a,b);
System.out.println();
y=b/l;
System.out.println();
System.out.println("The resultant value is: "+x+"/"+y);
}
}
6
www.csetube.in
www.csetube.in
Output
.in
500
Enter the value for B
be
1000
.c
se
tu
Result
Thus the above program was executed and verified successfully.
7
www.csetube.in
www.csetube.in
Ex No 2:
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
be
tu
System.out.println();
se
.c
www.csetube.in
D:\java>java DateExample
be
.in
OUTPUT
tu
se
.c
Result
Thus the above program was executed and verified successfully.
10
www.csetube.in
www.csetube.in
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;
be
se
tu
public LispCommands() {
.c
LOGGER.info(tokenList[0]);
www.csetube.in
.in
while (commaTokens.hasMoreElements()) {
String token = commaTokens.nextToken();
be
tokenList.add(token.trim());
}
se
tu
.c
} 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:
14
www.csetube.in
www.csetube.in
Ex.No:4
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
System.out.println(stack.pop());
System.out.println(stack.pop());
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
se
tu
.c
System.out.println(stack.pop());
System.out.println(stack.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:-
.in
be
wheels=4;
doors=4;
seats=4;
tu
.c
se
www.csetube.in
.in
}
}
//This class inherits Vehicle.java
be
tu
Truck()
{
se
isPickup=true;
}
Truck(boolean aPickup)
.c
{
this();
isPickup=aPickup;
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
System.out.println(mine4);
.c
22
www.csetube.in
www.csetube.in
Output
.c
se
tu
be
.in
Result:
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
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
be
oos.writeObject(dr);
.in
oos.writeObject(re);
oos.flush();
tu
oos.close();
Dollar d1;
d1=(Dollar)ois.readObject();
Rupee r1;
.c
d1.printDollar();
se
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
.in
System.out.print(sym);
System.out.println(dol);
}
be
}
class Rupee implements Serializable
{
tu
se
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
tu
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);
}
});
}
}
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
.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);
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
www.csetube.in
.in
se
tu
be
.c
34
www.csetube.in
www.csetube.in
// power button
if (buttonText == "x^n") {
powerButtonPressed = true;
initialNumber = displayNumber;
currentNumber = 0;
decimalPointPressed = false;
}
.in
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
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
be
mb.show();
}
else
display.setText(Double.toString(initialNumber/displayNumber));
tu
.c
se
}
} // end of action events
37
www.csetube.in
www.csetube.in
.in
se
tu
be
.c
}
}
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
be
@Override
public void run() {
super.run();
generateFibonacci();
se
tu
/*do {
.c
fibValue = f(i);
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
tu
se
.c
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);
}
}
}
}
be
se
tu
@Override
public void run() {
super.run();
generatePrime();
}
.in
import java.io.IOException;
import java.io.PipedWriter;
.c
}
}
//suspend();
43
www.csetube.in
www.csetube.in
return prime;
}
.in
import java.io.IOException;
be
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
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
se
.c
Program
import java.sql.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
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
}
catch(Exception e) {
System.out.println("Error" +e);
}
d.showRecord(res);
}
www.csetube.in
id.setText(res.getString(2));
name.setText(res.getString(3));
}
catch(Exception e) {}
}//end of the main
.in
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:
Aim:To develop a Java Program that supports multithreaded echo server and a GUI client.
.c
se
tu
be
.in
Procedure:
Program:
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
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>java chatserver
D:\Java\jdk1.5.0_03\bin>javac chatclient.java
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:
.c
se
tu
be
.in
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
.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
.c
se
63
www.csetube.in
www.csetube.in
.c
se
tu
be
.in
64
www.csetube.in
www.csetube.in
be
.c
se
tu
.in
OUTPUT:
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