0% found this document useful (0 votes)
8 views38 pages

Java.varshaKumari

This document is a lab report for a Java programming course, detailing various programming tasks completed by a student. It includes implementations of data structures like stacks and queues, dynamic polymorphism, multithreading, custom exceptions, file manipulation, and GUI applications. Each section contains code examples and explanations relevant to the respective programming concepts.

Uploaded by

varsharao605
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views38 pages

Java.varshaKumari

This document is a lab report for a Java programming course, detailing various programming tasks completed by a student. It includes implementations of data structures like stacks and queues, dynamic polymorphism, multithreading, custom exceptions, file manipulation, and GUI applications. Each section contains code examples and explanations relevant to the respective programming concepts.

Uploaded by

varsharao605
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

A

Lab File / Report


of

Programming in Java Lab


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

Submitted By: SubmittedTo:


Varsha Kumari Ms. Jyoti
Reg No.-191250357 Assistant Professor
BTech(CSE)-5th Sem Deptt. Of Computer Science & Engg.

2022
Department of Computer Science & Engineering

DPG Institute of Technology & Management, Gurgaon(HR)

Maharishi Dayanand University, Rohtak(HR)


Sr. Program(s) Page NO. Remarks
No.
1. Create a java program to implement stack and queue concept. 3-8

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

3. Write a java program to show multithreaded producer and consumer 12-14


Application.
4. Create a customized exception and also make use of all the 5 15-16
exception keywords.
5. Convert the content of a given file into the upper case content of the 17-19
same file
6. Develop an analog clock using applet. 20-22

7. Develop a scientific calculator using swings. 23-27

8. Create an editor like MS-word using swings. 28-33

9. Create a servlet that uses Cookies to store the number of times a 34-36
user has visited your servlet.
10. Create a simple java bean having bound and constrained 37-38
properties.
PROGRAM-1

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

 Java program to implement Stack

package com.company;
import java.util.Stack;
class Main1 {

// store elements of stack


private int arr[];
// represent top of stack
private int top;
// total capacity of the stack
private int capacity;

// Creating a stack
Main1(int size) {
// initialize the array
// initialize the stack variables
arr = new int[size];
capacity = size;
top = -1;
}

// push elements to the top of stack


public void push(int x) {
if (isFull()) {
System.out.println("Stack OverFlow");

// terminates the program


System.exit(1);
}

// insert element on top of stack


System.out.println("Inserting " + x);
arr[++top] = x;
}

// pop elements from top of stack


public int pop() {

// if stack is empty
// no element to pop
if (isEmpty()) {
System.out.println("STACK EMPTY");
// terminates the program
System.exit(1);
}

// pop element from top of stack


return arr[top--];
}

// return size of the stack


public int getSize() {
return top + 1;
}

// check if the stack is empty


public Boolean isEmpty() {
return top == -1;
}

// check if the stack is full


public Boolean isFull() {
return top == capacity - 1;
}

// display elements of stack


public void printStack() {
for (int i = 0; i <= top; i++) {
System.out.print(arr[i] + ", ");
}
}

public static void main(String[] args) {


Main1 stack = new Main1(5);

stack.push(1);
stack.push(2);
stack.push(3);

System.out.print("Stack: ");
stack.printStack();

// remove element from stack


stack.pop();
System.out.println("\nAfter popping out");
stack.printStack();

}
}
OUTPUT

 Java program to implement Queue

public class Queue {


int SIZE = 5;
int items[] = new int[SIZE];
int front, rear;

Queue() {
front = -1;
rear = -1;
}

// check if the queue is full


boolean isFull() {
if (front == 0 && rear == SIZE - 1) {
return true;
}
return false;
}

// check if the queue is empty


boolean isEmpty() {
if (front == -1)
return true;
else
return false;
}

// insert elements to the queue


void enQueue(int element) {

// if queue is full
if (isFull()) {
System.out.println("Queue is full");
}
else {
if (front == -1) {
// mark front denote first element of queue
front = 0;
}

rear++;
// insert element at the rear
items[rear] = element;
System.out.println("Insert " + element);
}
}

// delete element from the queue


int deQueue() {
int element;

// if queue is empty
if (isEmpty()) {
System.out.println("Queue is empty");
return (-1);
}
else {
// remove element from the front of queue
element = items[front];

// if the queue has only one element


if (front >= rear) {
front = -1;
rear = -1;
}
else {
// mark next element as the front
front++;
}
System.out.println( element + " Deleted");
return (element);
}
}

// display element of the queue


void display() {
int i;
if (isEmpty()) {
System.out.println("Empty Queue");
}
else {
// display the front of the queue
System.out.println("\nFront index-> " + front);

// display element of the queue


System.out.println("Items -> ");
for (i = front; i <= rear; i++)
System.out.print(items[i] + " ");

// display the rear of the queue


System.out.println("\nRear index-> " + rear);
}
}

public static void main(String[] args) {

// create an object of Queue class


Queue q = new Queue();

// try to delete element from the queue


// currently queue is empty
// so deletion is not possible
q.deQueue();

// insert elements to the queue


for(int i = 1; i < 6; i ++) {
q.enQueue(i);
}

// 6th element can't be added to queue because queue is full


q.enQueue(6);

q.display();

// deQueue removes element entered first i.e. 1


q.deQueue();

// Now we have just 4 elements


q.display();

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

Polymorphism is that it has many forms that mean one specific defined form is used in many different
ways.

Dynamic Polymorphism
This type of polymorphism is resolved by the java virtual machine, not by the java compiler. That’s
why this type of polymorphism is called run-time polymorphism. Run time polymorphism occurs
during method overriding in java.

// Java Program to Illustrate Run-time polymorphism

// Importing I/O classes

import java.io.*;

// Class 1 (Parent class)

class GFG1 {

//name method

void name() {

System.out.println("This is the GFG1 class");

// Class 2 (Child class)

// Main class extending parent class

public class GFG extends GFG1 {

// Method 1

void name() {

// Print statement

System.out.println("This is the GFG class");


}

// Method 2

// Main drive method

public static void main(String[] args) {

// Now creating 2 objects with different references and // calling the Method 1 over the
objects

// Case 1: GFG1 reference and GFG1 is the object

GFG1 ob = new GFG1();

ob.name();

// Case 2: GFG1 reference and GFG is the object

GFG1 ob1 = new GFG();

ob1.name();

}
}

Interface - Interfaces are very similar to classes. They have variables and methods but the interfaces
allow only abstract methods(that don’t contain the body of the methods), but what is the difference
between the classes and the interfaces? The first advantage is to allow interfaces to implement the
multiple inheritances in a particular class. The JAVA language doesn’t support multiple inheritances if
we extend multiple classes in the class, but with the help of the interfaces, multiple inheritances are
allowed in Java.

// Java Program to Demonstrate Concept of interfaces


// Interface
interface salary {
void insertsalary(int salary);
}
// Class 1
// Implementing the salary in the class
class SDE1 implements salary {
int salary;

@Override public void insertsalary(int salary) {


this.salary = salary;

}
void printSalary() { System.out.println(this.salary); }
}

// Class 2
// Implementing the salary inside the SDE2 class
class SDE2 implements salary {
int salary;
@Override public void insertsalary(int salary) {
this.salary = salary;
}
void printSalary() { System.out.println(this.salary); }
}

public class GFG {


public static void main(String[] args)
{
SDE1 ob = new SDE1();
// Insert different salaries
ob.insertsalary(100000);
ob.printSalary();
SDE2 ob1 = new SDE2();
ob1.insertsalary(200000);
ob1.printSalary();
}
}
3. Write a Java program to show multithread producer and consumer
application ?

// Java program to implement solution of producer


// consumer problem.
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);
}
}
}
}
}
4. Create a customised exception and also make use of all the 5 exception
keywords ?

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


}
}
5. Convert a content of given file into the uppper case content of the same
file
// Java program to read content from one file
// and write it into another file

// Custom paths for this program


// Reading from - gfgInput.txt
// Writing to - gfgOutput.txt

// Importing input output classes


import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

// Class
class GFG {

// Main driver method


public static void main(String[] args)
{

// The file reading process may sometimes give


// IOException

// Try block to check for exceptions


try {

// Creating a FileReader object and


// file to be read is passed as in parameters
// from the local directory of computer
FileReader fr = new FileReader("gfgInput.txt");

// FileReader will open that file from that


// directory, if there is no file found it will
// through an IOException

// Creating a FileWriter object


FileWriter fw = new FileWriter("gfgOutput.txt");

// It will create a new file with name


// "gfgOutput.text", if it is already available,
// then it will open that instead

// Declaring a blank string in which


// whole content of file is to be stored
String str = "";
int i;

// read() method will read the file character by


// character and print it until it end the end
// of the file

// Condition check
// Reading the file using read() method which
// returns -1 at EOF while reading
while ((i = fr.read()) != -1) {

// Storing every character in the string and converting into upper case
str += (char)i.toUpperCase();
}

// Print and display the string that


// contains file data
System.out.println(str);

// Writing above string data to


// FileWriter object
fw.write(str);

// Closing the file using close() method


// of Reader class which closes the stream &
// release resources that were busy in stream
fr.close();
fw.close();

// Display message
System.out.println(
"File reading and writing both done");
}

// Catch block to handle the exception


catch (IOException e) {

// If there is no file in specified path or


// any other error occured during runtime
// then it will print IOException

// Display message
System.out.println(
"There are some IOException");
}
}
}
6. Develop an analog clock using applet .
// 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);
}
}
7. Develop a scientific calculator using swings.
// Java program to create a simple calculator
// with basic +, -, /, * using java swing elements

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
class calculator extends JFrame implements ActionListener {
// create a frame
static JFrame f;

// create a textfield
static JTextField l;

// store operator and operands


String s0, s1, s2;

// default constructor
calculator()
{
s0 = s1 = s2 = "";
}

// main function
public static void main(String args[])
{
// create a frame
f = new JFrame("calculator");

try {
// set look and feel
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch (Exception e) {
System.err.println(e.getMessage());
}

// create a object of class


calculator c = new calculator();

// create a textfield
l = new JTextField(16);

// set the textfield to non editable


l.setEditable(false);
// create number buttons and some operators
JButton b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, ba, bs, bd, bm, be, beq, beq1;

// create number buttons


b0 = new JButton("0");
b1 = new JButton("1");
b2 = new JButton("2");
b3 = new JButton("3");
b4 = new JButton("4");
b5 = new JButton("5");
b6 = new JButton("6");
b7 = new JButton("7");
b8 = new JButton("8");
b9 = new JButton("9");

// equals button
beq1 = new JButton("=");

// create operator buttons


ba = new JButton("+");
bs = new JButton("-");
bd = new JButton("/");
bm = new JButton("*");
beq = new JButton("C");

// create . button
be = new JButton(".");

// create a panel
JPanel p = new JPanel();

// add action listeners


bm.addActionListener(c);
bd.addActionListener(c);
bs.addActionListener(c);
ba.addActionListener(c);
b9.addActionListener(c);
b8.addActionListener(c);
b7.addActionListener(c);
b6.addActionListener(c);
b5.addActionListener(c);
b4.addActionListener(c);
b3.addActionListener(c);
b2.addActionListener(c);
b1.addActionListener(c);
b0.addActionListener(c);
be.addActionListener(c);
beq.addActionListener(c);
beq1.addActionListener(c);

// add elements to panel


p.add(l);
p.add(ba);
p.add(b1);
p.add(b2);
p.add(b3);
p.add(bs);
p.add(b4);
p.add(b5);
p.add(b6);
p.add(bm);
p.add(b7);
p.add(b8);
p.add(b9);
p.add(bd);
p.add(be);
p.add(b0);
p.add(beq);
p.add(beq1);

// set Background of panel


p.setBackground(Color.blue);

// add panel to frame


f.add(p);

f.setSize(200, 220);
f.show();
}
public void actionPerformed(ActionEvent e)
{
String s = e.getActionCommand();

// if the value is a number


if ((s.charAt(0) >= '0' && s.charAt(0) <= '9') || s.charAt(0) == '.') {
// if operand is present then add to second no
if (!s1.equals(""))
s2 = s2 + s;
else
s0 = s0 + s;

// set the value of text


l.setText(s0 + s1 + s2);
}
else if (s.charAt(0) == 'C') {
// clear the one letter
s0 = s1 = s2 = "";

// set the value of text


l.setText(s0 + s1 + s2);
}
else if (s.charAt(0) == '=') {

double te;

// store the value in 1st


if (s1.equals("+"))
te = (Double.parseDouble(s0) + Double.parseDouble(s2));
else if (s1.equals("-"))
te = (Double.parseDouble(s0) - Double.parseDouble(s2));
else if (s1.equals("/"))
te = (Double.parseDouble(s0) / Double.parseDouble(s2));
else
te = (Double.parseDouble(s0) * Double.parseDouble(s2));

// set the value of text


l.setText(s0 + s1 + s2 + "=" + te);

// convert it to string
s0 = Double.toString(te);

s1 = s2 = "";
}
else {
// if there was no operand
if (s1.equals("") || s2.equals(""))
s1 = s;
// else evaluate
else {
double te;

// store the value in 1st


if (s1.equals("+"))
te = (Double.parseDouble(s0) + Double.parseDouble(s2));
else if (s1.equals("-"))
te = (Double.parseDouble(s0) - Double.parseDouble(s2));
else if (s1.equals("/"))
te = (Double.parseDouble(s0) / Double.parseDouble(s2));
else
te = (Double.parseDouble(s0) * Double.parseDouble(s2));

// convert it to string
s0 = Double.toString(te);
// place the operator
s1 = s;

// make the operand blank


s2 = "";
}

// set the value of text


l.setText(s0 + s1 + s2);
}
}
}
8. Create an editor like ms-word using swing.
// 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();
}
}
9. Create a servlet that uses cookies to store the number of times a user has
visited your servlet ?

index.html

<form action="servlet1" method="post">


Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>

FirstServlet.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class FirstServlet extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse response){


try{

response.setContentType("text/html");
PrintWriter out = response.getWriter();

String n=request.getParameter("userName");
out.print("Welcome "+n);

Cookie ck=new Cookie("uname",n);//creating cookie object


response.addCookie(ck);//adding cookie in the response

//creating submit button


out.print("<form action='servlet2'>");
out.print("<input type='submit' value='go'>");
out.print("</form>");

out.close();

}catch(Exception e){System.out.println(e);}
}
}

SecondServlet.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class SecondServlet extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse response){


try{

response.setContentType("text/html");
PrintWriter out = response.getWriter();

Cookie ck[]=request.getCookies();
out.print("Hello "+ck[0].getValue());

out.close();

}catch(Exception e){System.out.println(e);}
}

web.xml

<web-app>

<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>

<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>

</web-app>
Output

10.Create a simple java bean having bound and constrained properties ?

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

You might also like