Java Lab File-Chakshit Gaur
Java Lab File-Chakshit Gaur
(LC-CSE-327G)
[In the partial fulfillment of third Years BTech(Computer Science & Engg.) course]
2021
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);
}
}
if(pos == -1)
System.out.println("Element not found");
else
System.out.println("Element is found at position: " +
pos);
}
stack_push(stack);
stack_pop(stack);
stack_push(stack);
stack_peek(stack);
stack_search(stack, 2);
stack_search(stack, 6);
}
}
Output-
System.out.println(q);
// implementation.
int size = q.size();
System.out.println("Size of queue-"+ size);
}
}
Output-
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();
// Driver Code
public static void main (String[] args)
{
TestClass t = new TestClass();
t.display();
System.out.println(a);
}
}
Output-
import java.util.LinkedList;
// 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 {
System.out.println("Producer produced-"
+ value);
System.out.println("Consumer consumed-"
+ val);
// 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);
}
}
// main method
public static void main(String args[])
{
try
{
// calling the method
validate(13);
}
catch (InvalidAgeException ex)
{
System.out.println("Caught the exception");
Files.delete(source);
Files.move(temp, source);
} catch (IOException | SecurityException se) {
System.out.println("Error -- " + se.toString());
}
}
}
Output-
import java.applet.Applet;
import java.awt.*;
import java.util.*;
@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();
}
// 12 hour format
if (hour > 12) {
hour -= 12;
}
// 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);
Output-
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);
eq = new JButton("=");
buttonpanel.add(eq);
eq.addActionListener(this);
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;
}
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");
// Text component
t = new JTextArea();
// Create a menubar
JMenuBar mb = new JMenuBar();
m1.add(mi1);
m1.add(mi2);
m1.add(mi3);
m1.add(mi9);
m2.add(mi4);
m2.add(mi5);
m2.add(mi6);
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:");
if (r == JFileChooser.APPROVE_OPTION) {
try {
// Create a file writer
FileWriter wr = new FileWriter(fi, false);
// 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:");
// File reader
FileReader fr = new FileReader(fi);
// Buffered reader
BufferedReader br = new BufferedReader(fr);
// Initialize sl
sl = br.readLine();
// 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:
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];
if ( this.lines != null )
{
int step = height;
for ( String line : this.lines )
paintString( g, line, height += step );
}
}
/**
* Bean with constrained properties.
*/
public class MyBean
extends JComponent
implements Serializable
{
private String title;
private String[] lines = new String[10];
if ( this.lines != null )
{
int step = height;
for ( String line : this.lines )
paintString( g, line, height += step );
}
}