0% found this document useful (0 votes)
41 views

Java Practicle

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views

Java Practicle

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

\\ Write a java program to accept names of ‘n’ cities, insert same into array list collection and display

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

ArrayList<Object> al = new ArrayList<>();

System.out.println("Enter How many cities :");


int n = sc.nextInt();

System.out.println("Enter the Cities :");


sc.nextLine();
for (int i = 0; i < n; i++) {
String c = sc.nextLine();
al.add(c);
}
System.out.println("Cities :" + al);

System.out.println("ArrayList after removing the elements :");


al.clear();

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

LinkedList<Object> ll = new LinkedList<>();

System.out.println("Enter How many Friends :");


int n = sc.nextInt();

System.out.println("Enter the "+n+" Friends :");


sc.nextLine();
for (int i = 0; i < n; i++) {
String fl = sc.nextLine();
ll.add(fl);
}
System.out.println("Friends :" + ll);
sc.close();
}
}

\\ 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<>();

System.out.println("Enter How many Colours :");


int n = sc.nextInt();

System.out.println("Enter the "+n+" Colours :");


sc.nextLine();
for (int i = 0; i < n; i++) {
String c = sc.nextLine();
ts.add(c);
}
System.out.println("Colours :" + ts);
sc.close();
}
}

\\ 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<>();

System.out.println("Enter how many Numbers: ");


int n = sc.nextInt();

System.out.println("Enter the " + n + " Numbers: ");


for (int i = 0; i < n; i++) {
int num = sc.nextInt();
ts.add(num);
}
System.out.println("Numbers in Sorted Order and without Duplication :" + ts);
sc.close();
}
}

\\ Write a program to sort HashMap by keys and display the details


before sorting and after sorting.

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

TreeMap<Object,Object> tm = new TreeMap<>(map);


System.out.println("\nHashMap Details After Sorting :\n" + tm);
}
}

\\ 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(":");

String name = parts[0].trim();


String number = parts[1].trim();
if (!name.equals("") && !number.equals("")) {
table.put(name, number);
}
}
System.out.println("Enter Name :");
String key = sc.nextLine();

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.*;

public class C1 extends JFrame implements ActionListener {


JTextField txtname, txtstd;
JButton btnadd, btndelete, btnsearch;
JPanel p1;
Hashtable<String, String> table = new Hashtable<>();

C1() {
setTitle("City STD Code Information");
setSize(700, 500);
setVisible(true);
setLayout(new GridLayout(3, 2, 20, 20));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JLabel name = new JLabel("Enter City Name: ");


add(name);
txtname = new JTextField(10);
add(txtname);

JLabel stdcode = new JLabel("Enter STD Code: ");


add(stdcode);
txtstd = new JTextField(10);
add(txtstd);

JLabel op = new JLabel("Choose Operation: ");


add(op);

p1 = new JPanel();
p1.setLayout(new GridLayout(1, 3, 5, 5));

btnadd = new JButton("Add");


p1.add(btnadd);
btnadd.addActionListener(this);

btndelete = new JButton("Delete");


p1.add(btndelete);
btndelete.addActionListener(this);

btnsearch = new JButton("Search");


p1.add(btnsearch);
btnsearch.addActionListener(this);

add(p1);

}// SETC1

public void actionPerformed(ActionEvent ae) {

String name = (txtname.getText());


String std = (txtstd.getText());

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

public static void main(String[] args) {


new C1();
}
}

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

System.out.println("\nElements in List :\n" + ll);

ll.addFirst(0);

System.out.println("\nList after adding Elements at First :\n" + ll);


ll.removeLast();

System.out.println("\nList after deleting Last Element :\n" + ll);

System.out.println("\nSize of the List :\n" + ll.size());

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;

br = new BufferedReader(new FileReader(f));


FileOutputStream fout = new FileOutputStream(arg[0]);
int ch;
ArrayList<Object> al = new ArrayList<>();

String line = "";


while ((line = br.readLine()) != null) {
al.add(line);

} // 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

public class A1 extends Thread {


String str;
int n;

A1(String str, int n) {


this.str = str;
this.n = n;
}

public void run() {


try {
for (int i = 0; i < n; i++) {
System.out.println(getName() + " : " + str);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
A1 t1 = new A1("COVID19", 10);
A1 t2 = new A1("LOCKDOWN2020", 20);
A1 t3 = new A1("VACCINATED", 30);

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;

public synchronized int get() {


while (flag == false) {
try {
wait();
} catch (Exception e) {
e.getStackTrace();
} // catch
} // while
flag = false;
notify();
return material;
}// get

public synchronized void put(int value) {


while (flag == true) {
try {
wait();
} catch (Exception e) {
e.getStackTrace();
} // catch
} // while
material = value;
flag = true;
notify();
}// put

}// shop

class Consumer extends Thread {


shop sh;
int no;

public Consumer(shop shp, int no) {


sh = shp;
this.no = no;
}// consumerc

public void run() {


int value = 0;
for (int i = 0; i < 10; i++) {
value = sh.get();
System.out.println("Consumer #" + this.no + " got: " + value);
} // for
}// run
}// Consumer

class Producer extends Thread {


shop sh;
int no;

public Producer(shop s, int no) {


sh = s;
this.no = no;
}// producerc

public void run() {


for (int i = 0; i < 10; i++) {
sh.put(i);
System.out.println("Producer #" + this.no + " put: " + i);
try {
sleep((int) (Math.random() * 1000));
} catch (Exception e) {
e.getStackTrace();
} // catch
} // for
}// run
}// Producer

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;

class Mythread extends Thread {


String str;
String filename;

Mythread(String str, String filename) {


this.str = str;
this.filename = filename;
}

public void run() {


try {
int flag = 0;
File f = new File(filename);
BufferedReader br = new BufferedReader(new FileReader(f));
String line = "";
while ((line = br.readLine()) != null) {
if (line.contains(str) == true) {
flag = 1;
break;
}
}
if (flag == 1) {
System.out.println("String found in folder/file :" + filename);
} else {
System.out.println("String not found in folder/file :" + filename);

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

//Your folder name


String dirname = "thread";
File d = new File(dirname);
if (d.isDirectory()) {
String s[] = d.list();
for (int i = 0; i < s.length; i++) {
File f = new File(dirname + "/" + s[i]);
if (f.isFile() && s[i].endsWith(".txt")) {
Mythread t = new Mythread(str, dirname + "/" + s[i]);
t.start();
}
}
}
sc.close();
}
}

\\ 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.*;

public class C1 extends JFrame implements ActionListener {


JPanel panel = new JPanel();

JLabel title_lbl = new JLabel("Traffic Light");


JRadioButton rb1 = new JRadioButton("Red");
JRadioButton rb2 = new JRadioButton("Yellow");
JRadioButton rb3 = new JRadioButton("Green");

JButton ok_btn = new JButton("OK");

ButtonGroup g1 = new ButtonGroup();

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

red = new JLabel("STOP");


red.setForeground(Color.red);
yellow = new JLabel("READY");
yellow.setForeground(Color.yellow);
green = new JLabel("GO");
green.setForeground(Color.green);

panel.setPreferredSize(new Dimension(500, 400));


panel.setLayout(null);
panel.setBackground(Color.lightGray);

title_lbl.setBounds(200, 0, 200, 100);


panel.add(title_lbl);

rb1.setBounds(100, 210, 100, 20);


panel.add(rb1);
rb2.setBounds(200, 210, 100, 20);
panel.add(rb2);
rb3.setBounds(300, 210, 100, 20);
panel.add(rb3);

ok_btn.setBounds(200, 310, 100, 50);


panel.add(ok_btn);
ok_btn.addActionListener(this);

red.setBounds(220, 110, 100, 50);


yellow.setBounds(220, 110, 100, 50);
green.setBounds(220, 110, 100, 50);

rb1.setForeground(Color.red);
rb2.setForeground(Color.yellow);
rb3.setForeground(Color.green);

rb1.setBackground(Color.lightGray);
rb2.setBackground(Color.lightGray);
rb3.setBackground(Color.lightGray);

red.setFont(new Font("Arial", Font.BOLD, 20));


yellow.setFont(new Font("Arial", Font.BOLD, 20));
green.setFont(new Font("Arial", Font.BOLD, 20));
title_lbl.setFont(new Font("Arial", Font.BOLD, 20));

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

public void actionPerformed(ActionEvent ae) {


if (ae.getSource() == ok_btn) {
if (rb1.isSelected()) {
yellow.setVisible(false);
green.setVisible(false);
red.setVisible(true);
} else if (rb2.isSelected()) {
red.setVisible(false);
green.setVisible(false);
yellow.setVisible(true);
}
if (rb3.isSelected()) {
red.setVisible(false);
yellow.setVisible(false);
green.setVisible(true);
}
}
}

public static void main(String args[]) {


new C1();

}
}

\\ 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;

public class StudentprojectDisplay extends JFrame implements ActionListener


{
Connection con;
ResultSet rs;
Statement st;
static JTable table;
String[] columnNames={"p_id","p_name","p_description","p_status"};
JFrame frm;
JPanel p1;
String p_id = "",p_name = "",p_description = "",p_status = "";

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

Label l1 = new Label("P-ID");


p1.add(l1);
txtid = new JTextField(20);
p1.add(txtid);

Label l2 = new Label("P-NAME");


p1.add(l2);
txtname = new JTextField(20);
p1.add(txtname);

Label l3 = new Label("P-DESCRIPTION");


p1.add(l3);
txtdesc = new JTextField(20);
p1.add(txtdesc);

Label l4 = new Label("P-STATUS");


p1.add(l4);
textstatus = new JTextField(20);
p1.add(textstatus);

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

// This all coloumn names are taken from project table.


model.addRow(new Object[]{p_id,p_name,p_description,p_status});

}//while
frm.add(scroll);

frm.setVisible(true);
frm.setSize(400,400);
}//try

catch(Exception e){
JOptionPane.showMessageDialog(null,e,"Error",JOptionPane.ERROR_MESSAGE);
}
}//if
}

public static void main(String args[])


{
new StudentprojectDisplay();
}//main
}//class

\\ Write a program to display information about the database and list all the tables in the
database. (Use DatabaseMetaData).

import java.sql.;

public class Metadata {


public static void main(String[] args) {
try {
// load a driver
Class.forName("org.postgresql.Driver");

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

String table[] = { "TABLE" };


ResultSet rs = dbmd.getTables(null, null, null, table);
System.out.println("\t\tTable Names:");

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

\\ Write a program to display information about all columns in the DONAR t


table using ResultSetMetaData

import java.sql.*;

public class DONOR {


public static void main(String[] args) {
try {
// load a driver
Class.forName("org.postgresql.Driver");

// Establish Connection
Connection conn = DriverManager.getConnection("jdbc:postgresql://localhost/postgres", "postgres", "dsk");

Statement stmt = null;


stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select * from donor");

ResultSetMetaData rsmd = rs.getMetaData();


System.out.println("\t-------------------------------------------------");

int count = rsmd.getColumnCount();


System.out.println("\t No. of Columns: " + rsmd.getColumnCount());
System.out.println("\t-------------------------------------------------");
for (int i = 1; i <= count; i++)
{
System.out.println("\t\tColumn No : " + i);
System.out.println("\t\tColumn Name : " + rsmd.getColumnName(i));
System.out.println("\t\tColumn Type : " + rsmd.getColumnTypeName(i));
System.out.println("\t\tColumn Display Size : " + rsmd.getColumnDisplaySize(i));
System.out.println();
} // for
System.out.println("\t--------------------------------------------------");

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.*;

public class mobile {


public static void main(String[] args) {
Connection conn = null;
PreparedStatement pstmt = null;
Statement stmt = null;
ResultSet rs = null;
try {
// load a driver
Class.forName("org.postgresql.Driver");

// Establish Connection
conn = DriverManager.getConnection("jdbc:postgresql://localhost/postgres", "postgres", "dsk");

Scanner sc = new Scanner(System.in);


System.out.println("\n\tMobile Information\n");
do {
System.out.println("\n\t1.Insert \n\t2.Modify\n\t3.Delete\n\t4.Search \n\t5.View All\n\t6.Exit\n");
System.out.println("Enter Your Choice: ");
int ch = sc.nextInt();
switch (ch) {
case 1:
pstmt = conn.prepareStatement("insert into mobile values(?,?,?,?,?,?,?,?)");

System.out.println("Enter Model_Number: ");


int mno = sc.nextInt();
pstmt.setInt(1, mno);

sc.nextLine();
System.out.println("Enter Model_Name: ");
String name = sc.nextLine();
pstmt.setString(2, name);

System.out.println("Enter Model_Color: ");


String color = sc.nextLine();
pstmt.setString(3, color);

System.out.println("Enter Sim_Type: ");


String sim = sc.nextLine();
pstmt.setString(4, sim);

System.out.println("Enter Battery Capacity: ");


int Battery = sc.nextInt();
pstmt.setInt(5, Battery);

System.out.println("Enter Internal Storage In GB: ");


int internal = sc.nextInt();
pstmt.setInt(6, internal);

System.out.println("Enter RAM In GB: ");


int ram = sc.nextInt();
pstmt.setInt(7, ram);

sc.nextLine();
System.out.println("Enter Processor_Type: ");
String pr = sc.nextLine();
pstmt.setString(8, pr);

int result = pstmt.executeUpdate();


System.out.println(result + " Record Inserted\n");
break;

case 2:
String SQL = "update mobile set name=? where mno=?";
pstmt = conn.prepareStatement(SQL);

System.out.println("Enter Model No for Update Record: ");


int no = sc.nextInt();
pstmt.setInt(2, no);

sc.nextLine();
System.out.println("Enter Updated Model name: ");
String mname = sc.nextLine();
pstmt.setString(1, mname);

int result2 = pstmt.executeUpdate();


System.out.println(result2 + " Record Updated\n");
break;

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

int result3 = pstmt.executeUpdate();


System.out.println(result3 + " Record Deleted\n");
break;

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

select * from mobile;

\\ - 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.*;

class InvalidBirthDateException extends Exception {

String msg = "Invalid Date Exception\n";

public String toString() {


return msg;
}

public class Cowin extends JFrame implements ActionListener {


JTextField adhar, byear, phone, hosp;
JPanel p1, p2, p3, p4;
JButton add, update, delete, view, search;
JRadioButton r1, r2, r3, r4, r5, r6, r7, r8;
ButtonGroup bg,bg1,bg2;
JComboBox hos;
String s[] = { "Tambe Hospital", "Daima Hospital", "Nighute Hospital" };

Cowin() {
setTitle("Cowin Registration");
setSize(800, 600);

setLayout(new GridLayout(8, 2, 40, 40));


setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JLabel adharno = new JLabel("Adhar Card Number: ");


add(adharno);
adhar = new JTextField(10);
add(adhar);

JLabel Byear = new JLabel("Birth Year: ");


add(Byear);
byear = new JTextField(10);
add(byear);

JLabel phoneNo = new JLabel("Mobile Number: ");


add(phoneNo);
phone = new JTextField(10);
add(phone);

// Age Radio Button


p1 = new JPanel();
p1.setLayout(new FlowLayout());

JLabel Age = new JLabel("Age Group : ");


add(Age);

r1 = new JRadioButton("18 & above");


p1.add(r1);
// to get the value of radio button
r1.setActionCommand("18 & above");

r2 = new JRadioButton("45 & above");


r2.setActionCommand("45 & above");
p1.add(r2);
add(p1);

JLabel hospital = new JLabel("Select Hospital: ");


add(hospital);

hos = new JComboBox(s);


add(hos);

// Vaccines Radio Button


p2 = new JPanel();
p2.setLayout(new FlowLayout());

JLabel Vaccines = new JLabel("Vaccines : : ");


add(Vaccines);

r3 = new JRadioButton("Covishield");
p2.add(r3);
r3.setActionCommand("Covishield");

r4 = new JRadioButton("Covaxin");
p2.add(r4);
r4.setActionCommand("Covaxin");

r5 = new JRadioButton("Sputnik V");


p2.add(r5);
r5.setActionCommand("SputnikV");
add(p2);

// TimeSlot Radio Button


p3 = new JPanel();
p3.setLayout(new FlowLayout());

JLabel Time = new JLabel("Time Slot :: ");


add(Time);
r6 = new JRadioButton("Morning");
p3.add(r6);
r6.setActionCommand("Morning");

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 = new JButton("Add");


p4.add(add);
update = new JButton("Update");
p4.add(update);
delete = new JButton("Delete");
p4.add(delete);
view = new JButton("View");
p4.add(view);
search = new JButton("Search");
p4.add(search);
add(p4);

add.addActionListener(this);

bg = new ButtonGroup();
bg.add(r1);
bg.add(r2);

bg1 = new ButtonGroup();


bg1.add(r4);
bg1.add(r3);
bg1.add(r5);

bg2 = new ButtonGroup();


bg2.add(r6);
bg2.add(r7);
bg2.add(r8);

setVisible(true);
}

public void actionPerformed(ActionEvent ae) {


if (ae.getSource() == add) {

String adharno = (adhar.getText());


int year = Integer.parseInt(byear.getText());
String phNo = (phone.getText());
String hospital = (String) (hos.getSelectedItem());
String age=bg.getSelection().getActionCommand();
String vaccine=bg1.getSelection().getActionCommand();
String timestamp=bg2.getSelection().getActionCommand();

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

int result = pstmt.executeUpdate();


if (result == 1) {

JOptionPane.showMessageDialog(null, "Succesfully Inserted", hospital,


JOptionPane.INFORMATION_MESSAGE);
}

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

public static void main(String[] args) {


new Cowin();
}// MAIN

}// 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.*;

public class Student_Course extends JFrame implements ActionListener {

JButton addstd, Delete, View, Search, addcourse, course;


JPanel p1, p2;
Connection con;
ResultSet rs;
Statement st;
PreparedStatement pstmt = null;

AddStudent stdobj;
Addcourse cobj;

static JTable table;


String s_id = "", s_name = "", s_class = "";

String st_name = "";

String[] columnNames = { "s_id ", "s_name ", "s_class " };


String[] SC_columns = { "st_name "};
JFrame frm,frmdisp;

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

JLabel std = new JLabel("Student : ");


add(std);

addstd = new JButton("Add");


p1.add(addstd);

Delete = new JButton("Delete");


p1.add(Delete);

View = new JButton("View All");


p1.add(View);

Search = new JButton("Search");


p1.add(Search);

add(p1);
p2 = new JPanel();
p2.setLayout(new FlowLayout());

JLabel sub = new JLabel("Course : ");


add(sub);

addcourse = new JButton("Add");


p2.add(addcourse);

course = new JButton("View ");


p2.add(course);

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

public void actionPerformed(ActionEvent ae) {

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

JScrollPane scroll = new JScrollPane(table);

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

pstmt = con.prepareStatement("select * from student1 where s_name=?");


pstmt.setString(1, s1);

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) {

String s1 = JOptionPane.showInputDialog(null, "Enter course Name");

frmdisp = new JFrame("Student course DISPLAY");


setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

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

JScrollPane scroll = new JScrollPane(table);

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

// This all coloumn names are taken from sc table.


model.addRow(new Object[] { st_name});

} // while
frmdisp.add(scroll);

frmdisp.setVisible(true);
frmdisp.setSize(400, 400);

} // try

catch (Exception e) {
JOptionPane.showMessageDialog(null, e, "Error", JOptionPane.ERROR_MESSAGE);
}

public static void main(String[] args) {


new Student_Course();
}
}// class

class AddStudent extends JFrame implements ActionListener {


JTextField txtroll, txtname, txtclass;
JButton btnadd, btnclear;

AddStudent() {
setTitle("Student Information");

setSize(400, 500);
setVisible(true);
setLayout(new GridLayout(4, 2, 40, 40));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JLabel rollno = new JLabel("Enter Roll Number: ");


add(rollno);
txtroll = new JTextField(10);
add(txtroll);
JLabel stdname = new JLabel("Enter Student Name: ");
add(stdname);
txtname = new JTextField(10);
add(txtname);

JLabel classname = new JLabel("Enter Student Class: ");


add(classname);
txtclass = new JTextField(10);
add(txtclass);

btnadd = new JButton("Submit");


add(btnadd);
btnadd.addActionListener(this);

btnclear = new JButton("Clear");


add(btnclear);
btnclear.addActionListener(this);

}// constructor

public void actionPerformed(ActionEvent ae) {


String str = ae.getActionCommand();

int rn = Integer.parseInt(txtroll.getText());
String name = (txtname.getText());
String cname = (txtclass.getText());

Connection conn = null;


PreparedStatement pstmt = null;
try {
// load a driver
Class.forName("org.postgresql.Driver");

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

int result = pstmt.executeUpdate();


System.out.println(result + " Record Inserted");

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

JLabel cno = new JLabel("Enter Course Number: ");


add(cno);
txtcno = new JTextField(10);
add(txtcno);

JLabel cname1 = new JLabel("Enter course Name: ");


add(cname1);
txtcname = new JTextField(10);
add(txtcname);

JLabel ins = new JLabel("Enter course Instructor: ");


add(ins);
txtins = new JTextField(10);
add(txtins);

btnadd = new JButton("Submit");


add(btnadd);
btnadd.addActionListener(this);

btnclear = new JButton("Clear");


add(btnclear);
btnclear.addActionListener(this);

}// constructor

public void actionPerformed(ActionEvent ae) {


String str = ae.getActionCommand();

int cn = Integer.parseInt(txtcno.getText());
String name = (txtcname.getText());
String course = (txtins.getText());

Connection conn = null;


PreparedStatement pstmt = null;
try {
// load a driver
Class.forName("org.postgresql.Driver");

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

int result = pstmt.executeUpdate();


System.out.println(result + " Record Inserted");
txtcno.setText("");
txtcname.setText("");
txtins.setText("");

}
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.*;

public class Employee {


public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
// load a driver
Class.forName("org.postgresql.Driver");

// Establish Connection
conn = DriverManager.getConnection("jdbc:postgresql://localhost/postgres", "postgres", "dsk");

// create statement and execute queries


stmt = conn.createStatement();

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("---------------");

// close resultset,stmt & connection Object


rs.close();
stmt.close();
conn.close();

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

\\ Write a Program to make use of following JSP implicit objects:


i.out: To display current Date and Time.
ii.request: To get header information.
iii.response: To Add Cookie
iv.config: get the parameters value defined in <init-param>
v.application: get the parameter value defined in <context-param>
vi.session: Display Current Session ID
vii.pageContext: To set and get the attributes.
viii.page: get the name of Generated Servlet

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>

\\ Write a JSP program to display the details of PATIENT (PatientNo, PatientName,


PatientAddress, Patientage,PatientDiease) in tabular form on browser

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

<%@ page language="java" contentType="text/html; charset=UTF-8"


pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Online Multiple Choice Test</title>
</head>
<body>
<h1>Online Multiple Choice Test</h1>

<%-- 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'?"
};

// Define an array of choices for each question


String[][] choices = {
{"Paris", "London", "Berlin", "Rome"},
{"Mars", "Venus", "Mercury", "Jupiter"},
{"Harper Lee", "Stephen King", "J.K. Rowling", "F. Scott Fitzgerald"}
};

// 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>
<%
}
%>

<%-- Add a submit button --%>


<button type="submit">Submit Answers</button>
</body>
</html>
\\ Create a Spring core example to display the message "If you can't explain it simply,
you don't understand it well enough"

# 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>

\\ Design simple student information like Student_id, Student_Name and


Student_Age using Spring Framework.

# 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

public class Main {


public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
hellobean hello = (hellobean) context.getBean("helloWorld");
hello.printStudents();
}
}

# Student.java
package springcore_example;
public class Student {
private int id;
private String name;
private int age;
public int getId() {
return id;
}

public void setId(int id) {


this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
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="student1" class="springcore_example.Student">
<property name="id" value="1"/>
<property name="name" value="Shahrukh"/>
<property name="age" value="20"/>
</bean>
<bean id="student2" class="springcore_example.Student">
<property name="id" value="2"/>
<property name="name" value="Shubham"/>
<property name="age" value="22"/>
</bean>
<bean id="student3" class="springcore_example.Student">
<property name="id" value="3"/>
<property name="name" value="Rahul"/>
<property name="age" value="23"/>
</bean>
<bean id="helloWorld" class="springcore_example.hellobean">
<property name="students">
<list>
<ref bean="student1"/>
<ref bean="student2"/>
<ref bean="student3"/>
</list>
</property>
</bean>
</beans>
Output :Student ID is: 1 Shahrukh is 20 years old.
Student ID is: 2 Shubham is 20 years old.
Student ID is: 3 Rahul is 20 years old.

\\ Write a program to display the Current Date using spring

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 {

public static void main(String[] args) {


SpringApplication.run(CurrentDateApplication.class, args);
}
}

@RestController
class CurrentDateController {

@GetMapping("/current-date")
public String getCurrentDate() {
LocalDate currentDate = LocalDate.now();
return "Current Date: " + currentDate.toString();
}
}

\\ Design the Employee login form


application using spring form MVC validation

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 @Min(18) @Max(100)


private Integer age;

@NotNull
private Gender gender;

@DateTimeFormat(pattern="MM/dd/yyyy")
@NotNull @Past
private Date birthday;

@Phone
private String phone;

public enum Gender {


MALE, FEMALE
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public String getEmail() {


return email;
}

public void setEmail(String email) {


this.email = email;
}

public Integer getAge() {


return age;
}

public void setAge(Integer age) {


this.age = age;
}

public Gender getGender() {


return gender;
}

public void setGender(Gender gender) {


this.gender = gender;
}

public Date getBirthday() {


return birthday;
}

public void setBirthday(Date birthday) {


this.birthday = birthday;
}

public String getPhone() {


return phone;
}

public void setPhone(String phone) {


this.phone = phone;
}

}
package com.journaldev.spring.form.model;

public class Employee {

private int id;


private String name;
private String role;

public int getId() {


return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}

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

Class<?>[] groups() default {};

Class<? extends Payload>[] payload() default {};

}
package com.journaldev.spring.form.validator;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class PhoneValidator implements ConstraintValidator<Phone, String> {

@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;

public class EmployeeFormValidator implements Validator {

//which objects can be validated by this validator


@Override
public boolean supports(Class<?> paramClass) {
return Employee.class.equals(paramClass);
}

@Override
public void validate(Object obj, Errors errors) {
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "id", "id.required");

Employee emp = (Employee) obj;


if(emp.getId() <=0){
errors.rejectValue("id", "negativeValue", new Object[]{"'id'"}, "id can't be negative");
}

ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "name.required");


ValidationUtils.rejectIfEmptyOrWhitespace(errors, "role", "role.required");
}
}
Controller Classes
package com.journaldev.spring.form.controllers;

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 {

private static final Logger logger = LoggerFactory


.getLogger(CustomerController.class);

private Map<String, Customer> customers = null;

public CustomerController(){
customers = new HashMap<String, Customer>();
}

@RequestMapping(value = "/cust/save", method = RequestMethod.GET)


public String saveCustomerPage(Model model) {
logger.info("Returning custSave.jsp page");
model.addAttribute("customer", new Customer());
return "custSave";
}

@RequestMapping(value = "/cust/save.do", method = RequestMethod.POST)


public String saveCustomerAction(
@Valid Customer customer,
BindingResult bindingResult, Model model) {
if (bindingResult.hasErrors()) {
logger.info("Returning custSave.jsp page");
return "custSave";
}
logger.info("Returning custSaveSuccess.jsp page");
model.addAttribute("customer", customer);
customers.put(customer.getEmail(), customer);
return "custSaveSuccess";
}

}
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 {

private static final Logger logger = LoggerFactory


.getLogger(EmployeeController.class);

private Map<Integer, Employee> emps = null;

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

@RequestMapping(value = "/emp/save", method = RequestMethod.GET)


public String saveEmployeePage(Model model) {
logger.info("Returning empSave.jsp page");
return "empSave";
}

@RequestMapping(value = "/emp/save.do", method = RequestMethod.POST)


public String saveEmployeeAction(
@ModelAttribute("employee") @Validated Employee employee,
BindingResult bindingResult, Model model) {
if (bindingResult.hasErrors()) {
logger.info("Returning empSave.jsp page");
return "empSave";
}
logger.info("Returning empSaveSuccess.jsp page");
model.addAttribute("emp", employee);
emps.put(employee.getId(), employee);
return "empSaveSuccess";
}
}
Form Validation Error Messages Resource Bundle
#application defined error messsages
id.required=Employee ID is required
name.required=Employee Name is required
role.required=Employee Role is required
negativeValue={0} can't be negative or zero

#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

#application messages for annotations, {ValidationClass}.{modelObjectName}.{field}


#the {0} is field name, other fields are in alphabatical order, max and then min
Size.customer.name=Customer {0} should be between {2} and {1} characters long
NotEmpty.customer.email=Email is a required field
NotNull.customer.age=Customer {0} should be in years

#Generic annotation class messages


Email=Email address is not valid
NotNull=This is a required field
NotEmpty=This is a required field
Past=Date should be Past

#Custom validation annotation


Phone=Invalid format, valid formats are 1234567890, 123-456-7890 x1234
<%@ 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>Customer Save Page</title>
<style>
.error {
color: #ff0000;
font-style: italic;
font-weight: bold;
}
</style>
</head>
<body>

<springForm:form method="POST" commandName="customer"


action="save.do">
<table>
<tr>
<td>Name:</td>
<td><springForm:input path="name" /></td>
<td><springForm:errors path="name" cssClass="error" /></td>
</tr>
<tr>
<td>Email:</td>
<td><springForm:input path="email" /></td>
<td><springForm:errors path="email" cssClass="error" /></td>
</tr>
<tr>
<td>Age:</td>
<td><springForm:input path="age" /></td>
<td><springForm:errors path="age" cssClass="error" /></td>
</tr>
<tr>
<td>Gender:</td>
<td><springForm:select path="gender">
<springForm:option value="" label="Select Gender" />
<springForm:option value="MALE" label="Male" />
<springForm:option value="FEMALE" label="Female" />
</springForm:select></td>
<td><springForm:errors path="gender" cssClass="error" /></td>
</tr>
<tr>
<td>Birthday:</td>
<td><springForm:input path="birthday" placeholder="MM/dd/yyyy"/></td>
<td><springForm:errors path="birthday" cssClass="error" /></td>
</tr>
<tr>
<td>Phone:</td>
<td><springForm:input path="phone" /></td>
<td><springForm:errors path="phone" cssClass="error" /></td>
</tr>
<tr>
<td colspan="3"><input type="submit" value="Save Customer"></td>
</tr>
</table>

</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" %>

<%@ page session="false" %>


<html>
<head>
<title>Customer Saved Successfully</title>
</head>
<body>
<h3>
Customer Saved Successfully.
</h3>

<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 method="POST" commandName="employee"


action="save.do">
<table>
<tr>
<td>Employee ID:</td>
<td><springForm:input path="id" /></td>
<td><springForm:errors path="id" cssClass="error" /></td>
</tr>
<tr>
<td>Employee Name:</td>
<td><springForm:input path="name" /></td>
<td><springForm:errors path="name" cssClass="error" /></td>
</tr>
<tr>
<td>Employee Role:</td>
<td><springForm:select path="role">
<springForm:option value="" label="Select Role" />
<springForm:option value="ceo" label="CEO" />
<springForm:option value="developer" label="Developer" />
<springForm:option value="manager" label="Manager" />
</springForm:select></td>
<td><springForm:errors path="role" cssClass="error" /></td>
</tr>
<tr>
<td colspan="3"><input type="submit" value="Save"></td>
</tr>
</table>

</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>

\\ Write a program to calculate the sum and the average of an


array of 1000 integers (generate randomly) using 10 threads.
Each thread calculates the sum of 100 integers. Use these values to calculate average. [use join method]

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

}
}

\\ Write a Java program that implements a multi-thread application that has


three threads. First thread generates a random integer for every 1 second;
second thread computes the square of the number and prints; third thread will
print the value of cube of the number.

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.*;

class boucingthread extends JFrame implements Runnable


{
Thread t;
int x,y;

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)
{

}
}

public void paint(Graphics g)


{

g.drawOval(x,y,7,7);

public static void main(String a[])throws Exception


{
boucingthread t=new boucingthread();
Thread.sleep(1000);
}
}

\\ 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".

public class MessagePassing {

// Shared message between sender and receiver


private static String message;

public static void main(String[] args) {


// Create sender and receiver threads
Sender sender = new Sender();
Receiver receiver = new Receiver();

// Start sender and receiver threads


sender.start();
receiver.start();
}

// Sender thread class


static class Sender extends Thread {
@Override
public void run() {
// Loop until "Good Bye Corona" is set as message
while (!message.equals("Good Bye Corona")) {
synchronized (MessagePassing.class) {
// Accept message input from console
Scanner scanner = new Scanner(System.in);
System.out.print("Enter message: ");
message = scanner.nextLine();
MessagePassing.class.notify(); // Notify receiver thread
}
}
}
}

// Receiver thread class


static class Receiver extends Thread {
@Override
public void run() {
// Loop until "Good Bye Corona" is received as message
while (!message.equals("Good Bye Corona")) {
synchronized (MessagePassing.class) {
try {
MessagePassing.class.wait(); // Wait for notification from sender thread
} catch (InterruptedException e) {
e.printStackTrace();
}
// Display received message on console
System.out.println("Received message: " + message);
}
}
System.out.println("Receiver exiting...");
}
}
}

You might also like