Annamalai University
Annamalai University
Annamalai University
ANNAMALAI UNIVERSITY
DIRECTORATE OF DISTANCE EDUCATION
PROGRAMMING LAB – IV
Annamalai University
JAVA PROGRAMMING
Copyright Reserved
(For Private Circulation Only)
Java Programming
class ifelse
{
public static void main(String args[])
{
int a = 325, b = 712, c = 478;
System.out.print("Largest Value is :");
if (a > b)
{
if (a > c)
{
System.out.println(a);
}
else
{
System.out.println(c);
}
}
else
{
if (c > b)
{
System.out.println(c);
}
else
{
System.out.println(b);
}
}
}
}
Annamalai University
2. Write a program to display the season given the month using switch case.
(switchcs.java)
class switchcs
{
public static void main(String args[])
{
int mth = 4;
String season;
switch(mth)
Page 1
Java Programming
{
case 12:
case 1:
case 2:
season = "Winter";
break;
case 3:
case 4:
case 5:
season = "Spring";
break;
case 6:
case 7:
case 8:
season = "Summer";
break;
case 9:
case 10:
case 11:
season = "Autumn";
break;
default:
season = "Invalid Month";
}
System.out.println("April is in the " + season + ".'");
}
}
class student
{
int rollno;
void getnum(int n)
{
}
rollno = n; Annamalai University
void putnum()
{
System.out.println("Roll NO. :"+rollno);
}
}
Page 2
Java Programming
interface sports
{
float spwt = 6.0F;
void putWt();
}
class Results extends test implements sports
{
float total;
public void putWt()
{
System.out.println("Sports Wt = " + spwt);
}
void disp()
{
float tot = sub1+sub2+spwt;
putnum();
putmks();
putWt();
System.out.println("Total Score = " + tot);
}
}
class mltinh
{ Annamalai University
public static void main(String args[])
{
Results stu1 = new Results();
stu1.getnum(1234);
stu1.getmrks(27.5F, 63.0F);
stu1.disp();
}
}
Page 3
Java Programming
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
//<applet code=chkbox height=400 width=400></applet>
public class chkbox extends Applet implements ItemListener
{
Checkbox cb1,cb2,cb3;
String msg = " ";
public void init()
{
cb1 = new Checkbox("Computers");
cb2 = new Checkbox("Management");
cb3 = new Checkbox("Arts");
add(cb1);
add(cb2);
add(cb3);
cb1.addItemListener(this);
cb2.addItemListener(this);
cb3.addItemListener(this);
}
public void itemStateChanged(ItemEvent ie)
{ repaint(); }
public void paint(Graphics g)
{
msg = "Current State :";
g.drawString(msg,6,80);
msg = "Computers : " + cb1.getState();
g.drawString(msg,6,100);
msg = "Management : " + cb2.getState();
g.drawString(msg,6,120);
msg = "Arts Annamalai University
: " + cb3.getState();
g.drawString(msg,6,140);
}
}
Page 4
Java Programming
Annamalai University
repaint();
Thread.sleep(250);
ch = msg.charAt(0);
msg = msg.substring(1,msg.length());
msg += ch;
if(stopflag)
break;
}
catch(InterruptedException e) {}
}
}
Page 5
Java Programming
Page 6
Java Programming
{
System.out.println("Screen Display");
for(int i = 1; i <= 9; i++)
{
for(int j = 1; j <= i; j++)
{
System.out.print(i);
if(i==j)
System.out.println(" ");
}
}
}
}
import java.awt.*;
import java.applet.*;
public class ctrloop extends Applet
{
Annamalai University
public void paint(Graphics g)
{
for(int i = 0; i <= 5; i ++)
{
if (i%2 == 0)
g.drawOval(120,i*60+10,50,50);
else
g.fillOval(120,i*60+10,50,50);
}
}
}
Page 7
Java Programming
import java.awt.*;
import java.applet.*;
public class poly extends Applet
{
int x1[] = {20,120,220,20};
int y1[] = {20,120,20,20};
int n1 = 4;
int x2[] = {120,220,220,120};
int y2[] = {120,20,220,120};
int n2 = 4;
10. Write a program to accept values as datainputstream and calculate and print the
interest amount using wrapper Classes. (wrapcls.java)
import java.io.*;
class wrapcls
{
public static void main(String args[])
{
Float pamt = new Float(0);
Float inrt = new Float(0);
int nyrs = 0;
try
{
DataInputStream in = new DataInputStream(System.in);
Annamalai University
System.out.print("Enter Principal Amount :");
System.out.flush();
String pstr = in.readLine();
pamt = Float.valueOf(pstr);
Page 8
Java Programming
import java.awt.*;
import java.applet.*;
public class humface extends Applet
{
public void paint(Graphics g)
{
g.drawOval(40,40,120,150);
Page 9
Java Programming
g.drawOval(57,75,30,20);
g.drawOval(110,75,30,20);
g.fillOval(68,81,10,10);
g.fillOval(121,81,10,10);
g.drawOval(85,100,30,30);
g.fillArc(60,125,80,40,180,180);
g.drawOval(25,92,15,30);
g.drawOval(160,92,15,30);
}
}
12. Write a program to display the URL details using java.net package.
(urldemo.java)
import java.net.*;
class urldemo
{
public static void main(String args[]) throws MalformedURLException
{
URL hp = new URL("http://www.osborne.com/download");
13. Write a program to copy the contents one file to another. (fcopy.java,source.txt)
import java.io.*;
class fcopy
{
Annamalai University
public static void main(String args[]) throws IOException
{
int i;
FileInputStream fin;
FileOutputStream fout;
try
{
try
{ fin = new FileInputStream(args[0]); }
catch(FileNotFoundException e)
{
Page 10
Java Programming
try
{ fout = new FileOutputStream(args[1]); }
catch(FileNotFoundException e)
{
System.out.println("Error Opening Output File");
return;
}
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Usage : CopyFile From To");
return;
}
try
{
do{
i= fin.read();
if(i != -1) fout.write(i);
} while(i != -1);
}
catch(IOException e)
{
System.out.println("File Error");
}
fin.close();
fout.close();
}
}
content of source.txt :
This is a sample text file for demonstrating
the input output process to copy from one file to another.
Annamalai University
14. Write an applet program for user interface to accept values and display the sum.
(inapt.java)
import java.io.*;
import java.applet.*;
import java.awt.*;
//<applet code=Inapt height=400 width=400></applet>
public class Inapt extends Applet
{
Page 11
Java Programming
TextField t1,t2;
public void init()
{
t1 = new TextField(5);
t2 = new TextField(5);
add(t1);
add(t2);
t1.setText("0");
t2.setText("0");
}
public void paint (Graphics g)
{
int x = 0, y = 0, z = 0;
String s1,s2,s;
g.drawString("Input numbers in the text boxes", 10,50);
try
{
s1 = t1.getText();
x = Integer.parseInt(s1);
s2 = t2.getText();
y = Integer.parseInt(s2);
}
catch (Exception ex) {}
z = x + y;
s = String.valueOf(z);
g.drawString("The sum is :",10,75);
g.drawString(s,100,75);
}
public boolean action(Event event, Object obj)
{
repaint();
return true;
}
}
Annamalai University
15. Write a servlet to initialise the counter. (Simplecounter.java)
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SimpleCounter extends HttpServlet
{
int count=0;
public void doGet (HttpServletRequest req,
Page 12
Java Programming
HttpServletResponse res)
throws ServletException, IOException
{
res.setContentType("text/plain");
PrintWriter out = res.getWriter();
count++;
out.println("fine loading this Servlet has been
added" + count+"times");
}
}
}
Annamalai University
this.frequency=frequency;
Page 13
Java Programming
import java.lang.String;
import java.awt.*;
Annamalai University
import java.awt.Color;
import java.applet.*;
public class banr extends Applet implements Runnable
{
String msg; Thread t = null;
public void init()
{
setBackground(Color.cyan); setForeground(Color.red);
msg = "java makes the web move";
}
Page 14
Java Programming
t = null;
}
}
public void run ()
{
char ch;
for(; ;) {
try {
repaint (); Thread.sleep(350); ch = msg.charAt(0);
msg = msg.substring(1, msg.length()); msg +=ch;}
catch(InterruptedException e) {}
}
}
public void paint(Graphics g)
{
g.drawString (msg, 100,100);
}
}
}
public boolean handleEvent (Event e)
{
if (e.target instanceof Scrollbar)
{
int taxrate=((Scrollbar)e.target).getValue();
t.setText(taxrate + "%");
return true;
}
return false;
}
}
/*The program below illustrates a growing marquee in which the font size of the
character grow and fall.*/
import java.awt.*;
import java.lang.*;
import java.applet.*;
public class marquee extends Applet implements Runnable
{
Thread t; int x,y,f; String msg;
public void init()
{
x=10; y=100; f=5; msg="this is a growing marquee";}
public void start ()
{
t=new Thread(this);
t.start ();
}
public void run ()
{
for(;;)
{
Annamalai University
try{Thread.sleep(300);
}
catch(InterruptedException e) {}
repaint ();
}
}
public void stop ()
{
t.stop ();
}
Page 16
Java Programming
import java.applet.*;
import java.awt.*;
public class ball extends Applet implements Runnable
{
Thread mythread;
private
int bx, by, my=200, mx=400;
int bdia = 50; int incx = 10; int incy =10;
public void start()
{
if (mythread ==null)
{
mythread = new Thread (this);
mythread.start ();
}
}
Page 17
Java Programming
22. Write a program to create an applet to display check boxes to select font size and
display the text. (check.java)
/*Program to change the font size of the given text using check boxs*/
import java.awt.*;
public class check extends java.applet.Applet
{
final String str8="8";
final String str14="14";
final String str24="24";
final String str32="32";
Annamalai University
Integer intFontSize;
public static void main (String args[])
{
Frame f=new Frame("CHECKBOXES");
f.add("Center", new check());
f.resize (300, 150);
f.show ();
}
public check()
{
Page 18
Java Programming
23. Write a program to create an applet to copy text from one textarea to another.
(copytext.java)
/*The program to copy a selected text from one text area to another text area.*/
import java.awt.*;
import java.applet.*;
public class copytext extends Applet
{
private TextArea t1, t2;
private Button b;
Annamalai University
public void init ()
{
String s="Internet is a collection of individual data\n" +
"networks connected together in such a way\n"+
"that data can be transmitted back and forth\n"+
"between any one individual network\n"+
"and any other individual data network";
t1=new TextArea(5,20);
t1.setText(s);
t2=new TextArea(5,50);
Page 19
Java Programming
b=new Button("copy>>>");
setLayout(new FlowLayout(FlowLayout.LEFT, 5,5));
add(t1);
add(b);
add(t2);
}
public boolean action (Event e, Object o)
{
if (e.target==b)
{
t2.setText(t1.getSelectedText());
return true;
}
return false;
}
}
import java.applet.*;
import java.awt.*;
public class piechart extends Applet
{
final static int dataset[] = {20, 30, 40, 10};
final static String datalabel[] = {"apples", "oranges", "bananas", "others"};
final static Color datacolor[] = {Color.red, Color.blue, Color.green, Color.yellow};
int graphoffset = 20;
int graphdia = 150;
public void paint (Graphics g)
{
int startangle = 0, piesize;
int subtotal = 0;
for (int i = 0; i<dataset.length; i++)
Annamalai University
{subtotal += dataset[i];
piesize = subtotal*360/100 - startangle;
g.setColor(datacolor[i]);
g.fillArc(graphoffset, graphoffset, graphdia, graphdia, startangle, piesize);
startangle += piesize;
g.fillRect(graphoffset+ graphdia +10,graphoffset +i*20, 15, 15);
g.setColor(Color.black);
g.drawString(datalabel[i],graphoffset+graphdia+10+20,graphoffset+i*20+15);
}
}
}
Page 20
Java Programming
/*Drawing strings*/
import java.awt.Graphics;
import java.util.Date;
public class strings extends java.applet.Applet
{
String then;
public void init ()
{
Date now;
now=new Date ();
then=now.toString() ;
}
public void paint (Graphics g)
{
g.drawString ("Today's Date is :"+ then,10 ,10);
}
}
26. Write a program to create a thread and display the time elapsed. (thread.java)
class thread
{
public static void main(String args[])
{
long start = System.currentTimeMillis();
Thread t = Thread.currentThread();
System.out.println("CurrentThread"+t);
Annamalai University
t.setName("My Thread");
System.out.println("Current Thread :"+t);
try
{
for(int n=5; n>0; n--)
{
System.out.println(""+n);
Thread.sleep(1000);
}
}
catch(InterruptedException e)
Page 21
Java Programming
{
System.out.println("Interrupted");
}
System.out.println("No Interruption has occurred");
long end = System.currentTimeMillis();
System.out.println("Elapsed Time is"+(end-start));
}
}
27. Write a program to create an applet to display fonts of different sizes. (font.java)
import java.awt.*;
import java.applet.*;
public class font extends Applet
{
public void paint (Graphics g)
{
String fontlist[] = getToolkit().getFontList();
for (int i = 0; i < fontlist.length; i++)
{ Font f = new Font (fontlist[i], Font.BOLD, 16+1*4);
g.setFont(f);
g.drawString (fontlist[i] + (16+i*4) + " point", 5, i*35 + 20);}
}
}
Page 22
Java Programming
29. Write a program to create an applet to display message in the status bar.
(status.java)
import java.awt.*;
import java.applet.*;
Annamalai University
public class status extends Applet
{
public void init()
{ setBackground(Color.cyan);
}
public void paint(Graphics g)
{
g.drawString("This is in the Applet Window",10,20);
showStatus("This is in the Status Window");
}}
Page 23
Java Programming
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class tabbedpanel extends JPanel
JPanel createPane(String s)
{
JPanel p = new JPanel();
p.add(new JLabel(s));
return p;
}
public static void main(String args[])
{
JFrame frame = new JFrame("Tabbed Pane Example");
frame.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
Annamalai University
System.exit(0);
}
});
frame.getContentPane().add(new tabbedpanel(),BorderLayout.CENTER);
frame.setSize(400,125);
frame.setVisible(true);
}
}
Page 24
Java Programming
31. Write a program to display 9 * one below the other using 2 for loop and a
continue and break statements. (contbr1.java)
class contbr1
{
public static void main(String args[])
{
LOOP1 : for(int i = 1; i < 100; i++)
{
System.out.println(" ");
if (i >= 10) break;
for (int j = 1; j <=i; j++)
{
System.out.print("*");
if (j == 1)
continue LOOP1;
}
}
System.out.println("Teminated by Break");
}
}
32. Write a program to print the column details using resultsetmetadata and jdbc.
(eight.java, printcolumntypes.java)
eight.java
import java.sql.*;
public class eight
{
public static void main(String args[])
{
String url="jdbc:odbc:MyData";
Connection con;
String query="select * from stud1";
Statement stmt;
try
Annamalai University
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
}
catch(java.lang.ClassNotFoundException e)
{
System.err.print("ClassNotFoundException:");
System.err.print(e.getMessage());
}
try
Page 25
Java Programming
{
con=DriverManager.getConnection(url);
stmt=con.createStatement();
ResultSet rs=stmt.executeQuery(query);
ResultSetMetaData rsmd=rs.getMetaData();
//PrintColumnTypes.printColTypes(rsmd);
System.out.println(" ");
int noc=rsmd.getColumnCount();
for(int i=1;i<=noc;i++)
{
if(i>1)
System.out.println("");
String columnName=rsmd.getColumnName(i);
System.out.println(columnName);
}
System.out.println("");
while(rs.next())
{
for(int i=1;i<noc;i++)
{
if(i>1)
System.out.println("");
String columnValue=rs.getString(i);
System.out.println(columnValue);
}
System.out.println("");
}
stmt.close();
con.close();
}
catch(SQLException ex)
{
System.err.print("SQLException");
} Annamalai University
System.err.println(ex.getMessage());
}
}
printcolumntypes.java
import java.sql.*;
public class PrintColumnTypes
{
public static void main(String args[])
Page 26
Java Programming
{
String url="jdbc:odbc:MyData";
Connection con;
String query="select * from Stud1";
Statement stmt;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
}
catch(java.lang.ClassNotFoundException e)
{
System.err.print("ClassNotFoundException:");
System.err.print(e.getMessage());
}
try
{
con=DriverManager.getConnection(url);
stmt=con.createStatement();
ResultSet rs=stmt.executeQuery(query);
ResultSetMetaData rsmd=rs.getMetaData();
int noc=rsmd.getColumnCount();
for(int i=1;i<=noc;i++)
{
int jdbcType=rsmd.getColumnType(i);
String name=rsmd.getColumnTypeName(i);
System.out.println("Column "+i+"is JDBC
type"+jdbcType);
System.out.println(", Which the DBMS
Calls"+name);
}
stmt.close();
con.close();
}
Annamalai University
catch(SQLException ex)
{
System.err.print("SQLException");
System.err.println(ex.getMessage());
}
}
}
Page 27
Java Programming
import java.sql.*;
import java.util.*;
con.setAutoCommit(true);
while(rs.next())
{
Annamalai University
sno =rs.getInt("Regno");
sname=rs.getString("Name");
sc =rs.getString("Course");
System.out.println(sno+" "+sname+" "+sc);
}
PreparedStatement updatesc;
String updateString="update Stud1 set Course='"
+"Java'" + "where RegNo=101";
updatesc=con.prepareStatement(updateString);
System.out.println("Updated");
Page 28
Java Programming
updatesc.executeUpdate();
System.out.println("updated Data");
while(rsl.next())
{
sno=rsl.getInt("Regno");
sname=rs.getString("Name");
sc=rs.getString("Course");
System.out.println(sno+" "+sname+" "+sc);
}
}
catch(SQLException e)
{
System.err.print("SQLException");
System.out.println(e);
System.exit(0);
}
}
}
34. write a program to display the column names from the query which has been
given as the command line argument. (fourth.java)
import java.sql.*;
import java.util.*;
class fourth
{
public static void main(String args[])
{
if(args.length!=1)
{
Annamalai University
System.out.println("usage of java application
sql");
System.exit(0);
}
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
}
catch(java.lang.ClassNotFoundException e)
{
System.err.print("ClassNotFoundException:");
Page 29
Java Programming
System.err.print(e.getMessage());
}
try
{
String url="jdbc:odbc:MyData";
Connection con =
DriverManager.getConnection(url);
Statement stmt=con.createStatement();
String sql=args[0];
System.out.println(sql);
boolean hasResults=stmt.execute(sql);
if(hasResults)
{
ResultSet rs=stmt.executeQuery(sql);
if(rs!=null)
{
ResultSetMetaData rmeta =
rs.getMetaData();
int numcolumns =
rmeta.getColumnCount();
for(int i=1;i<=numcolumns;i++)
System.out.print(rmeta.getColumnName(i)
+" ");
}
}
con.close();
}
catch(Exception e)
{
System.err.print("SQLException");
System.out.println(e);
System.exit(0);
}
} //main
}
Annamalai University
35. Write a program to display the types of table available in the RDBMS that you
are using, with the help of databasemetadata. (ninth.java)
import java.sql.*;
Page 30
Java Programming
Connection con;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
}
catch(java.lang.ClassNotFoundException e)
{
System.err.print("ClassNotFoundException:");
System.err.print(e.getMessage());
}
try
{
con=DriverManager.getConnection(url);
DatabaseMetaData dbmd=con.getMetaData();
String dbmsName=dbmd.getDatabaseProductName();
ResultSet rs=dbmd.getTableTypes();
System.out.print("The following types of table
are");
System.out.println("available in" + dbmsName + "
:" );
while(rs.next())
{
String tableType=rs.getString("TABLE_TYPE");
System.out.println(" "+tableType);
}
rs.close();
con.close();
}
catch(SQLException e)
{
System.err.print("SQLException:"+e.getMessage());
}
}
}
Annamalai University
36. Write a program to swap the strings in ascending order. (swapstr.java)
class swapstr
{
static String name[] = {"Chennai", "Mumbai", "Delhi", "Agra","Patna"};
public static void main(String args[])
{
int size = name.length;
String temp = null;
Page 31
Java Programming
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.text.*;
import java.util.*;
public class DatePrintServlet extends HttpServlet
{
public void service(HTTPServletRequest
req,HTTPServletResponse res)throws IOException
{
String sToday;
Date today;
serveltOutPutStream out;
today=new Date();
Annamalai University
stoday=DateFormat.getDateInstance().format(today);
res.setContentType("text/plain");
out=res.getOutputStream();
out.print(stoday);
}
public String getServletInfo()
{
return "Return an in-line formatted representation of
the current date";
}
}
Page 32
Java Programming
38. Write a program to create an applet to receive parameters and display the
string. (appletparam.java, appletparam.html)
appletparam.java
import java.awt.*;
import java.applet.*;
public class Appletparam extends Applet
{
String str;
public void init()
{
str=getParameter("string");
if (str == null)
str = "Java";
str = "Hello" + str;
}
public void paint(Graphics g)
{
g.drawString(str,10,100);
}
}
appletparam.html
39. Write a program to illustrate the use of classes and calculate the electricity bill
with the given readings. (electricity.java)
class Electricity
{
int Cno,Cmr,Pmr,Uc;
Annamalai University
double Ba;
String CName, Remark;
public static void main(String args[])
{
int a,c,d,NCode;
String b, Scode;
char ACode[], CCode;
a=Integer.parseInt(args[0]);
b=args[1];
Page 33
Java Programming
c=Integer.parseInt(args[2]);
d=Integer.parseInt(args[3]);
Scode=args[4];
ACode=Scode.toCharArray();
CCode=ACode[0];
if(Character.isDigit(CCode))
{
NCode=Integer.parseInt(args[4]);
Electricity Eb=new Electricity(a,b,c,d,NCode);
Eb.ShowBill();
}
else
{
Electricity Eb=new Electricity(a,b,c,d,CCode);
Eb.ShowBill();
}
}
Page 34
Java Programming
Cno=a;
CName=b;
Cmr=c;
Pmr=d;
Uc=c-d;
if(NCode==1)
{
Ba=(double)Uc * 15;
Remark="Farmer";
}
else if(NCode==2)
{
Ba=(double)Uc * 1;
Remark="Domestic";
}
else
{
Ba=(double)Uc * 1.5;
Remark="Commercial";
}
//ShowBill();
}
void ShowBill()
{
System.out.println("Cno :"+Cno);
System.out.println("Cname :"+CName);
System.out.println("Cmr :"+Cmr);
System.out.println("Pmr :"+Pmr);
System.out.println("UC :"+Uc);
System.out.println("BA :"+Ba);
System.out.println("Remark :"+Remark);
}
}
Annamalai University
40. Write a program to print the student details using JDBC. (first.java)
import java.sql.*;
import java.util.*;
class first
{
static int sno;
static String sc,sname,rem;
Page 35
Java Programming
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url="jdbc:odbc:MyData";
Connection con=DriverManager.getConnection(url);
Statement stmt=con.createStatement();
String sql="select * from stud1";
ResultSet rs=stmt.executeQuery(sql);
while(rs.next())
{
sno=Integer.parseInt(rs.getString("RegNo"));
sname=(rs.getString("Name"));
sc=(rs.getString("Course"));
System.out.println(sc);
import java.awt.*;
Annamalai University
import java.awt.event.*;
import javax.swing.*;
import javax.swing.JSlider;
import java.util.Hashtable;
public class Slider extends JPanel
{
public Slider()
{
setLayout(new BorderLayout());
Page 36
Java Programming
Right.setLabelTable(H);
Right.setPaintLabels(true);
Right.setInverted(true);
Bottom.setMajorTickSpacing(10);
Bottom.setPaintLabels (true);
add(Right, BorderLayout.EAST);
add(Bottom, BorderLayout.SOUTH);
// Right.add(BorderLayout.EAST);
// Bottom.add(BorderLayout.SOUTH);
}
Page 37
Java Programming
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
// Swing components
JLabel label=new JLabel("Welcome to MenuDemo");
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
JMenuItem fileNew = new JMenuItem("New");
JMenuItem fileOpen = new JMenuItem("Open");
JMenuItem fileSave = new JMenuItem("Save");
JMenuItem fileExit = new JMenuItem("Exit");
JMenu specialMenu = new JMenu("Properties");
JCheckBoxMenuItem specialCheck1 = new
JCheckBoxMenuItem("Bold");
JCheckBoxMenuItem specialCheck2 = new
JCheckBoxMenuItem("Italic");
JSeparator separator = new JSeparator();
JRadioButtonMenuItem specialRadio1 = new
JRadioButtonMenuItem("Red");
JRadioButtonMenuItem specialRadio2 = new
JRadioButtonMenuItem("Blue");
JRadioButtonMenuItem specialRadio3 = new
JRadioButtonMenuItem("Green");
Annamalai University
ButtonGroup buttonGroup = new ButtonGroup();
public MenuDemo()
{
super(TITLE);
buildGUI();
label.setFont(new Font("TimesRoman",Font.PLAIN,20));
setupEventHandlers();
setSize(WIDTH,HEIGHT);
show();
}
Page 38
Java Programming
void buildGUI()
{
setupMenuBar();
layoutComponents();
}
void setupMenuBar()
{
fileMenu.add(fileNew);
fileMenu.add(fileOpen);
fileMenu.add(fileSave);
fileMenu.add(fileExit);
specialMenu.add(specialCheck1);
specialMenu.add(specialCheck2);
specialMenu.add(separator);
buttonGroup.add(specialRadio1);
buttonGroup.add(specialRadio2);
buttonGroup.add(specialRadio3);
specialMenu.add(specialRadio1);
specialMenu.add(specialRadio2);
specialMenu.add(specialRadio3);
menuBar.add(fileMenu);
menuBar.add(specialMenu);
setJMenuBar(menuBar);
}
Annamalai University
void setupEventHandlers()
{
addWindowListener(new WindowHandler());
fileNew.addActionListener(new MenuItemHandler());
fileOpen.addActionListener(new MenuItemHandler());
fileSave.addActionListener(new MenuItemHandler());
fileExit.addActionListener(new MenuItemHandler());
specialCheck1.addItemListener(new ItemHandler());
specialCheck2.addItemListener(new ItemHandler());
specialRadio1.addItemListener(new ItemHandler());
specialRadio2.addItemListener(new ItemHandler());
Page 39
Java Programming
specialRadio3.addItemListener(new ItemHandler());
}
public static void main(String[] args)
{
MenuDemo app = new MenuDemo();
}
Annamalai University
else if(text.equals("Blue") && button.isSelected())
label.setForeground(Color.blue);
if(text.equals("Italic") && button.isSelected())
label.setFont(new
Font("TimesRoman",Font.ITALIC,20));
else if(text.equals("Bold") && button.isSelected())
label.setFont(new Font("TimesRoman",Font.BOLD,20));
else label.setFont(new
Font("TimesRoman",Font.PLAIN,20));
}
}
Page 40
Java Programming
}
43. Write a program to print the port, protocol, host, file name from the given URL.
(URLDemo.java)
import java.net.*;
class URLDemo
{
public static void main(String args[]) throws
MalformedURLException
{
URL hp=new
URL("HTTP://www.sun.com:80/doc/ejb/whitepaper.html");
System.out.println("Protocol:" +hp.getProtocol());
System.out.println("Port:" +hp.getPort());
System.out.println("Host:" +hp.getHost());
System.out.println("File:" +hp.getFile());
System.out.println("Ext:" +hp.toExternalForm());
}
}
// Introspection
import java.beans.*;
import java.awt.*;
Page 41
Java Programming
System.out.println("Properties");
PropertyDescriptor propertyDescriptor[] =
beaninfo.getPropertyDescriptors();
for(int i=0; i<propertyDescriptor.length; i++)
{
System.out.println("\t" +
propertyDescriptor[i].getName());
}
System.out.println("Events");
EventSetDescriptor eventdescriptor[] =
beaninfo.getEventSetDescriptors();
for(int i=0; i<eventdescriptor.length; i++)
{
System.out.println("\t" +
eventdescriptor[i].getName());
}
}
catch(Exception e)
{}
}
}
45. Write a program to create a Bean to illustrate the boolean property. (bool.java)
import java.applet.*;
import java.awt.*;
import java.io.*;
Page 42
Java Programming
46. Write a program to develop a Bean to show how to restrict an editor from
accepting numeric values. (DisplayBean.java)
import java.awt.*;
import java.awt.event.*;
import java.io.Serializable;
import java.text.*;
import java.beans.*;
public class DisplayBean extends Container
implements Serializable,KeyListener
{
protected TextField display;
protected boolean editable;
protected boolean canDisplay;
protected String displayType = "Numeric Field";
protected String text;
public DisplayBean()
{
super();
text="";
setLayout(new GridLayout(1,1));
display=new TextField("hello welcome");
editable=true;
canDisplay=false;
add(display); Annamalai University
display.addKeyListener(this);
}
public synchronized void setEditable(boolean b)
{
if(b!=editable)
{
fireModeChange(editable,b);
editable=b;
display.setEditable(editable);
Page 43
Java Programming
}
}
public boolean getEditable()
{
return editable;
}
public String getDisplayType()
{
return displayType;
}
public synchronized void setDisplayType(String type)
{
if(!(displayType.equals(type)))
{
fireDisplayTypeChange(displayType,type);
displayType=type;
displayData(text);
}
}
public String getDisplayText()
{
return text;
}
public synchronized void setDisplayText(String text)
{
if(!(this.text.equals(text)))
{
fireTextChange(this.text,text);
displayData(text);
}
}
private void displayData(String text)
{
this.text=text;
Annamalai University
if(displayType.equals("Numeric Field"))
{
displayNumeric();
}
else if(displayType.equals("Text Field"))
{
displayText();
}
}
private void displayNumeric()
Page 44
Java Programming
{
for(int i=0;i<text.length();i++)
{
if(text.charAt(i)>='0' && text.charAt(i) <='9')
{
canDisplay=true;
}
else {
canDisplay=false;
break;
}
}
if(canDisplay)
{
display.setText(text);
}
else {
display.setText(" ");
}
canDisplay = false;
}
private void displayText()
{
display.setText(text);
}
Page 45
Java Programming
PropertyChangeSupport(this);
public synchronized void
addPropertyChangeListener(PropertyChangeListener l)
{
listeners.addPropertyChangeListener(l);
}
public synchronized void
removePropertyChangeListener(PropertyChangeListener l)
{
listeners.removePropertyChangeListener(l);
}
public void fireTextChange(String oldText,
String newText)
{
listeners.firePropertyChange("text",oldText,newText);
}
public void fireDisplayTypeChange(String
oldDisplayType,String newDisplayType)
{
listeners.firePropertyChange("displayType",
oldDisplayType,newDisplayType);
}
public void fireModeChange(boolean oldVal,
boolean newVal)
{
listeners.firePropertyChange("editable",
new Boolean(oldVal),new Boolean(newVal));
}
}
import java.rmi.*;
Page 46
Java Programming
import java.net.*;
import java.rmi.*;
AddServerImpl.java
import java.rmi.*;
import java.rmi.server.*;
{
Annamalai University
RemoteException
return d1+d2;
}
}
Page 47
Java Programming
Enter javac - d *.java in the comand prompt to compile the four source file you have
created.
Now all the class files has been created in a directory in whichever directory you have
placed.
To do that,
Now in the divide directory you can see the follwing files
Addserverintf.java
Addserverintf.class
AddServer.java
AddServer.class
AddServerImpl.java
AddServerImpl.class
AddServerImpl_skel.class
AddServerImpl_stud.class
copy all the java files from server machine to this client machine.(espl. Stub and
implementation class file)
Start the RMI Registry on the Server Machine using the command: start rmiregistry
Start the server code from the command line as shown here.
java AddServer
48. Write a program to send in two values to the server program(Q.no.47) and get
Annamalai University
back the result calculated using RMI.
import java.lang.*;
import java.rmi.*;
Page 48
Java Programming
{
try
{
String addServerURL = "rmi://AES04/AddServer";
Addserverintf addServerintf =
(Addserverintf)Naming.lookup(addServerURL);
}
catch(Exception e)
{
System.out.println("Exception " + e);
}
}
}
Compile and then Run the Client(AddClient.class). The client program takes 2
parameters within the program to the server and the result is calculated by the server and
the result is displayed on the screen.
java AddClient
import java.awt.*;
import java.applet.*;
import javax.swing.*;
import javax.swing.JApplet;
/*
Annamalai University
<applet code=border height=400 width=400>
</applet>
*/
Page 49
Java Programming
Annamalai University
50. Write a servlet program using GenericServlet class to display some message.
(WelcServlet.java)
import java.io.*;
import javax.servlet.*;
Page 50
Java Programming
{
response.setContentType("Text/html");
PrintWriter pW = response.getWriter();
pW.println("<B> Welcome to servlets!");
pW.close();
}
}
import java.net.*;
byte bytes[];
int fourBytes[] = new int[4];
if(args.length == 0)
{
someHost = InetAddress.getLocalHost();
}
else
{
someHost = InetAddress.getByName(args[0]);
}
Page 51
Java Programming
QUESTIONS
Page 1
Java Programming
Annamalai University
36. Write a program to swap the strings in ascending order. (swapstr.java)
37. Write a program to display date using servlets. (DatePrintServlet.java)
38. Write a program to create an applet to receive parameters and display the string.
(appletparam.java, appletparam.html)
39. Write a program to illustrate the use of classes and calculate the electricity bill
with the given readings. (electricity.java)
40. Write a program to print the student details using JDBC. (first.java)
41. Write a program to Illustrate slider panel. (slider.java)
42. Write a program to demonstrate menus in java using swing. (MenuDemo.java)
Page 2
Java Programming
43. Write a program to print the port, protocol, host, and file name from the given
URL. (URLDemo.java)
44. Write a program to create a bean for introspection. (IntrospectorDemo.java) Note:
Uses Colors.class for introspection.
45. Write a program to create a Bean to illustrate the boolean property. (bool.java)
46. Write a program to develop a Bean to show how to restrict an editor from
accepting numeric values. (DisplayBean.java)
47. Write programs to create sequence of codes for a client/server application using
RMI.
48. Write a program to send in two values to the server program (Q.No.47) and get
back the result calculated using RMI.
49. Write a program to present a GUI with BorderLayout. (border.java)
50. Write a servlet program using GenericServlet class to display some message.
(WelcServlet.java)
51. Write a program to display the ip address of a given host machine.
Annamalai University
Page 3