You are on page 1of 42

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<n;i++)
new FileWatcher(args[i]).start();
}
}

2. Write a client-server program which displays the server machines date and time on the
client machine.
import java.net.*;
import java.io.*;
import java.util.*;
public class Server
{
public static void main(String args[])
throws Exception
{
ServerSocket ss = new ServerSocket(4444);
while(true)
{
Socket s = ss.accept();
PrintStream ps = new PrintStream(s.getOutputStream());
ps.println(new Date());
s.close();
}
}
}
import java.net.*;
import java.io.*;
import java.util.*;
public class Client
{
public static void main(String args[])
throws Exception
{
Socket s = new Socket("localhost",4444);
BufferedReader br = new BufferedReader(
new InputStreamReader(
s.getInputStream()));

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<rs.getRow())
{
rs.absolute(n);
dispRecord(rs);
}
else
{
System.out.println("Invalid rec no.");
}
break;
case 5:
System.exit(0);
}
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}

4. Write program to create a window that has a textbox/label to show current time. The
time should be displayed in hh:mm:ss format. The thread should start displaying the
time when the user clicks the Start button and stop when the user clicks the Stop
button.
import
import
import
import

java.awt.*;
java.awt.event.*;
javax.swing.*;
java.util.*;

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("<h3>Welcome Servlet<h3>"+
"Hit Count:<b>1</b>");
}
else
{

int val=Integer.parseInt(c[0].getValue())+1;
c[0].setValue(Integer.toString(val));
response.addCookie(c[0]);
out.println("Hit Count:<b>"+val+"</b>");
}
}
}

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
<form method='post' action='words.jsp'>
Enter Number:<input type='text' name='no'><br>
<input type='submit'><input type='reset'>
</form>
// words.jsp
<font color='blue'>
<%
String no = request.getParameter("no");
String words[]={"Zero","One","Two","Three","Four",
"Five","Six","Seven","Eight","Nine"};
for(int i=0;i<no.length();i++)
{
out.print(words[no.charAt(i)-'0']+" ");
}
%>
</font>

7. Create a JSP page, which accepts user name in a text box and greets the user according
to the time on server side.
eg.
User Name : tybsc
Good Morning tybsc ( if it is morning)
User Name : tybsc
Good Afternoon tybsc (if it is afternoon)
User Name : tybsc
Good Evening tybsc (if it is evening)
// user.html
<form method='post' action='user.jsp'>
User Name:<input type='text' name='uname'><br>
<input type='submit'><input type='reset'>
</form>

// user.jsp
<%@page import="java.util.*"%>
<%
String name = request.getParameter("uname");
Date d = new Date();
if(d.getHours()<10)
{
%>
Good Morning <%=name%>
<%
}
else if(d.getHours()<16)
{
%>
Good Afternoon <%=name%>
<%
}
else
{
%>
Good Evening <%=name%>
<%
}
%>

8. Create the table stud in database with attributes as rno,name,m1,m2,m3 as marks of 3


subjects. Accept student details from the console and add them in the table. Continue
the process until user enters a '0' to the prompt "Add More[Yes(1)/No(0)]?" Also
display the student details with total and percentage.
import java.io.*;
import java.sql.*;

class StudentInfo
{
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="";
String sql="SELECT * FROM stud";
String insertSQL="INSERT INTO stud VALUES(?,?,?,?,?)";
Connection con = null;
PreparedStatement ps = null;

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
throws Exception
{
LinkedList <String> ll1 =
LinkedList <String> ll2 =
LinkedList <String> ll3 =
LinkedList <String> ll4 =

args[])
new
new
new
new

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

case

case

case

case

s = br.readLine();
if(!ll2.contains(s)) ll2.add(s);
break;
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;
4:
int n = ll3.size();
ListIterator <String>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;
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;
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
<form method='post' action='http://localhost:8080/tybcs1/add'>
<h4>Select Course</h4>
<input type='radio' name='course' value='MBA'>MBA<br>
<input type='radio' name='course' value='MSc'>MSc<br>
<input type='radio' name='course' value='MCA'>MCA<br>
<input type='radio' name='course' value='MCM'>MCM<br>
<input type='submit'><input type='reset'><br>
</form>
<a href='http://localhost:8080/tybcs1/view'>View Cookies</a>
// 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("<h4>Cookie added with value "+value+"</h4>");
}
}
// 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("<table border=1>"+
"<tr><th>Name</th><th>Value</th></tr>");
for(int i=0;i<c.length;i++)
{
pw.println("<tr>"+
"<td>"+c[i].getName()+"</td>"+
"<td>"+c[i].getValue()+"</td>"+
"</tr>");
}
}
}

12. Write a Java thread program that displays the string Welcome to Java that moves
horizontally from left hand side of a frame panel to the right hand side.
import java.awt.*;
import javax.swing.*;

class MoveText extends JFrame implements Runnable


{
String str = "Welcome to Java";
Thread t;
int x;
MoveText()
{
setBackground(Color.YELLOW);
setSize(300,300);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
t = new Thread(this);
t.start();
}
public void run ()
{
while(true)
{
try

{
if(x<getWidth()) x++;
else x=0;
repaint();
Thread.sleep(250);
}catch(Exception e) {}
}
}
public void paint(Graphics g)
{
super.paint(g);
g.setColor(Color.RED);
g.drawString(str, x, 150);
}
public static void main(String args[])
{
new MoveText();
}
}

13. Write a Java program using threads for the following. (use Swing or AWT)

When the user clicks on the even button, your program should keep on displaying even
numbers till the user clicks on respective stop. Similarly, when the user clicks on the
odd button, your program should keep on displaying odd numbers till the user clicks on
its respective stop. (User may fix the range of even and odd numbers)

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class EvenThread extends Thread


{
JTextArea ta;
int count;
EvenThread(JTextArea ta)
{
this.ta=ta;
count=0;

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

case

case

case

case

ht.put(bid,bname);
break;
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;
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;
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;
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 <Student>studList = new LinkedList();
for(int i=0;i<n;i++)
{
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 percentage:");
float per = Float.parseFloat(br.readLine());
studList.add(new Student(rno,name,per));
}
Collections.sort(studList,new NameComparator());

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<=noCols;i++)
{
System.out.println("Column "+i+
"\nName:"+rsmd.getColumnName(i)+
"\nType:"+rsmd.getColumnTypeName(i));
}
rs.last();
int noRecords = rs.getRow();
System.out.println("No.of records:"+noRecords);
rs.close();

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(Age<15 || Age>21)
throw new InvalidAgeException();
for(int i=0; i<Name.length(); i++)
if(Character.isDigit(Name.charAt(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<names.length;i++)
{
File f = new File(name+"/"+names[i]);
if(f.isFile())
{
System.out.println(names[i]+
"\t"+f.length());
if(names[i].endsWith(".txt"))
{
System.out.print("Delete Y/N?");
String ch=br.readLine();
if(ch.equals("Y"))
f.delete();
}
count++;
}
}
System.out.println("No.of file in directory "+
name+":"+count);
}
}
}

21. Write a program to read student information as rollno, name, class and percentage and
store it in a file stud.dat. Display the details of the student having a given rollno.
import java.io.*;

class StudentInfo
{
public static void main(String args[])
{
try
{
BufferedReader br = new BufferedReader(
new InputStreamReader(
System.in));
DataOutputStream dos = new DataOutputStream(
new FileOutputStream("stud.dat",true));
while(true)
{
System.out.print("Enter roll no (0 to quit):");
int rno=Integer.parseInt(br.readLine());
if(rno==0) break;

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
<form method='post' action='login.jsp'>
<table>
<tr><td>User Name:</td><td><input type='text' name='uname'></td></tr>
<tr><td>Password:</td><td><input
type='password'
name='pass'></td></tr>
<tr><td><input type='submit'></td><td><input type='reset'></td></tr>
</table>
</form>
// Login.jsp
<%
String uname=request.getParameter("uname");
String pass=request.getParameter("pass");
Integer attempts = (Integer)session.getAttribute("count");
int count=1;
if(attempts!=null)
{
count=attempts.intValue()+1;
}
if(uname.equals("tybcs") && pass.equals("computers") && count<3)
{
out.print("<h4>Login successfully</h4>");
}
else
{
if(count>=3)
{
out.print("<h4>Three attempts over.</h4>");
}
session.setAttribute("count",new Integer(count));
out.print("<h4>Login failed.</h4>");
}
%>

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<b?(a<c?a:c):(b<c?b:c);
}
public static int getMax(int a, int b, int c)

{
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 = a<b?(a<c?a:c):(b<c?b:c);
int max = a>b?(a>c?a:c):(b>c?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 =
lblBin =
lblOct =
lblHex =
txtDec
txtBin
txtOct
txtHex

=
=
=
=

new
new
new
new

JLabel("Decimal Number:");
JLabel("Binary Number:");
JLabel("Octal Number:");
JLabel("Hexadecimal Number:");

new
new
new
new

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

You might also like