Java Practicle
Java Practicle
the contents of
also remove all these elements.
import java.util.;
public class A1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
sc.close();
}
}
\\ Write a java program to read ‘n’ names of your friends, store it into linked list,
also display contents of the same.
import java.util.;
public class A2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
\\ Write a program to create a new tree set, add some colors (string) and
print out the tree set.
import java.util.Scanner;
import java.util.TreeSet;
public class A3 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
TreeSet<Object> ts = new TreeSet<>();
\\ Create the hash table that will maintain the mobile number and student name.
Display the contact list.
import java.util.Hashtable;
public class A4 {
public static void main(String[] args) {
Hashtable<String, String> hashtable = new Hashtable<String, String>();
hashtable.put("Prasad", "8796465800");
hashtable.put("Ashish", "8806503414");
hashtable.put("Suhas", "8629913414");
hashtable.put("Sanket", "7118919895");
System.out.println(hashtable);
}
}
\\ Accept 'n' integers from the user. Store and display integers in sorted order having proper collection class.
The collection should not accept duplicate elements
import java.util.TreeSet;
import java.util.Scanner;
public class B1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
TreeSet<Object> ts = new TreeSet<>();
import java.util.HashMap;
import java.util.TreeMap;
public class B2 {
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<>();
map.put("Prasad", 2002);
map.put("Ashish", 2001);
map.put("Suhas", 2002);
map.put("Swayam", 2001);
map.put("Sanket", 2002);
System.out.println("\nHashMap Details Before Sorting :\n" + map);
\\ Write a program that loads names and phone numbers from a text file where the data is organized as one line per
.it takes a name or phone number as input and prints the corresponding other value from the hash table
(hint: use hash tables). (For file content use B3.txt)
import java.io.*;
import java.util.Hashtable;
import java.util.Scanner;
public class B3 {
public static void main(String[] args) {
try {
File f = new File("B3.txt");
BufferedReader br = null;
br = new BufferedReader(new FileReader(f));
Hashtable<String, String> table = new Hashtable<>();
Scanner sc = new Scanner(System.in);
String line = "";
while ((line = br.readLine()) != null) {
String[] parts = line.split(":");
if (table.containsKey(key)) {
System.out.println(table.get(key));
br.close();
sc.close();
}
} catch (Exception e) {
System.out.println(e);
}
}
}
\\ Create a java application to store city names and their STD codes using an appropriate collection. The GUI should a
No duplicates) ii. Remove a city from the collection iii.
Search for a city name and display the code
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
C1() {
setTitle("City STD Code Information");
setSize(700, 500);
setVisible(true);
setLayout(new GridLayout(3, 2, 20, 20));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
p1 = new JPanel();
p1.setLayout(new GridLayout(1, 3, 5, 5));
add(p1);
}// SETC1
if (ae.getSource() == btnadd) {
// System.out.println(table.containsKey(name) || table.containsValue(std));
if (table.containsKey(name) || table.containsValue(std)) {
String s2 = "Duplicates are not allowded ";
JOptionPane.showMessageDialog(null,s2,s2, JOptionPane.ERROR_MESSAGE);
} else {
table.put(name, std);
System.out.println(table);
JOptionPane.showMessageDialog(null, "Succesfully Added City & STD Code", name,
JOptionPane.INFORMATION_MESSAGE);
}
txtname.setText("");
txtstd.setText("");
}
if (ae.getSource() == btndelete) {
String s1 = JOptionPane.showInputDialog(null, "Enter City to remove");
table.remove(s1);
JOptionPane.showMessageDialog(null, "Succesfully removed City & STD Code", name,
JOptionPane.INFORMATION_MESSAGE);
}
if (ae.getSource() == btnsearch) {
String s1 = JOptionPane.showInputDialog(null, "Enter City");
if (table.containsKey(s1)) {
String s2 = "STD Code: " + table.get(s1);
JOptionPane.showMessageDialog(null, s2);
} else {
JOptionPane.showMessageDialog(null, "ERROR OCCURED");
\\ Write a program to create link list of integer objects. Do the following: i.add element at first position ii.delete last e
iii.display the size of link list
import java.util.LinkedList;
import java.util.Scanner;
public class C2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
LinkedList<Object> ll = new LinkedList<>();
ll.add(1);
ll.add(2);
ll.add(3);
ll.addFirst(0);
sc.close();
}
}
\\ Read a text file, specified by the first command line argument, into a list. The program should then display a menu
line 2. Delete line 3. Append line 4. Modify line 5. Exit When the user selects Exit, save the contents of the list to
the file and end the program. (For file content use C3.txt)
import java.util.*;
import java.io.*;
public class C3 {
public static void main(String arg[]) {
Scanner sc = new Scanner(System.in);
try {
// Here, we have used command line argument , so at the time of run the code use command java C3 C3.txt
File f = new File(arg[0]);
BufferedReader br = null;
} // while
// main logic
do {
System.out.println("1.Insert Line\n2.Delete Line\n3.Append Line\n4.Modify Line\n5.Exit");
System.out.println("Enter choice: ");
ch = sc.nextInt();
String l1 = "This is a new Line";
switch (ch) {
case 1:
al.add(l1);
break;
case 2:
al.remove(l1);
break;
case 3:
al.add(l1);
break;
case 4:
int n = al.size() - 1;
al.set(n, "\tUpdated line");
break;
case 5:
ListIterator<Object> li = al.listIterator();
while (li.hasNext()) {
String l2 = (String) li.next();
byte b[] = l2.getBytes();
fout.write(b);
}
System.exit(1);
break;
}
} while (ch < 6);
br.close();
fout.close();
} catch (Exception e) {
System.out.println(e);
}
sc.close();
}
}
\\ Program to define a thread for printing text on output screen for ‘n’ number of times. Create 3 threads and run the
ple: i. First thread prints “COVID19” 10 times. ii. Second thread prints “LOCKDOWN2020” 20 times iii.
Third thread prints “VACCINATED2021” 30 times
t1.start();
t2.start();
t3.start();
}
}
\\ Write a program in which thread sleep for 6 sec in the loop in reverse order from 100 to
1 and change the name of thread.
public class A2 {
public static void main(String[] args) {
try {
Thread t = Thread.currentThread();
t.setName("Reverse Thread");
System.out.println(t);
for (int i = 100; i >= 1; i--) {
System.out.println(i);
Thread.sleep(6000);
}
} // try
catch (Exception e) {
System.out.println(e);
} // catch
}// main
}// class
\\ Write a program to solve producer consumer problem in which a producer produces a value and consumer consu
(Hint: use thread synchronization)
class shop {
int material;
boolean flag = false;
}// shop
public class A3 {
public static void main(String[] args) {
shop s = new shop();
Producer p = new Producer(s, 1);
Consumer c = new Consumer(s, 1);
p.start();
c.start();
}
}
\\ Write a program for a simple search engine. Accept a string to be searched. Search for the string in all text files in t
e result should display the filename,
line number where the string is found.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.Scanner;
}
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class B2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter Search string :");
String str = sc.nextLine();
\\ Write a program that simulates a traffic light. The program lets the user select one of three lights: red, yellow, or gr
ate message with “stop” or “ready” or “go”should appear above the buttons in a selected color.
Initially there is no message shown
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
JLabel red;
JLabel yellow;
JLabel green;
C1() {
setLayout(new FlowLayout(FlowLayout.CENTER, 10, 10));
setSize(800, 700);
setTitle("Java Project Program");
setLocation(400, 150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
rb1.setForeground(Color.red);
rb2.setForeground(Color.yellow);
rb3.setForeground(Color.green);
rb1.setBackground(Color.lightGray);
rb2.setBackground(Color.lightGray);
rb3.setBackground(Color.lightGray);
panel.add(red);
panel.add(yellow);
panel.add(green);
red.setVisible(false);
yellow.setVisible(false);
green.setVisible(false);
g1.add(rb1);
g1.add(rb2);
g1.add(rb3);
this.add(panel);
this.pack();
setVisible(true);
}
}
}
\\ Create a PROJECT table with fields project_id, Project_name, Project_description, Project_Status. etc. Insert values i
a tabular format on the screen.(using swing). --for
database material use here project.pgsql file.
import java.sql.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import javax.swing.table.DefaultTableModel;
JTextField txtid,txtname,txtdesc,textstatus;
JButton b1,b2,b3,b4;
StudentprojectDisplay(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("STUDENT PROJECT INFO");
p1=new JPanel();
p1.setLayout(new GridLayout(5,5,10,10));
b1 = new JButton("Display");
p1.add(b1);
b1.addActionListener(this);
add(p1,BorderLayout.WEST);
setVisible(true);
setSize(400,400);
}//ProjectDetails()
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==b1)//display
{
frm = new JFrame("Display");
frm.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frm.setLayout(new BorderLayout());
DefaultTableModel model = new DefaultTableModel();
model.setColumnIdentifiers(columnNames);
table = new JTable();
table.setModel(model);
JScrollPane scroll = new JScrollPane(table);
try{
Class.forName("org.postgresql.Driver");
// Use database name & password according to your "dbname","pass"
con = DriverManager.getConnection("jdbc:postgresql://localhost/postgres", "postgres", "dsk");
st = con.createStatement();
rs = st.executeQuery("select * from project");
while(rs.next()){
p_id = rs.getString(1);
p_name = rs.getString(2);
p_description = rs.getString(3);
p_status = rs.getString(4);
}//while
frm.add(scroll);
frm.setVisible(true);
frm.setSize(400,400);
}//try
catch(Exception e){
JOptionPane.showMessageDialog(null,e,"Error",JOptionPane.ERROR_MESSAGE);
}
}//if
}
\\ Write a program to display information about the database and list all the tables in the
database. (Use DatabaseMetaData).
import java.sql.;
// Establish Connection
Connection conn = DriverManager.getConnection("jdbc:postgresql://localhost/postgres", "postgres", "dsk");
DatabaseMetaData dbmd = conn.getMetaData();
System.out.println("\t-----------------------------------------------------------------------");
System.out.println("\t\tDriver Name : " + dbmd.getDriverName());
System.out.println("\t\tDriver Version : " + dbmd.getDriverVersion());
System.out.println("\t\tUserName : " + dbmd.getUserName());
System.out.println("\t\tDatabase Product Name : " + dbmd.getDatabaseProductName());
System.out.println("\t\tDatabase Product Version : " + dbmd.getDatabaseProductVersion());
System.out.println("\t---------------------------------------------------------------------");
while (rs.next()) {
System.out.println(rs.getString("TABLE_NAME"));
}
rs.close();
conn.close();
} // try
catch (Exception e) {
System.out.println(e);
} // catch
}// main
}// metadata
import java.sql.*;
// Establish Connection
Connection conn = DriverManager.getConnection("jdbc:postgresql://localhost/postgres", "postgres", "dsk");
rs.close();
stmt.close();
conn.close();
} // try
catch (Exception e) {
System.out.println(e);
} // catch
}
}
\\ Create a MOBILE table with fields Model_Number, Model_Name, Model_Color, Sim_Type, NetworkType, BatteryCap
e. Write a menu
driven program to pass the input using Command line argument to perform the following operations on MOBILE tab
Insert 2. Modify 3. Delete 4. Search 5. View All 6. Exit. --for database material use here mobile.pgsql file
import java.sql.*;
import java.util.*;
// Establish Connection
conn = DriverManager.getConnection("jdbc:postgresql://localhost/postgres", "postgres", "dsk");
sc.nextLine();
System.out.println("Enter Model_Name: ");
String name = sc.nextLine();
pstmt.setString(2, name);
sc.nextLine();
System.out.println("Enter Processor_Type: ");
String pr = sc.nextLine();
pstmt.setString(8, pr);
case 2:
String SQL = "update mobile set name=? where mno=?";
pstmt = conn.prepareStatement(SQL);
sc.nextLine();
System.out.println("Enter Updated Model name: ");
String mname = sc.nextLine();
pstmt.setString(1, mname);
case 3:
pstmt = conn.prepareStatement("delete from mobile where mno=?");
System.out.println("Enter Model No for Delete Record: ");
int model = sc.nextInt();
pstmt.setInt(1, model);
case 4:
pstmt = conn.prepareStatement("select * from mobile where mno=?");
System.out.println("Enter Model No for serach Record: ");
int m = sc.nextInt();
pstmt.setInt(1, m);
rs = pstmt.executeQuery();
System.out.println("\n------------------------------------------------------------------------------------------------------------------")
while (rs.next()) {
System.out.println(rs.getInt(1) + "\t" + rs.getString(2) + "\t" + rs.getString(3) + "\t"
+ rs.getString(4) + "\t" + rs.getInt(5) + "\t" + rs.getInt(6) + "\t" + rs.getInt(7)
+ "\t" + rs.getString(8));
}
System.out.println("------------------------------------------------------------------------------------------------------------------");
break;
case 5:
stmt = conn.createStatement();
rs = stmt.executeQuery("select * from mobile");
System.out.println("\n------------------------------------------------------------------------------------------------------------------");
while (rs.next()) {
System.out.println(rs.getInt(1) + "\t" + rs.getString(2) + "\t" + rs.getString(3) + "\t"
+ rs.getString(4) + "\t" + rs.getInt(5) + "\t" + rs.getInt(6) + "\t" + rs.getInt(7)
+ "\t" + rs.getString(8));
}
System.out.println("------------------------------------------------------------------------------------------------------------------");
break;
case 6:
System.exit(1);
rs.close();
stmt.close();
pstmt.close();
conn.close();
sc.close();
}
} while (true);
} // try
catch (Exception e) {
System.out.println(e);
} // catch
}// main
}// class
create table mobile(mno int ,name char(20),color char(20),sim char(20), Battery int, internal int , ram int , pr char(25))
\\ - Design a following Registration form and raise an appropriate exception if invalid information
is entered like Birth Year ‘0000’
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
Cowin() {
setTitle("Cowin Registration");
setSize(800, 600);
r3 = new JRadioButton("Covishield");
p2.add(r3);
r3.setActionCommand("Covishield");
r4 = new JRadioButton("Covaxin");
p2.add(r4);
r4.setActionCommand("Covaxin");
r7 = new JRadioButton("Afternoon");
p3.add(r7);
r7.setActionCommand("Afternoon");
r8 = new JRadioButton("Evening");
p3.add(r8);
r8.setActionCommand("Evening");
add(p3);
// Button
p4 = new JPanel();
p4.setLayout(new FlowLayout());
add.addActionListener(this);
bg = new ButtonGroup();
bg.add(r1);
bg.add(r2);
setVisible(true);
}
try {
if (year == 0000) {
throw new InvalidBirthDateException();
} else {
Connection conn = null;
PreparedStatement pstmt = null;
try {
// load a driver
Class.forName("org.postgresql.Driver");
// Establish Connection
// Use database name & password according to your "dbname","pass"
conn = DriverManager.getConnection("jdbc:postgresql://localhost/postgres", "postgres", "dsk");
pstmt = conn.prepareStatement("insert into cowin values(?,?,?,?,?,?,?)");
pstmt.setString(1, adharno);
pstmt.setInt(2, year);
pstmt.setString(3, phNo);
pstmt.setString(4, hospital);
pstmt.setString(5, age);
pstmt.setString(6, vaccine);
pstmt.setString(7, timestamp);
pstmt.close();
conn.close();
} // try
catch (Exception e) {
JOptionPane.showMessageDialog(null, e, "ERROR OCCURED", JOptionPane.ERROR_MESSAGE);
} // catch
}
} catch (InvalidBirthDateException e) {
JOptionPane.showMessageDialog(null, e, "ERROR OCCURED", JOptionPane.ERROR_MESSAGE);
}
}
}
}// CLASS
\\ Create tables : Course (courseid, coursename, courseinstructor) and Student (studentid, studentname, studentclas
GUI based system for performing the following operations on the tables: Course : Add Course, View All students of a
tudents, Search student.
--for database material use here student_course.pgsql file.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import javax.swing.table.*;
AddStudent stdobj;
Addcourse cobj;
Student_Course() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("STUDENT INFO");
setLayout(new GridLayout(4, 4, 40, 20));
setVisible(true);
setSize(400, 400);
p1 = new JPanel();
p1.setLayout(new FlowLayout());
add(p1);
p2 = new JPanel();
p2.setLayout(new FlowLayout());
add(p2);
// adding action listener to all buttons
addstd.addActionListener(this);
addcourse.addActionListener(this);
Delete.addActionListener(this);
View.addActionListener(this);
Search.addActionListener(this);
course.addActionListener(this);
try {
Class.forName("org.postgresql.Driver");
// Use database name & password according to your "dbname","pass"
con = DriverManager.getConnection("jdbc:postgresql://localhost/postgres", "postgres", "dsk");
if (ae.getSource() == View) {
frm = new JFrame("Student DISPLAY");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setLayout(new BorderLayout());
DefaultTableModel model = new DefaultTableModel();
model.setColumnIdentifiers(columnNames);
table = new JTable();
table.setModel(model);
table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
table.setFillsViewportHeight(true);
scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
st = con.createStatement();
rs = st.executeQuery("select * from student1");
while (rs.next()) {
s_id = rs.getString(1);
s_name = rs.getString(2);
s_class = rs.getString(3);
// This all coloumn names are taken from project table.
model.addRow(new Object[] { s_id, s_name, s_class });
} // while
frm.add(scroll);
frm.setVisible(true);
frm.setSize(400, 400);
} // view
if (ae.getSource() == addstd) {
stdobj = new AddStudent();
} // adding student record
if (ae.getSource() == Search) {
String s1 = JOptionPane.showInputDialog(null, "Enter Student Name");
rs = pstmt.executeQuery();
while (rs.next()) {
String result = rs.getInt(1) + "\t" + rs.getString(2) + "\t" + rs.getString(3);
JOptionPane.showMessageDialog(null, result);
}
if (ae.getSource() == Delete) {
String s1 = JOptionPane.showInputDialog(null, "Enter Student Name ");
pstmt = con.prepareStatement("delete from student1 where s_name=?");
pstmt.setString(1, s1);
pstmt.executeUpdate();
JOptionPane.showMessageDialog(null, "Record deleted");
if (ae.getSource() == addcourse) {
cobj = new Addcourse();
} // adding course record
if (ae.getSource() == course) {
setLayout(new BorderLayout());
DefaultTableModel model = new DefaultTableModel();
model.setColumnIdentifiers(SC_columns);
table = new JTable();
table.setModel(model);
table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
table.setFillsViewportHeight(true);
scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
pstmt = con.prepareStatement(
"select s_name from SC where c_name = ?");
pstmt.setString(1, s1);
rs = pstmt.executeQuery();
while (rs.next()) {
st_name = rs.getString(1);
} // while
frmdisp.add(scroll);
frmdisp.setVisible(true);
frmdisp.setSize(400, 400);
} // try
catch (Exception e) {
JOptionPane.showMessageDialog(null, e, "Error", JOptionPane.ERROR_MESSAGE);
}
AddStudent() {
setTitle("Student Information");
setSize(400, 500);
setVisible(true);
setLayout(new GridLayout(4, 2, 40, 40));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}// constructor
int rn = Integer.parseInt(txtroll.getText());
String name = (txtname.getText());
String cname = (txtclass.getText());
// Establish Connection
conn = DriverManager.getConnection("jdbc:postgresql://localhost/postgres", "postgres", "dsk");
if (str.equals("Submit")) {
pstmt = conn.prepareStatement("insert into student1 values(?,?,?)");
pstmt.setInt(1, rn);
pstmt.setString(2, name);
pstmt.setString(3, cname);
txtroll.setText("");
txtname.setText("");
txtclass.setText("");
}
pstmt.close();
conn.close();
} // try
catch (Exception e) {
System.out.println(e);
} // catch
}
}
class Addcourse extends JFrame implements ActionListener {
JTextField txtcname, txtins, txtcno;
JButton btnadd, btnclear;
Addcourse() {
setTitle("course Information");
setSize(400, 500);
setVisible(true);
setLayout(new GridLayout(4, 2, 40, 40));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}// constructor
int cn = Integer.parseInt(txtcno.getText());
String name = (txtcname.getText());
String course = (txtins.getText());
// Establish Connection
conn = DriverManager.getConnection("jdbc:postgresql://localhost/postgres", "postgres", "dsk");
if (str.equals("Submit")) {
pstmt = conn.prepareStatement("insert into course values(?,?,?)");
pstmt.setInt(1, cn);
pstmt.setString(2, name);
pstmt.setString(3, course);
}
pstmt.close();
conn.close();
} // try
catch (Exception e) {
System.out.println(e);
} // catch
}
}
\\ Create the following tables and relations, for an INVESTMENT firm EMP(empid ,empname, empaddress, empconta
nvest in one or more investments, hence he can be an investor. But an investor need not be an employee of the firm
h appropriate values. i. Display the List the distinct names of person who are either employees, or investors or both.
--for database material use here employee.pgsql fil
import java.sql.*;
// Establish Connection
conn = DriverManager.getConnection("jdbc:postgresql://localhost/postgres", "postgres", "dsk");
System.out.println("\n---------------");
System.out.println("Employees");
System.out.println("---------------");
rs = stmt.executeQuery("select empname from employee ");
while (rs.next()) {
System.out.println(rs.getString("empname"));
} // while
System.out.println("---------------");
System.out.println("\n---------------");
System.out.println("Investors");
System.out.println("---------------");
rs = stmt.executeQuery("select invname from investor ");
while (rs.next()) {
System.out.println(rs.getString("invname"));
} // while
System.out.println("---------------");
System.out.println(
"\n------------------------------------------------------------------------------------------");
System.out.println(
"Display the List the distinct names of person who are either employees or investor or both");
System.out.println(
"------------------------------------------------------------------------------------------");
rs = stmt.executeQuery("select empname from employee union select invname from investor");
while (rs.next()) {
System.out.println(rs.getString("empname"));
} // while
System.out.println("---------------");
System.out.println("\n--------------------------------------------------");
System.out.println("List the names of Employees who are not Investors");
System.out.println("--------------------------------------------------");
rs = stmt.executeQuery("select empname from employee except select invname from investor");
while (rs.next()) {
System.out.println(rs.getString("empname"));
} // while
System.out.println("---------------");
} // try
catch (Exception e) {
System.out.println(e);
} // catch
}// main
}// class
\\ Design a servlet that provides information about a HTTP request from a client, such as IP address and browser typ
h the servlet is running, such as the operating system type,and the names of
currently loaded servlets.
index.html
<html>
<body>
<form action="lmn" method="get">
Username:<input type="text" name="t1">
<input type="submit" >
</form>
</body>
</html>
web.xml
<web-app>
<servlet>
<servlet-name>abc</servlet-name>
<servlet-class>serverInfo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>abc</servlet-name>
<url-pattern>/lmn</url-pattern>
</servlet-mapping>
</web-app>
serverInfo.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class serverInfo extends HttpServlet implements Servlet
{
protected void doGet(HttpServletRequest req,HttpServletResponse res)throws
IOException,ServletException
{
res.setContentType("text/html");
PrintWriter pw=res.getWriter();
pw.println("<html><body><h2>Information about Http Request</h2>");
pw.println("<br>Server Name: "+req.getServerName());
pw.println("<br>Server Port: "+req.getServerPort());
pw.println("<br>Ip Address: "+req.getRemoteAddr());
//pw.println("<br>Server Path: "+req.getServerPath()); pw.println("<br>Client Browser:
"+req.getHeader("User-Agent"));
pw.println("</body></html>");
pw.close();
}
index.jsp
<%@ page language="java"%>
<%@ page import="java.util.Date" %>
<!DOCTYPE html>
<head>
<title>Index JSP Page</title>
</head>
<body>
<%-- out object example --%>
<table border="1"; style="background-color:#ffffcc; width:30%" >
<caption><h3>JSP Implicit object</h3></caption>
<tr><td><b>Current Time</b></td>
<td><% out.print(new Date()); %></td></tr>
<%-- response object example --%>
<%response.addCookie(new Cookie("Test","Value")); %>
<%-- application object example --%>
<tr><td><b>User context param value</b></td>
<td><%=application.getInitParameter("User") %></td></tr>
<%-- session object example --%>
<tr><td><b>User Session ID</b></td>
<td><%=session.getId() %></td></tr>
<%-- pageContext object example --%>
<% pageContext.setAttribute("Test", "Test Value"); %>
<tr><td><b>PageContext attribute</b></td>
<td>{Name="Test",Value="<%=pageContext.getAttribute("Test") %>"}</td></tr>
<%-- page object example --%>
<tr><td><b>Generated Servlet Name</b>:</td>
<td><%=page.getClass().getName() %></td></tr>
<%-- request object example --%>
<tr><td><b>Request User-Agent</b></td>
<td> <%=request.getHeader("User-Agent") %></td></tr>
</table>
</body>
</html>
web.xml
<web-app>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<context-param>
<param-name>User</param-name>
<param-value>Archana</param-value>
</context-param>
<servlet>
<servlet-name>xyz</servlet-name>
<jsp-file>/index.jsp</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>xyz</servlet-name>
<url-pattern>/test</url-pattern>
</servlet-mapping>
</web-app>
\\ Design an HTML page which passes customer number to a search servlet. The servlet
searches for the customer number in a database (customer table) and returns customer
details if found the number otherwise display error message.
ServletDatabase.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class servletDatabase extends HttpServlet
{
Connection cn;
public void init()
{
try
{
Class.forName("org.postgresql.Driver");
cn=DriverManager.getConnection("jdbc:postgresql://192.168.1.21:5432/
ty90","ty90","");
System.out.println("Hii");
}
catch(Exception ce)
{
ce.printStackTrace();
}
}
public void doGet(HttpServletRequest req, HttpServletResponse resp)throws
ServletException,IOException
{
resp.setContentType("text/html");
PrintWriter pw=resp.getWriter();
try
{
int rno=Integer.parseInt(req.getParameter("t1"));
String qry="Select * from student1 where rollno="+rno;
Statement st=cn.createStatement();
ResultSet rs=st.executeQuery(qry);
while(rs.next())
{
pw.print("<table border=1>");
pw.print("<tr>");
pw.print("<td>" + rs.getInt(1) + "</td>");
pw.print("<td>" + rs.getString(2) + "</td>");
pw.print("<td>" + rs.getFloat(3) + "</td>");
pw.print("</tr>");
pw.print("</table>");
}
}
catch(Exception se)
{
se.printStackTrace();
}
pw.close();
}
}
index.html
<html>
<body>
<form action="Data" method="get">
Enter Roll No:<input type="text" name="t1">
<input type="submit">
</form>
</body>
</html>
web.xml
<web-app>
<servlet>
<servlet-name>def</servlet-name>
<servlet-class>servletDatabase</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>def</servlet-name>
<url-pattern>/Data</url-pattern>
</servlet-mapping>
</web-app>
\\ Design an HTML page containing option buttons (Maths, Physics, Chemistry and
Biology) and buttons submit and reset. When the user clicks submit, the server
responds by adding a cookie containing the selected subject and sends a message back
to the client. Program should not allow duplicate cookies to be written.
Addcookies.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class AddCookie extends HttpServlet
{
public void doPost(HttpServletRequest req, HttpServletResponse res) throws
ServletException,IOException
{
res.setContentType("text/html");
PrintWriter pw = res.getWriter();
Cookie []c = req.getCookies();
int id=1;
if(c!=null) id = c.length+1;
String value = req.getParameter("course");
String cname = "course"+id;
Cookie newCookie = new Cookie(cname,value);
res.addCookie(newCookie);
pw.println("<h4>Cookie added with value "+value+"</h4>");
}
}
web.xml
<web-app>
<servlet>
<servlet-name>AddCookie</servlet-name>
<servlet-class>AddCookie</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>AddCookie</servlet-name>
<url-pattern>/cookies</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>Button.html</welcome-file>
</welcome-file-list>
</web-app>
Button.html
<!doctype html>
<head>
<title>CookiesExample</title>
</head>
<body>
<form action="cookies" method="post">
<fieldset style="width:14%; background-color:#ccffcc">
<h2>Select Course</h2> <hr>
<input type='radio' name='course' value='Java'>Java<br>
<input type='radio' name='course' value='UNIX'>UNIX<br>
<input type='radio' name='course' value='MCA'>MCA<br>
<input type='radio' name='course' value='OOSE '>OOSE<br><br>
<input type='submit'> <input type='reset'><br>
</fieldset>
</form>
</body>
</html>
Paitient.jsp
<%@page contentType="text/html" import="java.sql.*" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<body>
<%! int hno;
String hname,address; %>
<%
try{
Class.forName("org.postgresql.Driver");
Connection cn=DriverManager.getConnection("jdbc:postgresql://192.168.1.21:5432/ty90","ty90", "");
Statement st=cn.createStatement();
ResultSet rs=st.executeQuery("select * from PATIENT");
%>
<table border="1" width="40%"> <tr> <td>Hospital No</td> <td>Name</td> <td>Address</td> </tr>
<% while(rs.next()) { %> <tr><td><%= rs.getInt("hno") %></td> <td><%= rs.getString("hname")
%></td> <td><%= rs.getString("address") %> </tr> <%
}
cn.close();
}catch(Exception e)
{
out.println(e);
}
%>
</body>
</html>
\\ Create a JSP paper for an online multiple choice test. The questions are ind selected from for an online mailen the
The choices are displayed
<%-- Sample questions and choices (you can replace with your own data) --%>
<%
// Define an array of questions
String[] questions = {
"What is the capital of France?",
"Which planet is known as the Red Planet?",
"Who is the author of 'To Kill a Mockingbird'?"
};
// Loop through each question and display it along with its choices
for (int i = 0; i < questions.length; i++) {
%>
<div>
<p><strong>Question <%= i+1 %>:</strong> <%= questions[i] %></p>
<ul>
<%
// Loop through choices for the current question and display them
for (int j = 0; j < choices[i].length; j++) {
%>
<li><input type="radio" name="question<%= i %>" value="<%= choices[i][j] %>"> <%= choices[i][j] %><
<%
}
%>
</ul>
</div>
<%
}
%>
# hellobeans.java
package springcore_example;
public class hellobean {
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public void sayHello() {
System.out.println(getMessage());
}
}
# Main.java
package springcore_example;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
@SuppressWarnings("resource")
ApplicationContext context = new
ClassPathXmlApplicationContext("beans.xml");
hellobean hello = (hellobean) context.getBean("helloWorld");
hello.sayHello();
}
}
# beans.xml
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="helloWorld" class="springcore_example.hellobean">
<property name="message" value="If you can't explain it simply,
you don't understand it well enough"/>
</bean>
</beans>
# hellobean.java
package springcore_example;
import java.util.List;
public class hellobean {
private List<Student> students;
public List<Student> getStudents() {
return students;
}
public void setStudents(List<Student> students) {
this.students = students;
}
public void printStudents() {
for (Student student : students) {
System.out.println("Student ID is: "+student.getId()+student.getName() + "
is " + student.getAge() + " years old.");
}
}
}
# Main.javapackage springcore_example;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext
# Student.java
package springcore_example;
public class Student {
private int id;
private String name;
private int age;
public int getId() {
return id;
}
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.time.LocalDate;
@SpringBootApplication
public class CurrentDateApplication {
@RestController
class CurrentDateController {
@GetMapping("/current-date")
public String getCurrentDate() {
LocalDate currentDate = LocalDate.now();
return "Current Date: " + currentDate.toString();
}
}
ackage com.journaldev.spring.form.model;
import java.util.Date;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Past;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.format.annotation.DateTimeFormat;
import com.journaldev.spring.form.validator.Phone;
public class Customer {
@Size(min=2, max=30)
private String name;
@NotEmpty @Email
private String email;
@NotNull
private Gender gender;
@DateTimeFormat(pattern="MM/dd/yyyy")
@NotNull @Past
private Date birthday;
@Phone
private String phone;
}
package com.journaldev.spring.form.model;
}
Phone.java code:
package com.journaldev.spring.form.validator;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
import java.lang.annotation.RetentionPolicy;
import javax.validation.Constraint;
import javax.validation.Payload;
@Documented
@Constraint(validatedBy = PhoneValidator.class)
@Target( { ElementType.METHOD, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface Phone {
String message() default "{Phone}";
}
package com.journaldev.spring.form.validator;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
@Override
public void initialize(Phone paramA) {
}
@Override
public boolean isValid(String phoneNo, ConstraintValidatorContext ctx) {
if(phoneNo == null){
return false;
}
//validate phone numbers of format "1234567890"
if (phoneNo.matches("\\d{10}")) return true;
//validating phone number with -, . or spaces
else if(phoneNo.matches("\\d{3}[-\\.\\s]\\d{3}[-\\.\\s]\\d{4}")) return true;
//validating phone number with extension length from 3 to 5
else if(phoneNo.matches("\\d{3}-\\d{3}-\\d{4}\\s(x|(ext))\\d{3,5}")) return true;
//validating phone number where area code is in braces ()
else if(phoneNo.matches("\\(\\d{3}\\)-\\d{3}-\\d{4}")) return true;
//return false if nothing matches the input
else return false;
}
}
package com.journaldev.spring.form.validator;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import com.journaldev.spring.form.model.Employee;
@Override
public void validate(Object obj, Errors errors) {
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "id", "id.required");
import java.util.HashMap;
import java.util.Map;
import javax.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.journaldev.spring.form.model.Customer;
@Controller
public class CustomerController {
public CustomerController(){
customers = new HashMap<String, Customer>();
}
}
package com.journaldev.spring.form.controllers;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Validator;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.journaldev.spring.form.model.Employee;
@Controller
public class EmployeeController {
@Autowired
@Qualifier("employeeValidator")
private Validator validator;
@InitBinder
private void initBinder(WebDataBinder binder) {
binder.setValidator(validator);
}
public EmployeeController() {
emps = new HashMap<Integer, Employee>();
}
@ModelAttribute("employee")
public Employee createEmployeeModel() {
// ModelAttribute value should be same as used in the empSave.jsp
return new Employee();
}
#Spring framework error messages to be used when conversion from form data to bean fails
typeMismatch.int={0} Value must be an integer
typeMismatch.java.lang.Integer={0} must be an integer
typeMismatch={0} is of invalid format
</springForm:form>
</body>
</html>
<%@ taglib uri="https://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib prefix="fmt" uri="https://java.sun.com/jsp/jstl/fmt" %>
<strong>Customer Name:${customer.name}</strong><br>
<strong>Customer Email:${customer.email}</strong><br>
<strong>Customer Age:${customer.age}</strong><br>
<strong>Customer Gender:${customer.gender}</strong><br>
<strong>Customer Birthday:<fmt:formatDate value="${customer.birthday}" type="date" /></strong><br>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
<%@ taglib uri="https://www.springframework.org/tags/form"
prefix="springForm"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Employee Save Page</title>
<style>
.error {
color: #ff0000;
font-style: italic;
font-weight: bold;
}
</style>
</head>
<body>
</springForm:form>
</body>
</html>
empSaveSuccess.jsp file:
<%@ taglib uri="https://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<html>
<head>
<title>Employee Saved Successfully</title>
</head>
<body>
<h3>
Employee Saved Successfully.
</h3>
<strong>Employee ID:${emp.id}</strong><br>
<strong>Employee Name:${emp.name}</strong><br>
<strong>Employee Role:${emp.role}</strong><br>
</body>
</html>
import java.util.*;
class thread implements Runnable
{
Thread t;
int i,no,sum;
int a[]=new int[1000];
thread(String s,int n)
{
Random rs = new Random();
t=new Thread(this,s);
no=n;
int j=0;
for(i=1;i<=1000;i++)
{
a[j]=rs.nextInt()%100;;
j++;
}
t.start();
}
public void run() {
for(i=0;i<100;i++)
{
sum=sum+a[no];
no++;
}
System.out.println("Sum = "+sum);
System.out.println("Avg ="+sum/100);
}
}
public class Slip12_2
{
public static void main(String[] arg) throws InterruptedException
{
thread t1=new thread("g",1);
t1.t.join();
thread t2=new thread("r",100);
t2.t.join();
thread t3=new thread("s",200);
t3.t.join();
thread t4=new thread("t",300);
t4.t.join();
thread t5=new thread("p",400);
t5.t.join();
thread t6=new thread("p",500);
t5.t.join();
thread t7=new thread("p",600);
t5.t.join();
thread t8=new thread("p",700);
t5.t.join();
thread t9=new thread("p",800);
t5.t.join();
thread t10=new thread("p",900);
t5.t.join();
}
}
import java.util.Random;
class Square extends Thread
{
int x;
Square(int n)
{
x = n;
}
public void run()
{
int sqr = x * x;
System.out.println("Square of " + x + " = " + sqr );
}
}
class Cube extends Thread
{
int x;
Cube(int n)
{
x = n;
}
public void run()
{
int cub = x * x * x;
System.out.println("Cube of " + x + " = " + cub );
}
}
class Number extends Thread
{
public void run()
{
Random random = new Random();
for(int i =0; i<10; i++)
{
int randomInteger = random.nextInt(100);
System.out.println("Random Integer generated : " + randomInteger);
Square s = new Square(randomInteger);
s.start();
Cube c = new Cube(randomInteger);
c.start();
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
System.out.println(ex);
}
}
}
}
public class LAB3B {
public static void main(String args[])
{
Number n = new Number();
n.start();
}
}
Output:
Random Integer generated : 82
Square of 82 = 6724
Cube of 82 = 551368
Random Integer generated : 34
Square of 34 = 1156
Cube of 34 = 39304
Random Integer generated : 17
Square of 17 = 289
Cube of 17 = 4913
Random Integer generated : 84
Square of 84 = 7056
Cube of 84 = 592704
Random Integer generated : 34
Cube of 34 = 39304
Square of 34 = 1156
Random Integer generated : 51
Square of 51 = 2601
Cube of 51 = 132651
Random Integer generated : 38
Square of 38 = 1444
Cube of 38 = 54872
Random Integer generated : 94
Square of 94 = 8836
Cube of 94 = 830584
Random Integer generated : 65
Cube of 65 = 274625
Square of 65 = 4225
Random Integer generated : 75
Square of 75 = 5625
Cube of 75 = 421875
\\ Define a thread to move a ball inside a panel vertically.The Ball should be created when
user clicks on the Start Button.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
boucingthread()
{
super();
t= new Thread(this);
x=10;
y=10;
t.start();
setSize(1000,200);
setVisible(true);
setTitle("BOUNCEING BOLL WINDOW");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void run()
{
try
{
while(true)
{
x+=10;
y+=10;
repaint();
Thread.sleep(1000);
}
}catch(Exception e)
{
}
}
g.drawOval(x,y,7,7);
\\ Using the concepts of thread synchronization create two threads as sender and receiver. Sender thread will set a m
onsole. The sender thread accepts the input message from console. Continue this process until sender
sets the message as "Good Bye Corona".