OOS Pract File
OOS Pract File
NAWABGANJ KANPUR
3. Write a program in Java showing the action from three threads using a suitable
example.
Sol.
public class ThreadExample implements Runnable {
private String message;
4. Write a program of threads in Java showing inter leaving of actions from two threads: t1
& t2 synchronizing on a shared object. Let t1 print message Ping and t2 prints message
Pong. Take as command line arguments the following inputs to the program:
Sleep interval for thread t1Sleep interval for thread t2Messages per cycle Number of
Cycles.
Sol.
public class PingPong implements Runnable {
private Object lock;
private String message;
private int sleepInterval;
private int messagesPerCycle;
public PingPong(Object lock, String message, int sleepInterval, int messagesPerCycle) {
this.lock = lock;
this.message = message;
this.sleepInterval = sleepInterval;
this.messagesPerCycle = messagesPerCycle;
}
5. Write a program in Java which converts a text file into all capital letters.
Sol.
import java.io.*;
6. Write a program to create a sequential file that could store details about five products.
Details include product code, cost, no. Of items available and number of items available
and are provided through keyboard.
Sol.
import java.io.*;
import java.util.Scanner;
7. Create a Person class with private instance variables for Person’s name and birth date.
Add appropriate accessor methods to access the variables. Then create a subclass
CollegeGraduate with private instance variables for the student’s GPA and year of
graduation and appropriate accessors for these variables. Don’t forget to include
appropriate constructors for your classes. Then create a class with a main() method that
manages your classes.
Sol.
public class Person {
private String name;
private String birthDate;
8. Develop an applet that receives three numeric values from the user and displays the
largest of the three on the screen. Write a HTML page that embeds this applet.
Sol.
import java.applet.Applet;
import java.awt.*;
9. Write an applet which draws a human face with ovals and arcs.
Sol.
import java.applet.Applet;
import java.awt.*;
<!DOCTYPE html>
<html>
<head>
<title>Face Applet</title>
</head>
<body>
<h1>Face Applet</h1>
<hr>
<applet code="FaceApplet.class" width="300" height="300">
</applet>
</body>
</html>
10. Write servlets that accepts user preferences (color, hobby etc.) from user, saves it as
cookie onuser machine and reads the cookie from the user machine.
Sol.
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
response.sendRedirect("preferences.jsp");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// Read user preferences from cookies
Cookie[] cookies = request.getCookies();
String color = null, hobby = null, movie = null;
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals("color")) {
color = cookie.getValue();
} else if (cookie.getName().equals("hobby")) {
hobby = cookie.getValue();
} else if (cookie.getName().equals("movie")) {
movie = cookie.getValue();
}
}
}
11. Write an AWT application with checkbox such that all cable TV channels will be
displayedfrom the selected category.
Sol.
import java.awt.*;
import java.awt.event.*;
public TVChannels() {
setTitle("TV Channels");
setSize(400, 300);
setLayout(new FlowLayout());
news.addItemListener(this);
sports.addItemListener(this);
movies.addItemListener(this);
}
if (sports.getState()) {
channels.add("ESPN");
channels.add("Fox Sports");
}
if (movies.getState()) {
channels.add("HBO");
channels.add("Star Movies");
}
if (news.getState()) {
selectedCategory.setText(selectedCategory.getText() + " News ");
}
if (sports.getState()) {
selectedCategory.setText(selectedCategory.getText() + " Sports ");
}
if (movies.getState()) {
selectedCategory.setText(selectedCategory.getText() + " Movies ");
}
}
12. Create a simple Swing based applet that displays two buttons. Each time a button is
clicked, amessage is displayed that states which button was clicked.
Sol.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
13. Create JSP code that uses a persistant cookie (i.e. a cookie with an expiration date in
the future) to keep track of how many times the client computer has visited the page. Use
setMaxAge method to remain on the client’s computer for one month. Display the number
ofpage hits (i.e. cookie’s value) every time the page loads.
Sol.
<%@ page import="java.util.*" %>
<%
// Get the page hit count from the cookie
int count = 0;
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (int i = 0; i < cookies.length; i++) {
if (cookies[i].getName().equals("pageHitCount")) {
count = Integer.parseInt(cookies[i].getValue());
break;
}
}
}
14. Write JSP program that asks user his favourite color as request parameter and sets it
as thebackground color of the page or sets the background color white if the parameter
value is null.
Sol.
<!DOCTYPE html>
<html>
<head>
<title>Favorite Color</title>
</head>
<body <% if(request.getParameter("color") != null) { %>
style="background-color: <%= request.getParameter("color") %>;"
<% } else { %>
style="background-color: white;"
<% } %>>
<h1>What's your favorite color?</h1>
<form method="get">
<label>Color:</label>
<input type="text" name="color">
<button type="submit">Submit</button>
</form>
</body>
</html>
15. Write a program in Java to show the mouse click event. The program should change
thebackground colour of window randomly at each mouse click.
Sol.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
public MouseClickEventDemo() {
setTitle("Mouse Click Event Demo");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPane = new JPanel();
contentPane.setPreferredSize(new Dimension(300, 300));
contentPane.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
contentPane.setBackground(getRandomColor());
}
});
setContentPane(contentPane);
pack();
setVisible(true);
random = new Random();
}
Lab Assignment: 1
Model a “Traffic Signal System for a City Traffic Crossroad Circle” using Object Oriented
Methodology. Traffic Signal may be designed as a Class. Design Class Diagram and
implement the class in Java. You may use Java Graphics library to make a Visual Model of
Traffic System to simulate the real one.
Sol.
the class diagram for our TrafficSignal class:
+ +
| TrafficSignal |
+ +
| +currentSignal: SignalColor |
| +eastWestSignal: SignalColor |
| +northSouthSignal: SignalColor |
+ +
| +changeSignal(): void |
| +getEastWestSignal(): SignalColor |
| +getNorthSouthSignal(): SignalColor |
+ +
+ +
| SignalColor |
+ +
| -color: Color |
+ +
| +SignalColor(color: Color) |
| +getColor(): Color |
+ +
the implementation of the TrafficSignal class in Java, using the Java Graphics library to
draw the traffic signal:
import javax.swing.*;
import java.awt.*;
public TrafficSignal() {
this.currentSignal = SignalColor.RED;
this.eastWestSignal = SignalColor.RED;
this.northSouthSignal = SignalColor.GREEN;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLACK);
g.fillRect(0, 0, getWidth(), getHeight());
x = getWidth() / 2 - diameter / 2;
y = getHeight() / 2 - diameter / 2;
g.setColor(eastWestSignal.getColor());
g.fillOval(x, y, diameter, diameter);
x = getWidth() / 2 - diameter / 2;
y = getHeight() / 6 * 5 - diameter / 2;
g.setColor(northSouthSignal.getColor());
g.fillOval(x, y, diameter, diameter);
}
while (true) {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
trafficSignal.changeSignal();
}
}
}
enum SignalColor {
RED(Color.RED), YELLOW(Color.YELLOW), GREEN(Color.GREEN);
SignalColor(Color color) {
this.color = color;
}
Write a JSP program which displays a webpage containing arrival of new items within a
particular month in the different branches of a retail company.
Sol.
ItemServlet.java:
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
try {
// Load the MySQL JDBC driver
Class.forName("com.mysql.jdbc.Driver");
// Create a SQL statement to retrieve the items from the database based on the selected
month
String sql = "SELECT * FROM items WHERE MONTH(arrival_date) = ?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, selectedMonth);
rs = ps.executeQuery();
// Loop through the ResultSet and add each item to the ArrayList
while (rs.next()) {
Item item = new Item();
item.setItemId(rs.getInt("item_id"));
item.setItemName(rs.getString("item_name"));
item.setArrivalDate(rs.getDate("arrival_date"));
item.setBranchName(rs.getString("branch_name"));
item.setItemCategory(rs.getString("item_category"));
items.add(item);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
// Close the database resources
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
itemList.jsp:
Item.java:
public class Item {
Lab Assignment: 3
Write a program using Servlet and JDBC for developing an online submission of an
examination form. You are required to create a database comprising of the following
fields:-
I. Student Name
II. Enrollment No.
III. Course Code (s)
IV. Regional Center Code
V. E- mail Id.
Sol.
we will create a form to take input from the user:
exam-form.jsp:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Exam Form Submission</title>
</head>
<body>
<h1>Exam Form Submission</h1>
<form method="post" action="submit-form">
<label for="name">Student Name:</label>
<input type="text" id="name" name="name" required><br><br>
Next, we will create a servlet to handle form submission and insert the data into the database:
ExamFormServlet.java:
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/submit-form")
public class ExamFormServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
// Database credentials
private static final String USER = "username";
private static final String PASS = "password";
stmt.setString(1, name);
stmt.setString(2, enrollment);
stmt.setString(3, course);
stmt.setString(4, center);
stmt.setString(5, email);
if (rows > 0) {
response.getWriter().println("Form submitted successfully!");
} else {
response.getWriter().println("Failed to submit form!");
}
} catch (SQLException e) {
response.getWriter().println("Database error: " + e.getMessage());
}
}
}
USE examformdb;