java programs
DESCRIPTION
Java ProgrammingTRANSCRIPT
-
JAVA PROGRAMS T.Y.B.Sc(CS) 1. Write a Java program to create a class FileWatcher that can be given several filenames
that may or may not exist. The class should start a thread for each filename. Each
thread will periodically check for the existence of its file. If the file exists, then thread
will display the details of the file (viz. filename, permissions and size) on the console and
then end. If file does not exist then display appropriate error message. import java.io.*;
class FileWatcher extends Thread
{
String fileName;
FileWatcher(String fileName)
{
this.fileName = fileName;
}
public void run()
{
File f = new File(fileName);
while(true)
{
try
{
if(f.exists())
{
System.out.println("File "+fileName+
" found.");
System.out.println("Name:"+f.getName()+
"\nRead:"+f.canRead()+
"\nWrite:"+f.canWrite()+
"\nsize:"+f.length());
break;
}
else
{
System.out.println("File "+fileName+
" not found.");
}
Thread.sleep(200);
}
catch(Exception e){}
}
}
}
class FileWatcherDemo
-
{
public static void main(String args[])
{
int n = args.length;
for(int i=0;i
-
System.out.println("From Server:"+br.readLine());
}
}
3. Write a menu driven JDBC program to display the first record, last record, middle
record, nth record of a student,(Student table should contain student id, name and class)
(Note: Examiners can replace Student table with Item, Book, Supplier, Customer,
Doctor, Patient or any other and provide the design of the table) import java.io.*;
import java.sql.*;
class StudentDB
{
static BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));
static void dispRecord(ResultSet rs) throws Exception
{
System.out.println("ID:"+rs.getInt(1)+
"\nName:"+rs.getString(2)+
"\nClass:"+rs.getString(3));
}
public static void main(String args[])
{
String driver="com.mysql.jdbc.Driver";
String url="jdbc:mysql://localhost:3306/tybcs1";
String user="root";
String pass="";
String sql="SELECT * FROM student";
Connection con = null;
Statement s = null;
ResultSet rs = null;
try
{
Class.forName(driver);
con = DriverManager.getConnection(url,user,pass);
s = con.createStatement(
ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY);
rs = s.executeQuery(sql);
while(true)
{
System.out.print("1.First record"+
"\n2.Last record"+
"\n3.Middle record"+
"\n4.nth record"+
"\n5.Exit"+
"\nEnter ur choice (1-5):");
-
int ch=Integer.parseInt(br.readLine());
switch(ch)
{
case 1:
rs.first();
dispRecord(rs);
break;
case 2:
rs.last();
dispRecord(rs);
break;
case 3:
rs.last();
int mid=rs.getRow();
rs.absolute(mid/2);
dispRecord(rs);
break;
case 4:
System.out.print("Enter record no:");
int n = Integer.parseInt(br.readLine());
rs.last();
if(n>0 && n
-
class MyThread extends Thread
{
JTextField tf;
MyThread(JTextField tf)
{
this.tf = tf;
}
public void run()
{
while(true)
{
Date d = new Date();
int h = d.getHours();
int m = d.getMinutes();
int s = d.getSeconds();
tf.setText(h+":"+m+":"+s);
try
{
Thread.sleep(300);
}catch(Exception e){}
}
}
}
class StopWatch extends JFrame
{
JTextField txtTime;
JButton btnStart,btnStop;
MyThread t;
StopWatch()
{
txtTime = new JTextField(20);
btnStart = new JButton("Start");
btnStop = new JButton("Stop");
setTitle("Stop Watch");
setLayout(new FlowLayout());
setSize(300,100);
add(txtTime);
add(btnStart);
add(btnStop);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ButtonHandler bh = new ButtonHandler();
btnStart.addActionListener(bh);
btnStop.addActionListener(bh);
-
t = new MyThread(txtTime);
}
class ButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==btnStart)
{
if(!t.isAlive()) t.start();
else t.resume();
}
if(ae.getSource()==btnStop)
{
t.suspend();
}
}
}
public static void main(String args[])
{
new StopWatch();
}
}
5. Write a servlet which counts how many times a user has visited a web page. If the user
is visiting the page for the first time, display a welcome message. If the user is revisiting
the page, display the number of times visited. (Use cookies) import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HitCount extends HttpServlet
{
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException,IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Cookie c[]=request.getCookies();
if(c==null)
{
Cookie cookie = new Cookie("count","1");
response.addCookie(cookie);
out.println("Welcome Servlet"+
"Hit Count:1");
}
else
{
-
int val=Integer.parseInt(c[0].getValue())+1;
c[0].setValue(Integer.toString(val));
response.addCookie(c[0]);
out.println("Hit Count:"+val+"");
}
}
}
6. Create a JSP page to accept a number from the user and display it in words.
eg. 125 One Two Five
The output should be in blue color.
// number.html
Enter Number:
// words.jsp
-
// user.jsp
-
ResultSet rs = null;
int ch=0;
try
{
Class.forName(driver);
con = DriverManager.getConnection(url,user,pass);
ps = con.prepareStatement(insertSQL);
do
{
System.out.print("Enter roll no:");
int rno=Integer.parseInt(br.readLine());
System.out.print("Enter name:");
String name=br.readLine();
System.out.print("Enter marks 1:");
float m1=Float.parseFloat(br.readLine());
System.out.print("Enter marks 2:");
float m2=Float.parseFloat(br.readLine());
System.out.print("Enter marks 3:");
float m3=Float.parseFloat(br.readLine());
ps.setInt(1,rno);
ps.setString(2,name);
ps.setFloat(3,m1);
ps.setFloat(4,m2);
ps.setFloat(5,m3);
ps.executeUpdate();
System.out.print("Add More[Yes(1)/No(0)]?");
ch=Integer.parseInt(br.readLine());
}while(ch==1);
ps.close();
ps=con.prepareStatement(sql);
rs=ps.executeQuery();
System.out.println("RollNo\tName\tMarks1\tMarks2\t"+
"Marks3\tTotal\tPercentage");
while(rs.next())
{
float m1=rs.getFloat(3);
float m2=rs.getFloat(4);
float m3=rs.getFloat(5);
float tot=m1+m2+m3;
float per=tot/3;
System.out.println(rs.getInt(1)+"\t"+
rs.getString(2)+"\t"+
rs.getFloat(3)+"\t"+
rs.getFloat(4)+"\t"+
rs.getFloat(5)+"\t"+
tot+"\t"+per);
}
rs.close();
ps.close();
con.close();
-
}
catch(Exception e)
{
System.out.println(e);
}
}
}
9. Create two singly linked lists for string data and perform following operations
a) Add element in list1 b) Add element in list2 c) Union
d) Display the reverse of the linked list after the union of lists e) Intersection
f) exit import java.util.*; import java.io.*;
class LinkedListDemo
{
public static void main(String args[])
throws Exception
{
LinkedList ll1 = new LinkedList();
LinkedList ll2 = new LinkedList();
LinkedList ll3 = new LinkedList();
LinkedList ll4 = new LinkedList();
BufferedReader br = new BufferedReader(
new InputStreamReader(
System.in));
String s=null;
while(true)
{
System.out.println("1.Add element in list 1"+
"\n2.Add element in list 2"+
"\n3.Union"+
"\n4.Display reverse of union"+
"\n5.Intersection"+
"\n6.Exit"+
"\nEnter ur choice (1-6):");
int ch=Integer.parseInt(br.readLine());
switch(ch)
{
case 1:
System.out.print("Enter element:");
s = br.readLine();
if(!ll1.contains(s)) ll1.add(s);
break;
case 2:
System.out.print("Enter element:");
-
s = br.readLine();
if(!ll2.contains(s)) ll2.add(s);
break;
case 3:
ll3.addAll(ll1);
for(String t:ll2)
{
if(!ll3.contains(t)) ll3.add(t);
}
System.out.println("List 1:"+ll1+
"\nList 2:"+ll2+
"\nList 3:"+ll3);
break;
case 4:
int n = ll3.size();
ListIterator iter =
ll3.listIterator(n);
System.out.println("Elements in reverse:");
int i=1;
while(iter.hasPrevious())
{
String e = iter.previous();
System.out.println(i+":"+e);
}
break;
case 5:
for(String t:ll1)
{
if(ll2.contains(t)) ll4.add(t);
}
System.out.println("List 1:"+ll1+
"\nList 2:"+ll2+
"\nList 3:"+ll4);
break;
case 6:
System.exit(0);
}
}
}
}
10. Create a linked list containing the names of the days in a week. Display the menu that
has following options.
a) Display the contents of the list using Iterator. b) Display the contents of the list in reverse order using ListIterator
c) Accept a day and display its index in the collection d) Exit
import java.util.*;
import java.io.*;
class WeekDaysList
-
{
public static void main(String args[])
throws Exception
{
LinkedList days = new LinkedList();
days.add("Sunday");
days.add("Monday");
days.add("Tuesday");
days.add("Wednesday");
days.add("Thursday");
days.add("Firday");
days.add("Saturday");
BufferedReader br = new BufferedReader(
new InputStreamReader(
System.in));
while(true)
{
System.out.print("1.Display list"+
"\n2.Display list in reverse"+
"\n3.Display index of day"+
"\n4.Exit"+
"\nEnter ur choice (1-4):");
int ch=Integer.parseInt(br.readLine());
switch(ch)
{
case 1:
Iterator itr = days.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
break;
case 2:
int n = days.size();
ListIterator ritr = days.listIterator(n);
while(ritr.hasPrevious())
{
System.out.println(ritr.previous());
}
break;
case 3:
System.out.print("Enter day:");
String day = br.readLine();
int i = days.indexOf(day);
if(i==-1)
System.out.println("Invalid day");
else
System.out.println(day+" found at "+i);
break;
case 4:
-
System.exit(0);
}
}
}
}
11. Design a HTML page containing 4 option buttons(MBA,MSC,MCA,MCM) and two
buttons Reset and Submit. When the user clicks Submit the server responds by adding
a cookie containing the selected course and sends a message back to the client. // course.html
Select Course
MBA
MSc
MCA
MCM
View Cookies
// AddCookie.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");
Cookie newCookie = new Cookie("course:"+id,value);
res.addCookie(newCookie);
pw.println("Cookie added with value "+value+"");
}
}
// ViewCookies.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
-
public class ViewCookies extends HttpServlet
{
public void doGet(HttpServletRequest req,
HttpServletResponse res)
throws ServletException,IOException
{
res.setContentType("text/html");
PrintWriter pw = res.getWriter();
Cookie []c = req.getCookies();
pw.println(""+
"NameValue");
for(int i=0;i
-
{
if(x
-
}
public void run()
{
while(true)
{
ta.append(count+"\n");
try
{
Thread.sleep(100);
}catch(Exception e){}
count+=2;
if(count>100)count=0;
}
}
}
class OddThread extends Thread
{
JTextArea ta;
int count;
OddThread(JTextArea ta)
{
this.ta=ta;
count=1;
}
public void run()
{
while(true)
{
ta.append(count+"\n");
try
{
Thread.sleep(100);
}catch(Exception e){}
count+=2;
if(count>100)count=1;
}
}
}
class EvenOdd extends JFrame
{
JTextArea taEven,taOdd;
JButton btnOdd,btnEven,btnEvenStop,btnOddStop;
JPanel panCenter,panSouth;
EvenThread et;
OddThread ot;
-
EvenOdd()
{
taEven = new JTextArea();
taOdd = new JTextArea();
btnOdd = new JButton("Odd");
btnEven = new JButton("Even");
btnOddStop = new JButton("Stop");
btnEvenStop = new JButton("Stop");
panCenter = new JPanel();
panCenter.setLayout(new GridLayout(1,2));
panCenter.add(new JScrollPane(taEven));
panCenter.add(new JScrollPane(taOdd));
panSouth = new JPanel();
panSouth.setLayout(new GridLayout(1,4));
panSouth.add(btnEven);
panSouth.add(btnEvenStop);
panSouth.add(btnOdd);
panSouth.add(btnOddStop);
setTitle("Even & Odd");
setSize(300,200);
add(panCenter,"Center");
add(panSouth,"South");
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ButtonHandler bh = new ButtonHandler();
btnOdd.addActionListener(bh);
btnEven.addActionListener(bh);
btnOddStop.addActionListener(bh);
btnEvenStop.addActionListener(bh);
et = new EvenThread(taEven);
ot = new OddThread(taOdd);
}
class ButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==btnEven)
{
if(et.isAlive()) et.resume();
else et.start();
}
if(ae.getSource()==btnOdd)
{
if(ot.isAlive()) ot.resume();
-
else ot.start();
}
if(ae.getSource()==btnEvenStop) et.suspend();
if(ae.getSource()==btnOddStop) ot.suspend();
}
}
public static void main(String args[])
{
new EvenOdd();
}
}
14. Write a Java program to create a Hash table to store book id and book name. Book id and name should be accepted from the console. Write a menu driven program to add,
search, delete and display the contents of the hash table. Display the contents of the
hash table in tabular format. Display all the options till Exit is selected. (Do not use
Swing). import java.io.*;
import java.util.*;
class BookHash
{
public static void main(String args[])
throws Exception
{
BufferedReader br = new BufferedReader(
new InputStreamReader(
System.in));
Hashtable ht=new Hashtable();
int bid=0;
String bname=null;
while(true)
{
System.out.print("1.Add"+
"\n2.Search"+
"\n3.Delete"+
"\n4.Display"+
"\n5.Exit"+
"\nEnter ur choice (1-5):");
int ch=Integer.parseInt(br.readLine());
switch(ch)
{
case 1:
System.out.print("Enter book id:");
bid = Integer.parseInt(br.readLine());
System.out.print("Enter book name:");
bname = br.readLine();
-
ht.put(bid,bname);
break;
case 2:
System.out.print("Enter book id:");
bid = Integer.parseInt(br.readLine());
bname = ht.get(bid);
if(bname==null)
System.out.println("Book not found.");
else
System.out.println("Book Name:"+bname);
break;
case 3:
System.out.print("Enter book id:");
bid = Integer.parseInt(br.readLine());
bname = ht.remove(bid);
if(bname==null)
System.out.println("Book not found.");
else
System.out.println("Book removed.");
break;
case 4:
Enumeration e = ht.keys();
System.out.println("ID\tName");
while(e.hasMoreElements())
{
bid = (Integer)e.nextElement();
bname = ht.get(bid);
System.out.println(bid+"\t"+bname);
}
break;
case 5:
System.exit(0);
}
}
}
}
15. Write a Java program to accept n student names from console and display the sorted list in descending order (Use Comparator).
(Note: The examiners can change the data that is to be stored in the List i.e. instead of
student names, accept n book names or item names or city names etc.) import java.util.*;
import java.io.*;
class Student
{
private int rollNo;
private String name;
private float per;
Student(int rollNo, String name, float per)
-
{
this.rollNo=rollNo;
this.name=name;
this.per=per;
}
public String toString()
{
return rollNo+"\t"+name+"\t"+per;
}
public String getName()
{
return name;
}
}
class NameComparator implements Comparator
{
public int compare(Object ob1, Object ob2)
{
String n1 = ((Student)ob1).getName();
String n2 = ((Student)ob2).getName();
return n1.compareTo(n2);
}
}
public class StudentSort
{
public static void main(String args[])
throws Exception
{
BufferedReader br = new BufferedReader(
new InputStreamReader(
System.in));
System.out.print("Enter no.of students:");
int n = Integer.parseInt(br.readLine());
LinkedList studList = new LinkedList();
for(int i=0;i
-
System.out.println("Sorted Names:");
for(Student s:studList)
System.out.println(s);
}
}
16. Write a JDBC Program to accept a table name from console and display the following
details. Number of columns in the table, column names, data type and the number of
records. import java.io.*;
import java.sql.*;
class TableInfo
{
static BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));
public static void main(String args[])
{
String driver="com.mysql.jdbc.Driver";
String url="jdbc:mysql://localhost:3306/tybcs1";
String user="root";
String pass="";
Connection con = null;
Statement s = null;
ResultSet rs = null;
ResultSetMetaData rsmd = null;
try
{
Class.forName(driver);
con = DriverManager.getConnection(url,user,pass);
System.out.print("Enter table name:");
String tname = br.readLine();
String sql = "SELECT * FROM "+tname;
s = con.createStatement(
ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY);
rs = s.executeQuery(sql);
rsmd = rs.getMetaData();
int noCols = rsmd.getColumnCount();
System.out.println("No.of columns:"+noCols);
for(int i=1;i
-
s.close();
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
17. Write a Java program which sends the name of a text file from the client to server and display the contents of that file on the client machine. If the file does not exists then
display proper error message to client. // Server.java
import java.io.*;
import java.net.*;
public class Server
{
public static void main(String args[])
throws Exception
{
ServerSocket ss = new ServerSocket(4444);
BufferedReader fromClient = null;
PrintStream toClient = null;
BufferedReader brFile = null;
File file = null;
while(true)
{
Socket s = ss.accept();
fromClient = new BufferedReader(
new InputStreamReader(
s.getInputStream()));
toClient = new PrintStream(
s.getOutputStream());
String fileName = fromClient.readLine();
file = new File(fileName);
if(file.exists())
{
brFile = new BufferedReader(
new FileReader(fileName));
String line = null;
while((line=brFile.readLine())!=null)
toClient.println(line);
-
}
else
{
toClient.println("File "+fileName+" Not Found.");
}
toClient.println("----");
s.close();
}
}
}
// Client.java
import java.io.*;
import java.net.*;
public class Client
{
public static void main(String args[])
throws Exception
{
Socket s = new Socket("localhost",4444);
BufferedReader fromServer = new BufferedReader(
new InputStreamReader(
s.getInputStream()));
PrintStream toServer = new PrintStream(
s.getOutputStream());
BufferedReader br = new BufferedReader(
new InputStreamReader(
System.in));
System.out.print("Enter file name:");
String fileName = br.readLine();
toServer.println(fileName);
String line = null;
while(true)
{
line = fromServer.readLine();
if(line.equals("----")) break;
System.out.println(line);
}
s.close();
}
}
-
18. Write a server program that echoes messages sent by the client. The process continues
till the client types END. // Client.java
import java.io.*;
import java.net.*;
class Client
{
public static void main(String argv[]) throws Exception
{
String sentence;
String modifiedSentence;
BufferedReader inFromUser = new BufferedReader(
new InputStreamReader(
System.in));
Socket clientSocket = new Socket("localhost", 9005);
DataOutputStream outToServer = new DataOutputStream(
clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(
new InputStreamReader(
clientSocket.getInputStream()));
System.out.println("Enter text (END to stop)");
while(true)
{
sentence = inFromUser.readLine();
if(sentence.equals("END")) break;
outToServer.writeBytes(sentence + '\n');
modifiedSentence = inFromServer.readLine();
System.out.println(modifiedSentence);
}
clientSocket.close();
}
}
// Server.java
import java.io.*;
import java.net.*;
class Server
{
-
public static void main(String argv[]) throws Exception
{
String clientSentence;
String capitalizedSentence;
ServerSocket welcomeSocket = new ServerSocket(9005);
while(true)
{
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient = new BufferedReader(
new InputStreamReader(
connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(
connectionSocket.getOutputStream());
clientSentence = inFromClient.readLine();
capitalizedSentence=clientSentence.toUpperCase()+'\n';
outToClient.writeBytes(capitalizedSentence);
}
}
}
19. Create a class student with attributes rno, name , age and class. Initialize values through parameterize constructor. If age of student is not in between 15 to 21 then
generate user defined exception as InvalidAgeException. Similarly if name contains special symbols or digits then raise exception as InvalidNameException. Handle these
exceptions. class InvalidAgeException extends Exception{}
class InvalidNameException extends Exception{}
class Student
{
int RollNo, Age;
String Name,Course;
Student(int rno, String name, int age, String course)
{
try
{
RollNo = rno;
Name = name;
Age = age;
Course = course;
if(Age21)
throw new InvalidAgeException();
for(int i=0; i
-
throw new InvalidNameException();
}
catch(InvalidAgeException e)
{
System.out.println("Age Not Within The Range");
}
catch(InvalidNameException e)
{
System.out.println("Name not valid");
}
}
public String toString()
{
return "Roll No:"+RollNo+
"\nName :"+Name+
"\nAge :"+Age+
"\nCourse :"+Course;
}
}
class StudentExceptionDemo
{
public static void main(String args[])
{
Student s1 = new Student(1,"Ram",17,"Java Programming");
System.out.println(s1);
Student s2 = new Student(2,"John",28,"C++ Programming");
System.out.println(s2);
Student s3 = new Student(3,"Akbar15",19,"C++ Programming");
System.out.println(s3);
}
}
20. Write a program to accept a string as command line argument and check whether it is a
file or directory. If it is a directory then list the file names and their size in that
directory. Also display a count of the number of files in the directory. Delete all the files
in that directory having the extension .txt ( Confirm from user to delete a file or not). If
it is a file then display various details about that file.
(Note: Examiners can change the file extension from .txt to .dat or .tmp or .swp etc.) import java.io.*;
class FileDemo
{
public static void main(String args[])
throws Exception
{
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));
String name=args[0];
File file = new File(name);
if(file.isFile())
{
-
System.out.println(name+" is a file.");
}
if(file.isDirectory())
{
System.out.println(name+" is a directory.");
String names[]=file.list();
int count=0;
for(int i=0;i
-
System.out.print("Enter name:");
String name=br.readLine();
System.out.print("Enter class:");
String cls=br.readLine();
System.out.print("Enter percentage:");
float per=Float.parseFloat(br.readLine());
dos.writeInt(rno);
dos.writeUTF(name);
dos.writeUTF(cls);
dos.writeFloat(per);
}
dos.close();
System.out.print("Enter roll no:");
int no=Integer.parseInt(br.readLine());
DataInputStream dis = new DataInputStream(
new FileInputStream("stud.dat"));
while(true)
{
int rno=dis.readInt();
String name=dis.readUTF();
String cls=dis.readUTF();
float per=dis.readFloat();
if(rno==no)
{
System.out.println("Roll No:"+rno+
"\nName:"+name+
"\nClass:"+cls+
"\nPercentage:"+per);
break;
}
}
dis.close();
}
catch(Exception e)
{
System.out.println("Roll No Not Found.");
}
}
}
22. Write a Java program to create GUI that displays all the font names available on a
system in a ComboBox. Also display some text message. Apply the font selected from
the combo box to the text message. import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
-
class FontDemo extends JFrame
{
JLabel lblFont;
JComboBox cmbFont;
JTextField txtMsg;
FontDemo()
{
String fontName[] = GraphicsEnvironment.
getLocalGraphicsEnvironment().
getAvailableFontFamilyNames();
lblFont = new JLabel("Font:");
txtMsg = new JTextField("Hello World!",40);
cmbFont = new JComboBox(fontName);
setTitle("Font Demo");
setSize(400,100);
setLayout(new FlowLayout());
add(lblFont);
add(cmbFont);
add(txtMsg);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
cmbFont.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent ie)
{
String fontName=
(String)cmbFont.getSelectedItem();
txtMsg.setFont(
new Font(fontName,Font.BOLD,15));
}
});
}
public static void main(String args[])
{
new FontDemo();
}
}
23. Write a Java program to design a screen using swings that will create four text fields.
First text field for the text, second for what to find and third for replace. Display result
in the fourth text field. Also display the count of total no. of replacements made. On the
click of clear button, clear the contents in all the text boxes.
-
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class FindReplace extends JFrame implements ActionListener
{
JLabel textLabel, findLabel, replaceLabel, occurrenceLabel;
JTextArea text;
JTextField findText, replaceText, occurrenceText;
JButton find, replace, clear;
JPanel pan1,pan2;
int occurrences=0;
public FindReplace()
{
textLabel = new JLabel("Enter Text:",JLabel.RIGHT);
findLabel = new JLabel("Text to Find:",JLabel.RIGHT);
replaceLabel = new JLabel("Text to Replace:",
JLabel.RIGHT);
occurrenceLabel = new JLabel("No.of Occurrences:",
JLabel.RIGHT);
text = new JTextArea(1,20);
findText = new JTextField(20);
replaceText = new JTextField(20);
occurrenceText = new JTextField(20);
pan1 = new JPanel();
pan1.setLayout(new GridLayout(4,2));
pan1.add(textLabel);
pan1.add(text);
pan1.add(findLabel);
pan1.add(findText);
pan1.add(replaceLabel);
pan1.add(replaceText);
pan1.add(occurrenceLabel);
pan1.add(occurrenceText);
-
find = new JButton("Find");
replace = new JButton("Replace");
clear = new JButton("Clear");
find.addActionListener(this);
replace.addActionListener(this);
clear.addActionListener(this);
pan2 = new JPanel();
pan2.setLayout(new FlowLayout());
pan2.add(find);
pan2.add(replace);
pan2.add(clear);
setTitle("Find And Replace");
setSize(300, 200);
add(pan1,"Center");
add(pan2,"South");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args)
{
new FindReplace();
}
public void actionPerformed(ActionEvent ae)
{
JButton btn = (JButton)ae.getSource();
if(btn == find)
{
String s = text.getText();
String f = findText.getText();
int i = s.indexOf(f);
if(i!=-1)
{
occurrences++;
occurrenceText.setText(
Integer.toString(occurrences));
text.select(i,i+f.length());
text.requestFocus();
}
}
if(btn == replace)
{
if(text.getSelectedText().length()!=0)
{
String r = replaceText.getText();
text.replaceSelection(r);
}
}
-
if(btn == clear)
{
text.setText("");
findText.setText("");
replaceText.setText("");
occurrenceText.setText("");
findText.requestFocus();
}
}
}
24. Create an abstract class shape. Derive three classes sphere, cone and cylinder from
shape. Calculate area and volume of all (use method overriding). import java.io.*;
abstract class Shape
{
double r,h;
Shape(double r, double h)
{
this.r = r;
this.h = h;
}
abstract double calcArea();
abstract double calcVolume();
}
class Sphere extends Shape
{
Sphere(double r)
{
super(r,0);
}
double calcArea()
{
return 4*Math.PI*r*r;
}
double calcVolume()
{
return 4*Math.PI*Math.pow(r,3)/3;
}
}
class Cone extends Shape
{
Cone(double r, double h)
{
super(r,h);
}
-
double calcArea()
{
return Math.PI*r*(r+Math.sqrt(r*r+h*h));
}
double calcVolume()
{
return Math.PI*r*r*h/3;
}
}
class Cylinder extends Shape
{
Cylinder(double r, double h)
{
super(r,h);
}
double calcArea()
{
return 2*Math.PI*r*(h+r);
}
double calcVolume()
{
return Math.PI*r*r*h;
}
}
class ShapeTest
{
public static void main(String args[])
throws Exception
{
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));
Shape s=null;
double r=0,h=0;
while(true)
{
System.out.print("1.Sphere"+
"\n2.Cone"+
"\n3.Cylinder"+
"\n4.Exit"+
"\nEnter your choice (1-4):");
int ch = Integer.parseInt(br.readLine());
switch(ch)
{
case 1:
System.out.print("Enter radius of sphere:");
-
r = Double.parseDouble(br.readLine());
s = new Sphere(r);
break;
case 2:
System.out.print("Enter radius of cone:");
r = Double.parseDouble(br.readLine());
System.out.print("Enter height of cone:");
h = Double.parseDouble(br.readLine());
s = new Cone(r,h);
break;
case 3:
System.out.print("Enter radius of cylinder:");
r = Double.parseDouble(br.readLine());
System.out.print("Enter height of cylinder:");
h = Double.parseDouble(br.readLine());
s = new Cylinder(r,h);
break;
case 4:
System.exit(0);
}
System.out.println("Area = "+s.calcArea()+
"\nVolume = "+s.calcVolume());
}
}
}
25. Write a Java program to create GUI screen that display the following graphics.
Fill outer and inner rectangle with red color. Fill outer circle with yellow color and inner
circle with blue color. Draw graphical shapes in black color.
(Note: The examiners can change the graphics that is to be drawn. However, atleast 4
graphical objects need to be drawn and filled with different colors)
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
-
class MyPanel extends JPanel
{
public void paintComponent(Graphics g)
{
Graphics2D g2d = (Graphics2D)g;
int w = getWidth();
int h = getHeight();
g2d.setPaint(Color.RED);
g2d.fill(new Rectangle2D.Float(5,5,w-10,h-10));
g2d.setPaint(Color.BLACK);
g2d.draw(new Rectangle2D.Float(5,5,w-10,h-10));
g2d.setPaint(Color.YELLOW);
g2d.fill(new Ellipse2D.Float(w/2-150,h/2-150,300,300));
g2d.setPaint(Color.BLACK);
g2d.draw(new Ellipse2D.Float(w/2-150,h/2-150,300,300));
g2d.setPaint(Color.BLUE);
g2d.fill(new Ellipse2D.Float(w/2-100,h/2-100,200,200));
g2d.setPaint(Color.BLACK);
g2d.draw(new Ellipse2D.Float(w/2-100,h/2-100,200,200));
g2d.setPaint(Color.RED);
g2d.fill(new Rectangle2D.Float(w/2-50,h/2-25,100,50));
g2d.setPaint(Color.BLACK);
g2d.draw(new Rectangle2D.Float(w/2-50,h/2-25,100,50));
}
}
class TwoD extends JFrame
{
TwoD()
{
setTitle("Circles & Rectangles");
setSize(400,400);
add(new MyPanel());
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String args[])
{
new TwoD();
}
}
26. Write a Java program to create the following GUI screen.
-
The first Scroll bar will handle red color; the second will handle green color and third will
handle the blue color. Set min = 0, max = 255 for the scroll bars. The screen has two labels
and one command button Apply. When user clicks on the Apply button, set the background color of the label1 according to the RGB values set using the scrollbars.
Display the values of Red, Green, Blue in label2. import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class ScrollDemo extends JFrame
{
JScrollBar sbRed,sbBlue,sbGreen;
JLabel lblRed,lblBlue,lblGreen,lblValues;
JPanel panColor,panCenter;
JButton btnApply;
ScrollDemo()
{
sbRed = new JScrollBar(JScrollBar.HORIZONTAL,0,5,0,260);
sbGreen = new JScrollBar(JScrollBar.HORIZONTAL,0,5,0,260);
sbBlue = new JScrollBar(JScrollBar.HORIZONTAL,0,5,0,260);
lblRed = new JLabel("Red:");
lblGreen = new JLabel("Green:");
lblBlue = new JLabel("Blue:");
lblValues = new JLabel("(0,0,0)");
panColor = new JPanel();
panCenter = new JPanel();
btnApply = new JButton("Apply");
panCenter.setLayout(new GridLayout(4,2));
panCenter.add(lblRed);
panCenter.add(sbRed);
panCenter.add(lblGreen);
panCenter.add(sbGreen);
panCenter.add(lblBlue);
-
panCenter.add(sbBlue);
panCenter.add(lblValues);
panCenter.add(panColor);
setTitle("ScrollBar Demo");
setSize(400,200);
add(panCenter,"Center");
add(btnApply,"South");
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
btnApply.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
int r = sbRed.getValue();
int g = sbGreen.getValue();
int b = sbBlue.getValue();
lblValues.setText("("+r+","+g+","+b+")");
panColor.setBackground(new Color(r,g,b));
}
});
}
public static void main(String args[])
{
new ScrollDemo();
}
}
27. Write a Java program to create GUI screen that display the following graphics
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
class MyPanel extends JPanel
{
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
int w = getWidth();
int h = getHeight();
-
GeneralPath path = new GeneralPath();
path.moveTo(5,h/3);
path.lineTo(w/3,5);
path.lineTo(w-5,5);
path.lineTo(w-5,2*h/3);
path.lineTo(5,2*h/3);
path.closePath();
g2d.draw(path);
g2d.draw(new Rectangle2D.Float(w/3+5,10,w/6,h/4-10));
g2d.draw(new Rectangle2D.Float(w/3+w/6+35,10,w/3,h/4-10));
g2d.setPaint(Color.LIGHT_GRAY);
g2d.fill(new Ellipse2D.Float(w/4,2*h/3-50,100,100));
g2d.setPaint(Color.BLACK);
g2d.draw(new Ellipse2D.Float(w/4,2*h/3-50,100,100));
g2d.setPaint(Color.WHITE);
g2d.fill(new Ellipse2D.Float(w/4+30,2*h/3-25,45,45));
g2d.setPaint(Color.BLACK);
g2d.draw(new Ellipse2D.Float(w/4+30,2*h/3-25,45,45));
g2d.setPaint(Color.LIGHT_GRAY);
g2d.fill(new Ellipse2D.Float(w/2+60,2*h/3-50,100,100));
g2d.setPaint(Color.BLACK);
g2d.draw(new Ellipse2D.Float(w/2+60,2*h/3-50,100,100));
g2d.setPaint(Color.WHITE);
g2d.fill(new Ellipse2D.Float(w/2+90,2*h/3-25,45,45));
g2d.setPaint(Color.BLACK);
g2d.draw(new Ellipse2D.Float(w/2+90,2*h/3-25,45,45));
}
}
class CarDemo extends JFrame
{
CarDemo()
{
setTitle("Car Demo");
setSize(400,300);
add(new MyPanel());
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String args[])
{
new CarDemo();
}
}
-
28. Create a JSP page which accepts username and password. User can have 3 login chances only. If username and password is correct display a Welcome message else
display an error message. // Login.html
User Name:
Password:
// Login.jsp
=3)
{
out.print("Three attempts over.");
}
session.setAttribute("count",new Integer(count));
out.print("Login failed.");
}
%>
29. Write a program to create a package named Maths. Define classes as MathOp with
static methods to find the maximum and minimum of three numbers. Create another
package Stats. Define a class StatsOp with methods to find the average and median of
three numbers. Use these methods in main to perform operations on three integers
accepted using command line arguments. package Maths;
public class MathsOperations
{
public static int getMin(int a, int b, int c)
{
return a
-
{
return a>b?(a>c?a:c):(b>c?b:c);
}
}
package Stats;
public class StatsOperations
{
public static float avg(int a, int b, int c)
{
return (a+b+c)/3.0f;
}
public static float median(int a, int b, int c)
{
int min = ac?b:c);
return (min+max)/2.0f;
}
}
import Stats.*;
import Maths.*;
class PackTest
{
public static void main(String args[])
{
int x = Integer.parseInt(args[0]);
int y = Integer.parseInt(args[1]);
int z = Integer.parseInt(args[2]);
System.out.println(MathsOperations.getMin(x,y,z));
System.out.println(MathsOperations.getMax(x,y,z));
System.out.println(StatsOperations.avg(x,y,z));
System.out.println(StatsOperations.median(x,y,z));
}
}
30. Write a Java program to accept a decimal number in the text filed.. When the user
clicks the Calculate button the program should display the binary, octal, hexadecimal
equivalents.
-
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class Conversion extends JFrame
{
JLabel lblDec,lblBin,lblOct,lblHex;
JTextField txtDec,txtBin,txtOct,txtHex;
JButton btnCalc,btnClear;
Conversion()
{
lblDec = new JLabel("Decimal Number:");
lblBin = new JLabel("Binary Number:");
lblOct = new JLabel("Octal Number:");
lblHex = new JLabel("Hexadecimal Number:");
txtDec = new JTextField();
txtBin = new JTextField();
txtOct = new JTextField();
txtHex = new JTextField();
btnCalc = new JButton("Calculate");
btnClear = new JButton("Clear");
setTitle("Conversion");
setSize(300,250);
setLayout(new GridLayout(5,2));
add(lblDec);
add(txtDec);
add(lblBin);
add(txtBin);
add(lblOct);
add(txtOct);
add(lblHex);
add(txtHex);
add(btnCalc);
add(btnClear);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
-
btnCalc.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
int n = Integer.parseInt(
txtDec.getText());
txtBin.setText(
Integer.toBinaryString(n));
txtOct.setText(
Integer.toOctalString(n));
txtHex.setText(
Integer.toHexString(n));
}
});
btnClear.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
txtDec.setText("");
txtBin.setText("");
txtOct.setText("");
txtHex.setText("");
txtDec.requestFocus();
}
});
}
public static void main(String args[])
{
new Conversion();
}
}