0% found this document useful (0 votes)
28 views45 pages

Java Lab File-Chakshit Gaur

Uploaded by

chakshitgaur25
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
28 views45 pages

Java Lab File-Chakshit Gaur

Uploaded by

chakshitgaur25
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 45

A

Lab File / Report


of

Java Programming Lab

(LC-CSE-327G)
[In the partial fulfillment of third Years BTech(Computer Science & Engg.) course]

Submitted By: Submitted To:


Chakshit Gaur Dr. jyoti
Reg.no-191250320 Professor
BTech(CSE)-5rd Sem Deptt. Of Computer Science

2021

Department of Computer Science & Engineering


DPG Institute of Technology & Management, Gurgaon(HR)
Maharishi Dayanand University, Rohtak(HR)
Python Programs Index
Sr. Program Page NO. Remarks
No.

1
Create a java program to implement stack and queue
concept.

2
Write a java package to show dynamic polymorphism
and interfaces.

3
Write a java program to show multithreaded producer
and consumer application.

4
Create a customized exception and also make use of
all the 5 exception keyword.

5
Convert the content of a given file into the upper case
content of the same file.

6
Develop an analog clock using applet.

7
Develop a scientific calculator using swing.

8
Create an editor like MS-word using swings.

9
Create a servelet that uses cookies to store the number
of times a user has visited your servlet.

10
Create a simple java bean having bound and
constrained properties.
PROGRAM.1- Create a java program to implement stack and queue
concept.
THEORY- The class is based on the basic principle of last-in-first-
out. In addition to the basic push and pop operations, the class
provides three more functions of empty, search, and peek. The class can
also be said to extend Vector and treats the class as a stack with the
five mentioned functions. The class can also be referred to as the
subclass of Vector.
PROGRAM-
// Java code for stack implementation

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

class Test
{
// Pushing element on the top of the stack
static void stack_push(Stack<Integer> stack)
{
for(int i = 0; i < 5; i++)
{
stack.push(i);
}
}

// Popping element from the top of the stack


static void stack_pop(Stack<Integer> stack)
{
System.out.println("Pop Operation:");

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


{
Integer y = (Integer) stack.pop();
System.out.println(y);
}
}

// Displaying element on the top of the stack


static void stack_peek(Stack<Integer> stack)
{
Integer element = (Integer) stack.peek();
System.out.println("Element on stack top: " + element);
}

// Searching element in the stack


static void stack_search(Stack<Integer> stack, int element)
{
Integer pos = (Integer) stack.search(element);

if(pos == -1)
System.out.println("Element not found");
else
System.out.println("Element is found at position: " +
pos);
}

public static void main (String[] args)


{
Stack<Integer> stack = new Stack<Integer>();

stack_push(stack);
stack_pop(stack);
stack_push(stack);
stack_peek(stack);

stack_search(stack, 2);
stack_search(stack, 6);
}
}
Output-

THEORY- The Queue interface present in the java.util package and


extends the Collection interface is used to hold the elements about to
be processed in FIFO(First In First Out) order. It is an ordered list
of objects with its use limited to insert elements at the end of the
list and deleting elements from the start of the list, (i.e.), it
follows the FIFO or the First-In-First-Out principle.
PROGRAM-
// Java program to demonstrate a Queue
import java.util.LinkedList;
import java.util.Queue;

public class QueueExample {

public static void main(String[] args)


{
Queue<Integer> q
= new LinkedList<>();

// Adds elements {0, 1, 2, 3, 4} to


// the queue
for (int i = 0; i < 5; i++)
q.add(i);

// Display contents of the queue.


System.out.println("Elements of queue "
+ q);

// To remove the head of queue.


int removedele = q.remove();
System.out.println("removed element-"
+ removedele);

System.out.println(q);

// To view the head of queue


int head = q.peek();
System.out.println("head of queue-"
+ head);

// Rest all methods of collection


// interface like size and contains
// can be used with this

// implementation.
int size = q.size();
System.out.println("Size of queue-"+ size);
}
}

Output-

PROGRAM.2- Write a java package to show dynamic polymorphism and


interfaces.
THEORY- Dynamic polymorphism is a process or mechanism in which a call
to an overridden method is to resolve at runtime rather than compile-
time. It is also known as runtime polymorphism or dynamic method
dispatch. ... In this process, an overridden method is called through a
reference variable of a superclass.
PROGRAM-
// A Java program to illustrate Dynamic Method
class A
{
void m1()
{
System.out.println("Inside A's m1 method");
}
}

class B extends A
{
// overriding m1()
void m1()
{
System.out.println("Inside B's m1 method");
}
}

class C extends A
{
// overriding m1()
void m1()
{
System.out.println("Inside C's m1 method");
}
}

// Driver class
class Dispatch
{
public static void main(String args[])
{
// object of type A

A a = new A();

// object of type B
B b = new B();
// object of type C
C c = new C();

// obtain a reference of type A


A ref;

// ref refers to an A object


ref = a;

// calling A's version of m1()


ref.m1();

// now ref refers to a B object


ref = b;

// calling B's version of m1()


ref.m1();

// now ref refers to a C object


ref = c;

// calling C's version of m1()


ref.m1();
}
}
Output-

THEORY- Like a class, an interface can have methods and variables,


but the methods declared in an interface are by default abstract (only
method signature, no body).
Interfaces specify what a class must do and not how. It is the
blueprint of the class.
An Interface is about capabilities like a Player may be an interface
and any class implementing Player must be able to (or must implement)
move(). So it specifies a set of methods that the class has to
implement.
If a class implements an interface and does not provide method bodies
for all functions specified in the interface, then the class must be
declared abstract.
PROGRAM-
// Java program to demonstrate working of
// interface.
import java.io.*;
// A simple interface
interface In1
{
// public, static and final
final int a = 10;

// public and abstract


void display();
}

// A class that implements the interface.


class TestClass implements In1
{
// Implementing the capabilities of
// interface.
public void display()
{
System.out.println("Hello");
}

// Driver Code
public static void main (String[] args)
{
TestClass t = new TestClass();
t.display();
System.out.println(a);
}
}
Output-

PROGRAM.3- Write a java program to show multithreaded producer and


consumer application.
THEORY- In computing, the producer-consumer problem (also known as the
bounded-buffer problem) is a classic example of a multi-process
synchronization problem. The problem describes two processes, the producer and
the consumer, which share a common, fixed-size buffer used as a queue.
The producer’s job is to generate data, put it into the buffer, and start
again.
At the same time, the consumer is consuming the data (i.e. removing it from
the buffer), one piece at a time.
PROGRAM-
// Java program to implement application of producer
// consumer.

import java.util.LinkedList;

public class Threadexample {


public static void main(String[] args)
throws InterruptedException
{
// Object of a class that has both produce()
// and consume() methods
final PC pc = new PC();

// Create producer thread


Thread t1 = new Thread(new Runnable() {
@Override
public void run()
{
try {
pc.produce();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
});

// Create consumer thread


Thread t2 = new Thread(new Runnable() {
@Override
public void run()
{
try {
pc.consume();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
});

// Start both threads


t1.start();
t2.start();

// t1 finishes before t2
t1.join();
t2.join();
}
// This class has a list, producer (adds items to list
// and consumer (removes items).
public static class PC {

// Create a list shared by producer and consumer


// Size of list is 2.
LinkedList<Integer> list = new LinkedList<>();
int capacity = 2;

// Function called by producer thread


public void produce() throws InterruptedException
{
int value = 0;
while (true) {
synchronized (this)
{
// producer thread waits while list
// is full
while (list.size() == capacity)
wait();

System.out.println("Producer produced-"
+ value);

// to insert the jobs in the list


list.add(value++);

// notifies the consumer thread that


// now it can start consuming
notify();

// makes the working of program easier


// to understand
Thread.sleep(1000);
}
}
}

// Function called by consumer thread


public void consume() throws InterruptedException
{
while (true) {
synchronized (this)
{
// consumer thread waits while list
// is empty
while (list.size() == 0)
wait();
// to retrieve the ifrst job in the list
int val = list.removeFirst();

System.out.println("Consumer consumed-"
+ val);

// Wake up producer thread


notify();

// and sleep
Thread.sleep(1000);
}
}
}
}
}
Output-

PROGRAM.4- Create a customized exception and also make use of all the
5 exception keyword.
THEORY-In Java, we can create our own exceptions that are derived
classes of the Exception class. Creating our own Exception is known as
custom exception or user-defined exception. Basically, Java custom
exceptions are used to customize the exception according to user need.
Using the custom exception, we can have your own exception and message.
Here, we have passed a string to the constructor of superclass i.e.
Exception class that can be obtained using getMessage() method on the
object we have created.
PROGRAM-
public class WrongFileNameException extends Exception {
public WrongFileNameException(String errorMessage) {
super(errorMessage);
}
}
// class representing custom exception
class InvalidAgeException extends Exception
{
public InvalidAgeException (String str)
{
// calling the constructor of parent Exception
super(str);
}
}

// class that uses custom exception InvalidAgeException


public class TestCustomException1
{

// method to check the age


static void validate (int age) throws InvalidAgeException{
if(age < 18){

// throw an object of user defined exception


throw new InvalidAgeException("age is not valid to vote");
}
else {
System.out.println("welcome to vote");
}
}

// main method
public static void main(String args[])
{
try
{
// calling the method
validate(13);
}
catch (InvalidAgeException ex)
{
System.out.println("Caught the exception");

// printing the message from InvalidAgeException object


System.out.println("Exception occured: " + ex);
}

System.out.println("rest of the code...");


}
}
Output-

PROGRAM.5-Convert the content of a given file into the upper case


content of the same file.
THEORY-The java string toUpperCase() method of String class has
converted all characters of the string into an uppercase letter. There
is two variant of toUpperCase() method. The key thing that is to be
taken into consideration is toUpperCase() method worked same as to
UpperCase(Locale.getDefault()) method as internally default locale is
used.
PROGRAM-
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;

public class Main {


public static void main(String[] arguments) {
String sourceName = "a.txt";

Path source = FileSystems.getDefault().getPath(sourceName);


Path temp = FileSystems.getDefault().getPath("tmp_" +
sourceName);

// Create input stream


FileReader fr = new FileReader(source.toFile());
BufferedReader in = new BufferedReader(fr);

// Create output stream


FileWriter fw = new FileWriter(temp.toFile());
BufferedWriter out = new BufferedWriter(fw);

boolean eof = false;


int inChar;
do {
inChar = in.read();
if (inChar != -1) {
char outChar = Character.toUpperCase((char) inChar);
out.write(outChar);
} else
eof = true;
} while (!eof);
in.close();
out.close();

Files.delete(source);
Files.move(temp, source);
} catch (IOException | SecurityException se) {
System.out.println("Error -- " + se.toString());
}
}
}

Output-

PROGRAM.6-Develop an analog clock using applet.


THEORY- Each hand of the clock will be animating with 1-second delay
keeping one end at the centre. The position of the other end can be
derived by the system time. The angle formed by a hand of the clock in
every second will be different throughout its journey. This is why
various instances make a different angle to the horizontal line.
PROGRAM-
// Java program to illustrate
// analog clock using Applets

import java.applet.Applet;
import java.awt.*;
import java.util.*;

public class analogClock extends Applet {

@Override
public void init()
{
// Applet window size & color
this.setSize(new Dimension(800, 400));
setBackground(new Color(50, 50, 50));
new Thread() {
@Override
public void run()
{
while (true) {
repaint();
delayAnimation();
}
}
}.start();
}

// Animating the applet


private void delayAnimation()
{
try {

// Animation delay is 1000 milliseconds


Thread.sleep(1000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}

// Paint the applet


@Override
public void paint(Graphics g)
{
// Get the system time
Calendar time = Calendar.getInstance();
int hour = time.get(Calendar.HOUR_OF_DAY);
int minute = time.get(Calendar.MINUTE);
int second = time.get(Calendar.SECOND);

// 12 hour format
if (hour > 12) {
hour -= 12;
}

// Draw clock body center at (400, 200)


g.setColor(Color.white);
g.fillOval(300, 100, 200, 200);

// Labeling
g.setColor(Color.black);
g.drawString("12", 390, 120);
g.drawString("9", 310, 200);
g.drawString("6", 400, 290);
g.drawString("3", 480, 200);

// Declaring variables to be used


double angle;
int x, y;

// Second hand's angle in Radian


angle = Math.toRadians((15 - second) * 6);

// Position of the second hand


// with length 100 unit
x = (int)(Math.cos(angle) * 100);
y = (int)(Math.sin(angle) * 100);

// Red color second hand


g.setColor(Color.red);
g.drawLine(400, 200, 400 + x, 200 - y);

// Minute hand's angle in Radian


angle = Math.toRadians((15 - minute) * 6);

// Position of the minute hand


// with length 80 unit
x = (int)(Math.cos(angle) * 80);
y = (int)(Math.sin(angle) * 80);

// blue color Minute hand


g.setColor(Color.blue);
g.drawLine(400, 200, 400 + x, 200 - y);

// Hour hand's angle in Radian


angle = Math.toRadians((15 - (hour * 5)) * 6);

// Position of the hour hand


// with length 50 unit
x = (int)(Math.cos(angle) * 50);
y = (int)(Math.sin(angle) * 50);

// Black color hour hand


g.setColor(Color.black);
g.drawLine(400, 200, 400 + x, 200 - y);
}
}

Output-

PROGRAM.7-Develop a scientific calculator using swing.


THEORY- A Scientific Calculator is a very powerful and general
purpose calculator. In addition to basic arithmetic functions, it
provides trigonometric functions, logarithms, powers, roots etc.
Therefore, these calculators are widely used in any situation where
quick access to certain mathematical functions is needed. Here we are
going to create a Scientific calculator using java swing.
PROGRAM-
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.event.*;
public class ScientificCalculator extends JFrame implements
ActionListener {
JTextField tfield;
double temp, temp1, result, a;
static double m1, m2;
int k = 1, x = 0, y = 0, z = 0;
char ch;
JButton b1, b2, b3, b4, b5, b6, b7, b8, b9, zero, clr, pow2, pow3,
exp,
fac, plus, min, div, log, rec, mul, eq, addSub, dot, mr,
mc, mp,
mm, sqrt, sin, cos, tan;
Container cont;
JPanel textPanel, buttonpanel;

ScientificCalculator() {
cont = getContentPane();
cont.setLayout(new BorderLayout());
JPanel textpanel = new JPanel();
tfield = new JTextField(25);
tfield.setHorizontalAlignment(SwingConstants.RIGHT);
tfield.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent keyevent) {
char c = keyevent.getKeyChar();
if (c >= '0' && c <= '9') {
} else {
keyevent.consume();
}
}
});
textpanel.add(tfield);
buttonpanel = new JPanel();
buttonpanel.setLayout(new GridLayout(8, 4, 2, 2));
boolean t = true;
mr = new JButton("MR");
buttonpanel.add(mr);
mr.addActionListener(this);
mc = new JButton("MC");
buttonpanel.add(mc);
mc.addActionListener(this);

mp = new JButton("M+");
buttonpanel.add(mp);
mp.addActionListener(this);

mm = new JButton("M-");
buttonpanel.add(mm);
mm.addActionListener(this);

b1 = new JButton("1");
buttonpanel.add(b1);
b1.addActionListener(this);
b2 = new JButton("2");
buttonpanel.add(b2);
b2.addActionListener(this);
b3 = new JButton("3");
buttonpanel.add(b3);
b3.addActionListener(this);

b4 = new JButton("4");
buttonpanel.add(b4);
b4.addActionListener(this);
b5 = new JButton("5");
buttonpanel.add(b5);
b5.addActionListener(this);
b6 = new JButton("6");
buttonpanel.add(b6);
b6.addActionListener(this);

b7 = new JButton("7");
buttonpanel.add(b7);
b7.addActionListener(this);
b8 = new JButton("8");
buttonpanel.add(b8);
b8.addActionListener(this);
b9 = new JButton("9");
buttonpanel.add(b9);
b9.addActionListener(this);

zero = new JButton("0");


buttonpanel.add(zero);
zero.addActionListener(this);

plus = new JButton("+");


buttonpanel.add(plus);
plus.addActionListener(this);

min = new JButton("-");


buttonpanel.add(min);
min.addActionListener(this);

mul = new JButton("*");


buttonpanel.add(mul);
mul.addActionListener(this);

div = new JButton("/");


div.addActionListener(this);
buttonpanel.add(div);

addSub = new JButton("+/-");


buttonpanel.add(addSub);
addSub.addActionListener(this);

dot = new JButton(".");


buttonpanel.add(dot);
dot.addActionListener(this);

eq = new JButton("=");
buttonpanel.add(eq);
eq.addActionListener(this);

rec = new JButton("1/x");


buttonpanel.add(rec);
rec.addActionListener(this);
sqrt = new JButton("Sqrt");
buttonpanel.add(sqrt);
sqrt.addActionListener(this);
log = new JButton("log");
buttonpanel.add(log);
log.addActionListener(this);

sin = new JButton("SIN");


buttonpanel.add(sin);
sin.addActionListener(this);
cos = new JButton("COS");
buttonpanel.add(cos);
cos.addActionListener(this);
tan = new JButton("TAN");
buttonpanel.add(tan);
tan.addActionListener(this);
pow2 = new JButton("x^2");
buttonpanel.add(pow2);
pow2.addActionListener(this);
pow3 = new JButton("x^3");
buttonpanel.add(pow3);
pow3.addActionListener(this);
exp = new JButton("Exp");
exp.addActionListener(this);
buttonpanel.add(exp);
fac = new JButton("n!");
fac.addActionListener(this);
buttonpanel.add(fac);

clr = new JButton("AC");


buttonpanel.add(clr);
clr.addActionListener(this);
cont.add("Center", buttonpanel);
cont.add("North", textpanel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e) {
String s = e.getActionCommand();
if (s.equals("1")) {
if (z == 0) {
tfield.setText(tfield.getText() + "1");
} else {
tfield.setText("");
tfield.setText(tfield.getText() + "1");
z = 0;
}
}
if (s.equals("2")) {
if (z == 0) {
tfield.setText(tfield.getText() + "2");
} else {
tfield.setText("");
tfield.setText(tfield.getText() + "2");
z = 0;
}
}
if (s.equals("3")) {
if (z == 0) {
tfield.setText(tfield.getText() + "3");
} else {
tfield.setText("");
tfield.setText(tfield.getText() + "3");
z = 0;
}
}
if (s.equals("4")) {
if (z == 0) {
tfield.setText(tfield.getText() + "4");
} else {
tfield.setText("");
tfield.setText(tfield.getText() + "4");
z = 0;
}
}
if (s.equals("5")) {
if (z == 0) {
tfield.setText(tfield.getText() + "5");
} else {
tfield.setText("");
tfield.setText(tfield.getText() + "5");
z = 0;
}
}
if (s.equals("6")) {
if (z == 0) {
tfield.setText(tfield.getText() + "6");
} else {
tfield.setText("");
tfield.setText(tfield.getText() + "6");
z = 0;
}
}
if (s.equals("7")) {
if (z == 0) {
tfield.setText(tfield.getText() + "7");
} else {
tfield.setText("");
tfield.setText(tfield.getText() + "7");
z = 0;
}
}
if (s.equals("8")) {
if (z == 0) {
tfield.setText(tfield.getText() + "8");
} else {
tfield.setText("");
tfield.setText(tfield.getText() + "8");
z = 0;
}
}
if (s.equals("9")) {
if (z == 0) {
tfield.setText(tfield.getText() + "9");
} else {
tfield.setText("");
tfield.setText(tfield.getText() + "9");
z = 0;
}
}
if (s.equals("0")) {
if (z == 0) {
tfield.setText(tfield.getText() + "0");
} else {
tfield.setText("");
tfield.setText(tfield.getText() + "0");
z = 0;
}
}
if (s.equals("AC")) {
tfield.setText("");
x = 0;
y = 0;
z = 0;
}
if (s.equals("log")) {
if (tfield.getText().equals("")) {
tfield.setText("");
} else {
a = Math.log(Double.parseDouble(tfield.getText()));
tfield.setText("");
tfield.setText(tfield.getText() + a);
}
}
if (s.equals("1/x")) {
if (tfield.getText().equals("")) {
tfield.setText("");
} else {
a = 1 / Double.parseDouble(tfield.getText());
tfield.setText("");
tfield.setText(tfield.getText() + a);
}
}
if (s.equals("Exp")) {
if (tfield.getText().equals("")) {
tfield.setText("");
} else {
a = Math.exp(Double.parseDouble(tfield.getText()));
tfield.setText("");
tfield.setText(tfield.getText() + a);
}
}
if (s.equals("x^2")) {
if (tfield.getText().equals("")) {
tfield.setText("");
} else {
a = Math.pow(Double.parseDouble(tfield.getText()),
2);
tfield.setText("");
tfield.setText(tfield.getText() + a);
}
}
if (s.equals("x^3")) {
if (tfield.getText().equals("")) {
tfield.setText("");
} else {
a = Math.pow(Double.parseDouble(tfield.getText()),
3);
tfield.setText("");
tfield.setText(tfield.getText() + a);
}
}
if (s.equals("+/-")) {
if (x == 0) {
tfield.setText("-" + tfield.getText());
x = 1;
} else {
tfield.setText(tfield.getText());
}
}
if (s.equals(".")) {
if (y == 0) {
tfield.setText(tfield.getText() + ".");
y = 1;
} else {
tfield.setText(tfield.getText());
}
}
if (s.equals("+")) {
if (tfield.getText().equals("")) {
tfield.setText("");
temp = 0;
ch = '+';
} else {
temp = Double.parseDouble(tfield.getText());
tfield.setText("");
ch = '+';
y = 0;
x = 0;
}
tfield.requestFocus();
}
if (s.equals("-")) {
if (tfield.getText().equals("")) {
tfield.setText("");
temp = 0;
ch = '-';
} else {
x = 0;
y = 0;
temp = Double.parseDouble(tfield.getText());
tfield.setText("");
ch = '-';
}
tfield.requestFocus();
}
if (s.equals("/")) {
if (tfield.getText().equals("")) {
tfield.setText("");
temp = 1;
ch = '/';
} else {
x = 0;
y = 0;
temp = Double.parseDouble(tfield.getText());
ch = '/';
tfield.setText("");
}
tfield.requestFocus();
}
if (s.equals("*")) {
if (tfield.getText().equals("")) {
tfield.setText("");
temp = 1;
ch = '*';
} else {
x = 0;
y = 0;
temp = Double.parseDouble(tfield.getText());
ch = '*';
tfield.setText("");
}
tfield.requestFocus();
}
if (s.equals("MC")) {
m1 = 0;
tfield.setText("");
}
if (s.equals("MR")) {
tfield.setText("");
tfield.setText(tfield.getText() + m1);
}
if (s.equals("M+")) {
if (k == 1) {
m1 = Double.parseDouble(tfield.getText());
k++;
} else {
m1 += Double.parseDouble(tfield.getText());
tfield.setText("" + m1);
}
}
if (s.equals("M-")) {
if (k == 1) {
m1 = Double.parseDouble(tfield.getText());
k++;
} else {
m1 -= Double.parseDouble(tfield.getText());
tfield.setText("" + m1);
}
}
if (s.equals("Sqrt")) {
if (tfield.getText().equals("")) {
tfield.setText("");
} else {
a =
Math.sqrt(Double.parseDouble(tfield.getText()));
tfield.setText("");
tfield.setText(tfield.getText() + a);
}
}
if (s.equals("SIN")) {
if (tfield.getText().equals("")) {
tfield.setText("");
} else {
a = Math.sin(Double.parseDouble(tfield.getText()));
tfield.setText("");
tfield.setText(tfield.getText() + a);
}
}
if (s.equals("COS")) {
if (tfield.getText().equals("")) {
tfield.setText("");
} else {
a = Math.cos(Double.parseDouble(tfield.getText()));
tfield.setText("");
tfield.setText(tfield.getText() + a);
}
}
if (s.equals("TAN")) {
if (tfield.getText().equals("")) {
tfield.setText("");
} else {
a = Math.tan(Double.parseDouble(tfield.getText()));
tfield.setText("");
tfield.setText(tfield.getText() + a);
}
}
if (s.equals("=")) {
if (tfield.getText().equals("")) {
tfield.setText("");
} else {
temp1 = Double.parseDouble(tfield.getText());
switch (ch) {
case '+':
result = temp + temp1;
break;
case '-':
result = temp - temp1;
break;
case '/':
result = temp / temp1;
break;
case '*':
result = temp * temp1;
break;
}
tfield.setText("");
tfield.setText(tfield.getText() + result);
z = 1;
}
}
if (s.equals("n!")) {
if (tfield.getText().equals("")) {
tfield.setText("");
} else {
a = fact(Double.parseDouble(tfield.getText()));
tfield.setText("");
tfield.setText(tfield.getText() + a);
}
}
tfield.requestFocus();
}

double fact(double x) {
int er = 0;
if (x < 0) {
er = 20;
return 0;
}
double i, s = 1;
for (i = 2; i <= x; i += 1.0)
s *= i;
return s;
}

public static void main(String args[]) {


try {
UIManager
.setLookAndFeel("com.sun.java.swing.plaf.windo
ws.WindowsLookAndFeel");
} catch (Exception e) {
}
ScientificCalculator f = new ScientificCalculator();
f.setTitle("ScientificCal culator");
f.pack();
f.setVisible(true);
}
}
Output-
PROGRAM.8-Create an editor like MS-word using swings.
THEORY- To create a simple text editor in Java Swing we will use a
JTextArea, a JMenuBar and add JMenu to it and we will add JMenuItems.
All the menu items will have actionListener to detect any action.
There will be a menu bar and it will contain two menus and a button:

1. File menu
 open: this menuitem is used to open a file
 save: this menuitem is used to save a file
 print : this menuitem is used to print the components of the text
area
 new : this menuitem is used to create a new blank file
2. Edit menu
 cut: this menuitem is to cut the selected area and copy it to
clipboard
 copy: this menuitem is to copy the selected area to the clipboard
 paste : this menuitem is to paste the text from the clipboard to
the text area
3. Close : this button closes the frame

PROGRAM-
// Java Program to create a text editor using java
import java.awt.*;
import javax.swing.*;
import java.io.*;
import java.awt.event.*;
import javax.swing.plaf.metal.*;
import javax.swing.text.*;
class editor extends JFrame implements ActionListener {
// Text component
JTextArea t;

// Frame
JFrame f;

// Constructor
editor()
{
// Create a frame
f = new JFrame("editor");

try {
// Set metal look and feel

UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");

// Set theme to ocean


MetalLookAndFeel.setCurrentTheme(new OceanTheme());
}
catch (Exception e) {
}

// Text component
t = new JTextArea();

// Create a menubar
JMenuBar mb = new JMenuBar();

// Create amenu for menu


JMenu m1 = new JMenu("File");

// Create menu items


JMenuItem mi1 = new JMenuItem("New");
JMenuItem mi2 = new JMenuItem("Open");
JMenuItem mi3 = new JMenuItem("Save");
JMenuItem mi9 = new JMenuItem("Print");

// Add action listener


mi1.addActionListener(this);
mi2.addActionListener(this);
mi3.addActionListener(this);
mi9.addActionListener(this);

m1.add(mi1);
m1.add(mi2);
m1.add(mi3);
m1.add(mi9);

// Create amenu for menu


JMenu m2 = new JMenu("Edit");

// Create menu items


JMenuItem mi4 = new JMenuItem("cut");
JMenuItem mi5 = new JMenuItem("copy");
JMenuItem mi6 = new JMenuItem("paste");
// Add action listener
mi4.addActionListener(this);
mi5.addActionListener(this);
mi6.addActionListener(this);

m2.add(mi4);
m2.add(mi5);
m2.add(mi6);

JMenuItem mc = new JMenuItem("close");

mc.addActionListener(this);

mb.add(m1);
mb.add(m2);
mb.add(mc);

f.setJMenuBar(mb);
f.add(t);
f.setSize(500, 500);
f.show();
}

// If a button is pressed
public void actionPerformed(ActionEvent e)
{
String s = e.getActionCommand();

if (s.equals("cut")) {
t.cut();
}
else if (s.equals("copy")) {
t.copy();
}
else if (s.equals("paste")) {
t.paste();
}
else if (s.equals("Save")) {
// Create an object of JFileChooser class
JFileChooser j = new JFileChooser("f:");

// Invoke the showsSaveDialog function to show the save


dialog
int r = j.showSaveDialog(null);

if (r == JFileChooser.APPROVE_OPTION) {

// Set the label to the path of the selected


directory
File fi = new
File(j.getSelectedFile().getAbsolutePath());

try {
// Create a file writer
FileWriter wr = new FileWriter(fi, false);

// Create buffered writer to write


BufferedWriter w = new BufferedWriter(wr);

// Write
w.write(t.getText());

w.flush();
w.close();
}
catch (Exception evt) {
JOptionPane.showMessageDialog(f,
evt.getMessage());
}
}
// If the user cancelled the operation
else
JOptionPane.showMessageDialog(f, "the user
cancelled the operation");
}
else if (s.equals("Print")) {
try {
// print the file
t.print();
}
catch (Exception evt) {
JOptionPane.showMessageDialog(f, evt.getMessage());
}
}
else if (s.equals("Open")) {
// Create an object of JFileChooser class
JFileChooser j = new JFileChooser("f:");

// Invoke the showsOpenDialog function to show the save


dialog
int r = j.showOpenDialog(null);

// If the user selects a file


if (r == JFileChooser.APPROVE_OPTION) {
// Set the label to the path of the selected
directory
File fi = new
File(j.getSelectedFile().getAbsolutePath());
try {
// String
String s1 = "", sl = "";

// File reader
FileReader fr = new FileReader(fi);

// Buffered reader
BufferedReader br = new BufferedReader(fr);

// Initialize sl
sl = br.readLine();

// Take the input from the file


while ((s1 = br.readLine()) != null) {
sl = sl + "\n" + s1;
}

// Set the text


t.setText(sl);
}
catch (Exception evt) {
JOptionPane.showMessageDialog(f,
evt.getMessage());
}
}
// If the user cancelled the operation
else
JOptionPane.showMessageDialog(f, "the user
cancelled the operation");
}
else if (s.equals("New")) {
t.setText("");
}
else if (s.equals("close")) {
f.setVisible(false);
}
}

// Main class
public static void main(String args[])
{
editor e = new editor();
}
}
Output-
PROGRAM.9-Create a servelet that uses cookies to store the number of
times a user has visited your servlet.
THEORY- Many websites use small strings of text known as cookies to
store persistent client-side state between connections. Cookies are
passed from server to client and back again in the HTTP headers of
requests and responses. Cookies can be used by a server to indicate
session IDs, shopping cart contents, login credentials, user
preferences, and more.
PROGRAM-
// Java program to illustrate methods
// of Cookie class
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* Servlet implementation class cookieTest
*/
@WebServlet("/cookieTest")
public class cookieTest extends HttpServlet
{
private static final long serialVersionUID = 1L;

/**
* @see HttpServlet#HttpServlet()
*/
public cookieTest() {
super();
// TODO Auto-generated constructor stub
}

/**
* @see HttpServlet#doGet(HttpServletRequest request,
HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{

response.setContentType("text/html");
// Create a new cookie with the name test cookie
// and value 123
Cookie cookie = new Cookie("test_cookie", "123");

// setComment() method
cookie.setComment("Just for testing");

// setDomain() method
// cookie.setDomain("domain");
// setMaxAge() method
cookie.setMaxAge(3600);

// setPath() method
cookie.setPath("/articles");

// setSecure() method
cookie.setSecure(false);

// setValue() method
cookie.setValue("321");

// setVersion() method
cookie.setVersion(0);

response.addCookie(cookie);

PrintWriter pw = response.getWriter();
pw.print("<html><head></head><body>");
Cookie ck[] = request.getCookies();

if (ck == null) {
pw.print("<p>This is first time the page is
requested.</p>");
pw.print("<p>And therefore no cookies
found</p></body></html>");
} else {
pw.print("<p>Welcome Again...Cookies found</p>");
for (int i = 0; i < ck.length; i++) {

// getName() method
pw.print("<p>Name :" + ck[i].getName() + "</p>");

// getValue() method
pw.print("<p>Value :" + ck[i].getValue() + "</p>");

// getDomain() method
pw.print("<p>Domain :" + ck[i].getDomain() +
"</p>");

// getPath() method
pw.print("<p>Name :" + ck[i].getPath() + "</p>");

// getMaxAge() method
pw.print("<p>Max Age :" + ck[i].getMaxAge() +
"</p>");

// getComment() method
pw.print("<p>Comment :" + ck[i].getComment() +
"</p>");

// getSecure() method
pw.print("<p>Name :" + ck[i].getSecure() + "</p>");

// getVersion() method
pw.print("<p>Version :" + ck[i].getVersion() +
"</p>");
}
pw.print("<body></html>");

}
pw.close();
}

/**
* @see HttpServlet#doPost(HttpServletRequest request,
HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{

doGet(request, response);
}

Output-
For the first request:

For the second request:

PROGRAM.10-Create a simple java bean having bound and constrained


properties.
THEORY- A Bean that has a bound property generates an event when the
property is changed. The event is of type PropertyChangeEvent and is
sent to objects that previously registered an interest in receiving
such notifications. A class that handles this event must implement
the PropertyChangeListener interface.
A Bean that has a constrained property generates an event when an
attempt is made to change its value. It also generates an event of
type PropertyChangeEvent. It too is sent to objects that previously
registered an interest in receiving such notifications. However, those
other objects have the ability to veto the proposed change by throwing
a PropertyVetoException. This capability allows a Bean to operate
differently according to its run-time environment. A class that handles
this event must implement the VetoableChangeListener interface.

PROGRAM-
:-bound
import java.awt.Graphics;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.Serializable;
import javax.swing.JComponent;

/**
* Bean with bound properties.
*/
public class MyBean
extends JComponent
implements Serializable
{
private String title;
private String[] lines = new String[10];

private final PropertyChangeSupport pcs = new


PropertyChangeSupport( this );

public String getTitle()


{
return this.title;
}

public void setTitle( String title )


{
String old = this.title;
this.title = title;
this.pcs.firePropertyChange( "title", old, title );
}

public String[] getLines()


{
return this.lines.clone();
}

public String getLines( int index )


{
return this.lines[index];
}

public void setLines( String[] lines )


{
String[] old = this.lines;
this.lines = lines;
this.pcs.firePropertyChange( "lines", old, lines );
}

public void setLines( int index, String line )


{
String old = this.lines[index];
this.lines[index] = line;
this.pcs.fireIndexedPropertyChange( "lines", index, old,
lines );
}

public void addPropertyChangeListener( PropertyChangeListener


listener )
{
this.pcs.addPropertyChangeListener( listener );
}

public void removePropertyChangeListener( PropertyChangeListener


listener )
{
this.pcs.removePropertyChangeListener( listener );
}

protected void paintComponent( Graphics g )


{
g.setColor( getForeground() );

int height = g.getFontMetrics().getHeight();


paintString( g, this.title, height );

if ( this.lines != null )
{
int step = height;
for ( String line : this.lines )
paintString( g, line, height += step );
}
}

private void paintString( Graphics g, String str, int height )


{
if ( str != null )
g.drawString( str, 0, height );
}
}
:- constrained properties
import java.io.Serializable;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.beans.PropertyVetoException;
import java.beans.VetoableChangeListener;
import java.beans.VetoableChangeSupport;
import java.awt.Graphics;
import javax.swing.JComponent;

/**
* Bean with constrained properties.
*/
public class MyBean
extends JComponent
implements Serializable
{
private String title;
private String[] lines = new String[10];

private final PropertyChangeSupport pcs = new


PropertyChangeSupport( this );
private final VetoableChangeSupport vcs = new
VetoableChangeSupport( this );

public String getTitle()


{
return this.title;
}
/**
* This method was modified to throw the PropertyVetoException
* if some vetoable listeners reject the new title value
*/
public void setTitle( String title )
throws PropertyVetoException
{
String old = this.title;
this.vcs.fireVetoableChange( "title", old, title );
this.title = title;
this.pcs.firePropertyChange( "title", old, title );
}

public String[] getLines()


{
return this.lines.clone();
}

public String getLines( int index )


{
return this.lines[index];
}
/**
* This method throws the PropertyVetoException
* if some vetoable listeners reject the new lines value
*/
public void setLines( String[] lines )
throws PropertyVetoException
{
String[] old = this.lines;
this.vcs.fireVetoableChange( "lines", old, lines );
this.lines = lines;
this.pcs.firePropertyChange( "lines", old, lines );
}

public void setLines( int index, String line )


throws PropertyVetoException
{
String old = this.lines[index];
this.vcs.fireVetoableChange( "lines", old, line );
this.lines[index] = line;
this.pcs.fireIndexedPropertyChange( "lines", index, old,
line );
}

public void addPropertyChangeListener( PropertyChangeListener


listener )
{
this.pcs.addPropertyChangeListener( listener );
}

public void removePropertyChangeListener( PropertyChangeListener


listener )
{
this.pcs.removePropertyChangeListener( listener );
}
/**
* Registration of the VetoableChangeListener
*/
public void addVetoableChangeListener( VetoableChangeListener
listener )
{
this.vcs.addVetoableChangeListener( listener );
}

public void removeVetoableChangeListener( VetoableChangeListener


listener )
{
this.vcs.addVetoableChangeListener( listener );
}
protected void paintComponent( Graphics g )
{
g.setColor( getForeground() );

int height = g.getFontMetrics().getHeight();


paintString( g, this.title, height );

if ( this.lines != null )
{
int step = height;
for ( String line : this.lines )
paintString( g, line, height += step );
}
}

private void paintString( Graphics g, String str, int height )


{
if ( str != null )
g.drawString( str, 0, height );
}
}
Output-

You might also like