Annamalai University

Download as pdf or txt
Download as pdf or txt
You are on page 1of 55

IT0226

ANNAMALAI UNIVERSITY
DIRECTORATE OF DISTANCE EDUCATION

M.Sc INFORMATION TECHNOLOGY


SECOND SEMESTER

PROGRAMMING LAB – IV
Annamalai University
JAVA PROGRAMMING

Copyright Reserved
(For Private Circulation Only)
Java Programming

Java Programming Lab


QUESTIONS & SOLUTIONS
1. Write a program to display the greatest of the given 3 numbers. (ifelse.java)

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 + ".'");
}
}

3. Write a program to illustrate multiple inheritance to display the student’s marks


and the sports details. (mltinh.java)

class student
{
int rollno;
void getnum(int n)
{

}
rollno = n; Annamalai University
void putnum()
{
System.out.println("Roll NO. :"+rollno);
}
}

class test extends student


{
float sub1, sub2;

Page 2
Java Programming

void getmrks(float m1, float m2)


{
sub1 = m1;
sub2 = m2;
}
void putmks()
{
System.out.println("Marks Obtained");
System.out.println("Subject 1 = " + sub1);
System.out.println("Subject 2 = " + sub2);
}
}

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

4. Write a program to illustrate the checkbox of the swing component.


(chkbox.java)

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

5. Write a program to create a moving banner. (banner.java)

/* Write an applet program to create a thread that scrolls the message */


import java.awt.*;
import java.applet.*;

Page 4
Java Programming

/*public class banner 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");
}
}
*/
public class banner extends Applet implements Runnable {
String msg = "A Moving Banner";
Thread t = null;
int st;
boolean stopflag;

public void init()


{ setBackground(Color.cyan);
setForeground(Color.blue);
}
public void start()
{
t = new Thread(this);
stopflag = false;
t.start();
}
public void run()
{
char ch;
for(; ;)
{
try
{

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

public void stop()


{
stopflag = true;
t = null;
}
public void paint(Graphics g)
{
g.drawString(msg,50,30);
}
}

6. Write a program to display stars * as shown using continue and break


statements. (contbr.java)
*
**
.....
.....
**********
class contbr
{
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 == i)
continue LOOP1;
}
}
System.out.println("Teminated by Break");
}
} Annamalai University
7. Write a program to display the following using for loop: (forloop.java)
1
22
.....
.....
999999999
class forloop
{
public static void main(String args[])

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

8. Write a prgram to draw applet using control loop. (ctrloop.java)

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

9. Create an applet to draw a polygon with one half as solid. (poly.java)

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;

public void paint(Graphics g)


{
g.drawPolygon(x1,y1,n1);
g.fillPolygon(x2,y2,n2);
}
}

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

System.out.print("Enter Rate Of Interest :");


System.out.flush();
String rstr = in.readLine();
inrt = Float.valueOf(rstr);
System.out.print("Enter No. of Years :");
System.out.flush();

Page 8
Java Programming

String ystr = in.readLine();


nyrs = Integer.parseInt(ystr);
}
catch(IOException e)
{
System.out.println("I/O Error");
System.exit(1);
}
float finval = loan(pamt.floatValue(),inrt.floatValue(),nyrs);
prtln();
System.out.println("Final Value =" + finval);
prtln();
}
static float loan(float p, float r, int n)
{
int yr = 1;
float sum = p;
while(yr <= n)
{
sum = sum * (1 + r);
yr = yr + 1;
}
return sum;
}
static void prtln()
{
for(int i = 1; i <= 50; i++)
{
System.out.print("*");
}
System.out.println(" ");
}
}
Annamalai University
11. Create an applet to draw a human face. (humface.java)

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

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

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

System.out.println("Input File Not Found");


return;
}

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

16. Write a program to create a class with simple properties. (simprop.java)

public class simprop


{
private float amplitude,frequency,phase;
public simprop()
{
amplitude=0f;
frequency=100f;
phase=0f;
}
public float getAmplitude()
{
return amplitude;
}
public void setAmplitude(float Amplitude)
{
this.amplitude= Amplitude;
}
public float getfrequency()
{
return frequency;
}
public void setFrequency(float frequency)
{

}
Annamalai University
this.frequency=frequency;

public float getPhase()


{
return phase;
}
public void setPhase(float phase)
{
this.phase=phase;
}
}

Page 13
Java Programming

17. Write a program to create an applet to draw a lamp. (lamp.java)

/*program to draw a lamp*/


import java.awt.*;
import java.awt.Color;
public class lamp extends java.applet.Applet
{
public void init()
{
resize(300,300);
}
public void paint(Graphics g)
{
g.setColor(Color.red);
g.fillRect(0,250,290,290);
g.drawLine(125,250,125,160);
g.drawLine(175,250,175,160);
g.drawArc(85,157,130,50,-65,312);
g.drawArc(85,87,130,50,62,58);
g.drawLine(85,177,119,89);
g.drawLine(215,177,181,89);
g.setColor(Color.blue);
g.fillArc(78,120,40,40,63,-174);
g.fillOval(120,96,40,40);
g.fillArc(173,100,40,40,110,180);
}
}

18. Write a program to create an applet to draw a moving banner. (banr.java)

/*program to display a moving banner*/

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

public void start()


{
if(t==null)
t = new Thread (this);
t.start();
}
public void stop()
{
if(t!=null)
{
t.stop();

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

19. Write a program to create an applet to display a scrollbar. (scroll.java)

/*The Scrollbar object:*/


import java.awt.*;
Annamalai University
import java.applet.*;
public class scroll extends Applet
{
Scrollbar s=new Scrollbar(Scrollbar.HORIZONTAL,50,100,0,100);
Label l=new Label ("choose your tax rate");
TextField t=new TextField("50%", 3);
public void init()
{
add(s);
add(l);
add(t);
Page 15
Java Programming

}
public boolean handleEvent (Event e)
{
if (e.target instanceof Scrollbar)
{
int taxrate=((Scrollbar)e.target).getValue();
t.setText(taxrate + "%");
return true;
}
return false;
}
}

20. Write a program to create an applet to display a growing text. (marquee.java)

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

public void paint (Graphics g)


{Font newFont=new Font("TimesRoman", Font.BOLD, f);
g.setFont (newFont);
FontMetrics fontmetrics =g.getFontMetrics ();
int width=fontmetrics.stringWidth(msg);
g.drawString (msg,x,y);
f+=2;
if(f>50) f=2;
}
}

21. Write a program to create an applet to display a bouncing ball. (ball.java)

/*The program below is intended to illustrate the bounching ball animation.*/

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

public void stop()


{
if(mythread != null)
{
mythread.stop(); Annamalai University
mythread = null;
}
}
public void run()
{
while (true)
{
repaint();
bx += incx;

Page 17
Java Programming

if (bx > mx || bx < 10)


{
incx *= -1;
bx +=2*incx;
}
by += incy;
if (by > mx || by < 1)
{
incy *= -1;
by +=2*incy;
}
try{Thread.sleep(25);
}
catch(InterruptedException e) {}
}
}

public void paint (Graphics g)


{
g.setColor(Color.white);
g.fillOval (bx,by, bdia, bdia);
}}

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

CheckboxGroup cbg=new CheckboxGroup();


add(new Checkbox(str8));
add(new Checkbox(str14));
add(new Checkbox(str24));
add(new Checkbox(str32));
intFontSize = new Integer(str8);
}
public boolean action (Event e, Object arg)
{
if(e.target instanceof Checkbox)
{
Checkbox checkbox=(Checkbox)e.target;
intFontSize=Integer.valueOf(checkbox.getLabel());
repaint ();
}
return true;
}
public void paint(Graphics g)
{
Font f=new Font ("TimesRoman", Font.BOLD,intFontSize.intValue());
g.setFont(f);
g.drawString("Hello World", 50,75);
}
}

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

24. Write a program to create an applet to display a piechart. (piechart.java)

/*The program to draw a piechart.*/

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

25. Write a program to create an applet to display a system date/time as a string.


(strings.java)

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

/*A Single threaded Java Program*/

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)

/*Font class providing different font types in different sizes */

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

28. Write a program to demonstrate thread priority. (TestThread.java)

// Explains Priority Of A THread


class TestingThread extends Thread
{
Thread MinThread,MaxThread,NormThread;
int i=0;
TestingThread()
{ Annamalai University
MinThread = new Thread("min");
MinThread.setName("min");
MinThread.setPriority(Thread.MIN_PRIORITY);
MaxThread = new Thread("max");
MaxThread.setName("Max");
MaxThread.setPriority(Thread.MAX_PRIORITY);
NormThread = new Thread("norm");
NormThread.setName("Norm");
NormThread.setPriority(Thread.NORM_PRIORITY);
start();

Page 22
Java Programming

public void run()


{
try
{
for(i=0;i<5;i++)
{
System.out.println(" Thread \t\t"
+Thread.currentThread());
Thread.sleep(100);
}
}
catch(InterruptedException e){}
}
}

public class TestThread


{
public static void main(String s[])
{
TestingThread t1 = new TestingThread();
TestingThread t2=new TestingThread();
TestingThread t3=new TestingThread();
}
}

29. Write a program to create an applet to display message in the status bar.
(status.java)

/* Write an applet program to message in status bar*/

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

30. Write a program to create an applet to display tabbedpanel. (tabbedpanel.java)

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class tabbedpanel extends JPanel

String tabs[]= {"One","Two","Three","Four"};


public JTabbedPane tabbedPane = new JTabbedPane();
public tabbedpanel()
{
setLayout(new BorderLayout());
for(int i=0;i<tabs.length;i++)
tabbedPane.addTab(tabs[i], null,createPane(tabs[i]));
tabbedPane.setSelectedIndex(0);
add(tabbedPane,BorderLayout.CENTER);

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

33. Write a program to update a column using setAutoCommit (false). (fifth.java)

import java.sql.*;
import java.util.*;

public class fifth


{
static int sno;
static String sc,sname;

public static void main(String args[])


{
try
{
Class. forName("sun.jdbc.odbc.JdbcOdbcDriver");
}
catch(java.lang.ClassNotFoundException e)
{
System.err.print("ClassNotFoundException:");
System.err.print(e.getMessage());
}
try
{
String url="jdbc:odbc:MyData";
Connection con=DriverManager.getConnection(url);
Statement stmt=con.createStatement();
String sql="select * from stud1";
ResultSet rs=stmt.executeQuery(sql);

con.setAutoCommit(true);

System.out.println("autocommit set 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();

String sql1="select * from stud1";


ResultSet rsl=stmt.executeQuery(sql1);

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

public class ninth


{
public static void main(String args[])
{
String url="jdbc:odbc:MyData";

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

for(int i = 0; i < size; i++)


{
for(int j = i+1; j < size; j++)
{
if(name[j].compareTo(name[i]) < 0)
{
temp = name[i];
name[i] = name[j];
name[j] = temp;
}
}
}
for(int i = 0; i < size; i++)
{
System.out.println(name[i]);
}
}
}

37. Write a program to display date using servlets. (DatePrintServlet.java)

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

<applet code=Appletparam.class height=400 width=400>


<param name="string" value="US">
</applet>
********

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

Electricity(int a, String b, int c, int d, char CCode)


{
System.out.println("Numeric Code Constructor");
Cno=a;
CName=b;
Cmr=c;
Pmr=d;
Uc=c-d;
if(CCode=='F' || CCode=='f')
{
Ba=(double)Uc * 15;
Remark="Farmer";
}
else if(CCode=='D' || CCode=='d')
{
Ba=(double)Uc * 1;
Remark="Domestic";
}
else Annamalai University
{
Ba=(double)Uc * 1.5;
Remark="Commercial";
}
//ShowBill();
}
Electricity(int a, String b, int c, int d, int NCode)
{
System.out.println("Numeric Code Constructor");

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;

public static void main(String args[])

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

System.out.println(" Course Report ");


System.out.println(" ================ ");
System.out.println(" Student No :"+ sno);
System.out.println(" Name :"+ sname);
System.out.println(" Course :"+ sc);

System.out.println(" ================= ");


}
}
catch(Exception e)
{
System.out.println(e);
System.exit(0);
}
}
}

41. Write a program to Illustrate slider panel. (slider.java)

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

JSlider Right, Bottom;


Right = new JSlider(0,1,10,10);
Hashtable H = new Hashtable();
H.put(new Integer (1), new JLabel("Java 2.0"));
H.put(new Integer (2), new JLabel("Html"));
H.put(new Integer (3), new JLabel("Dhtml 2.0"));
H.put(new Integer (4), new JLabel("Swing 2.0"));
H.put(new Integer (5), new JLabel("Servlt 2.0"));
H.put(new Integer (6), new JLabel("Jdbe"));
H.put(new Integer (7), new JLabel("Perl"));
H.put(new Integer (8), new JLabel("CGI"));
H.put(new Integer (9), new JLabel("VBSript"));

Right.setLabelTable(H);
Right.setPaintLabels(true);
Right.setInverted(true);

Bottom = new JSlider(1,0,100,50);

Bottom.setMajorTickSpacing(10);
Bottom.setPaintLabels (true);

add(Right, BorderLayout.EAST);
add(Bottom, BorderLayout.SOUTH);

// Right.add(BorderLayout.EAST);
// Bottom.add(BorderLayout.SOUTH);
}

public static void main(String[] args)


{

JFrame frame = new JFrame("COMPUTER COUCH");


frame.addWindowListener(new WindowAdapter()
{
Annamalai University
public void windowClosing (WindowEvent e)
{
System.exit(0);
}
});
frame.setContentPane(new Slider());
frame.pack();
frame.setVisible(true);
}
}

Page 37
Java Programming

42. Write a progrma to demonstrate menus in java using swing. (MenuDemo.java)

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

public class MenuDemo extends JFrame


{
public static int WIDTH = 300;
public static int HEIGHT = 300;
public static String TITLE = "MenuDemo";
Container frameContainer;

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

public void layoutComponents()


{
frameContainer = getContentPane();
frameContainer.setLayout(null);
label.setBounds(25,75,300,40);
frameContainer.add(label);
}

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

public class WindowHandler extends WindowAdapter


{
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
public class MenuItemHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String cmd = e.getActionCommand();
if(cmd.equals("Exit")) System.exit(0);
else label.setText("You Have Selected: "+cmd);
}
}
public class ItemHandler implements ItemListener
{
public void itemStateChanged(ItemEvent e)
{
AbstractButton button = (AbstractButton) e.getItem();
String text = button.getText();
String display="Welcome to American Education
Systems";
label.setText(display);
if(text.equals("Red") && button.isSelected())
label.setForeground(Color.red);
else if(text.equals("Green") && button.isSelected())
label.setForeground(Color.green);

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

44. Write a program to create a bean for introspection. (IntrospectorDemo.java)

Note:Uses Colors.class for introspection.

// Introspection

import java.beans.*;
import java.awt.*;

public class IntrospectorDemo


{
public static void main(String args[])
{
try
{ Annamalai University
System.out.println("Hai");
Class c = Class.forName("Colors");
System.out.println("class loaded");
BeanInfo beaninfo = Introspector.getBeanInfo(c);
BeanDescriptor
beanDescriptor=beaninfo.getBeanDescriptor();
System.out.println("Bean Name = " +
beanDescriptor.getName());
System.out.println("Hello");

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

public class bool extends Applet implements Serializable


{
boolean rect=true;
public boolean isrectangle()
{
return rect; Annamalai University
}
public void setrectangle(boolean a)
{
rect =a;
}
public boolean getrectangle()
{
return rect;
}

Page 42
Java Programming

public void paint(Graphics g)


{
if(rect)
g.fillRect(10,10,100,50);
else
g.fillOval(10,10,100,50);
}
}

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

public void clear()


{
display.setText(" ");
}
public void keyTyped(KeyEvent e)
{
if(displayType.equals("Numeric Field"))
{
char c;
Annamalai University
if(!((c=e.getKeyChar()) >='0' && c<='9'))
{
e.consume();
Toolkit.getDefaultToolkit().beep();
}
}
}
public void keyReleased(KeyEvent e) { }
public void keyPressed(KeyEvent e) { }
protected PropertyChangeSupport listeners = new

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

47. Write a programs to create sequence of codes for a client/server application


Using RMI.
Source Files on Server Side:
1. Annamalai University
Addserverint.java
2. AddServer.java
3. AddServerImpl.java
Addserverint.java

import java.rmi.*;

public interface Addserverintf extends Remote


{

Page 46
Java Programming

double add (double d1,double d2) throws RemoteException;


}
AddServer.java

import java.net.*;
import java.rmi.*;

public class AddServer


{
public static void main(String args[])
{
try
{
AddServerImpl addServerImpl = new
AddServerImpl();
Naming.rebind("AddServer",addServerImpl);
}
catch (Exception e)
{
System.out.println("exception: "+e);
}
}
}

AddServerImpl.java

import java.rmi.*;
import java.rmi.server.*;

public class AddServerImpl extends UnicastRemoteObject implements Addserverintf


{
public AddServerImpl() throws RemoteException
{}

public double add(double d1,double d2) throws

{
Annamalai University
RemoteException

return d1+d2;
}
}

Instructions On server side:


Before compiling enter the following code in the command prompt.
set the path where Java is installed.

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.

create the stub and skeleton codes.

To do that,

enter rmic AddServerImpl.java in the command prompt.

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

The RMI Registry maps names to object references.

Start the Server

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.

Client Side Program: AddClient.java

import java.lang.*;
import java.rmi.*;

public class AddClient


{
public static void main(String args[])

Page 48
Java Programming

{
try
{
String addServerURL = "rmi://AES04/AddServer";

Addserverintf addServerintf =
(Addserverintf)Naming.lookup(addServerURL);

System.out.println("the sum is" +


addServerintf.add(5,6));

}
catch(Exception e)
{
System.out.println("Exception " + e);
}
}
}

Instructions on Client Side:

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

49. Write a program to present the GUI with BorderLayout. (border.java)

import java.awt.*;
import java.applet.*;
import javax.swing.*;
import javax.swing.JApplet;

/*
Annamalai University
<applet code=border height=400 width=400>
</applet>
*/

public class border extends JApplet


{
// INSTANCE VARIABLES
private JLabel nameLabel = new JLabel("Enter Your Name");
private JTextField nameTextField = new JTextField(24);
private JButton joinButton = new JButton("Join The Chat Room");
private JButton leaveButton = new JButton("Leave");

Page 49
Java Programming

private JButton sendButton = new JButton("Send");


private JTextArea inputTextArea = new JTextArea (10,40);
private JTextArea outputTextArea = new JTextArea(10,40);
private JScrollPane inputScrollPane = new JScrollPane(inputTextArea);
private JScrollPane outputScrollPane= new JScrollPane(outputTextArea);
private StringenterPrompt = "Enter Name To Join";
private Container appletContainer = getContentPane();

public void init()


{
JPanel pl = new JPanel();
pl.setLayout(new GridLayout(1,3));
pl.add(nameLabel);
pl.add(nameTextField);
pl.add(joinButton);
appletContainer.add(pl,BorderLayout.NORTH);

JPanel p2 = new JPanel();


p2.setLayout(new GridLayout(1,2));
p2.add(inputScrollPane);
p2.add(outputScrollPane);
appletContainer.add(p2, BorderLayout.CENTER);

JPanel p3 = new JPanel ();


p3.setLayout(new GridLayout (1,2));
JPanel p4 = new JPanel();
p4.add(sendButton);
p3.add(p4);
JPanel p5 = new JPanel();
p5.add(leaveButton);
p3.add(p5);
appletContainer.add(p3, BorderLayout.SOUTH);

} // end of client class.


}

Annamalai University
50. Write a servlet program using GenericServlet class to display some message.
(WelcServlet.java)

import java.io.*;
import javax.servlet.*;

public class WelcServlet extends GenericServlet


{
public void service (ServletRequest req, ServletResponse response)
throws ServletException, IOException

Page 50
Java Programming

{
response.setContentType("Text/html");
PrintWriter pW = response.getWriter();
pW.println("<B> Welcome to servlets!");
pW.close();
}
}

51. Write a program to display the ip address of a given host machine.


(LookUp.java)

import java.net.*;

public class LookUp


{
public static void main(String args[]) throws
UnknownHostException
{
InetAddress someHost;

byte bytes[];
int fourBytes[] = new int[4];
if(args.length == 0)
{
someHost = InetAddress.getLocalHost();
}
else
{
someHost = InetAddress.getByName(args[0]);
}

System.out.println("Host ' " +


someHost.getHostName() + "' has address: ");
bytes = someHost.getAddress();
for(int i=0; i<4; i++)
{
Annamalai University
fourBytes[i] = bytes[i] & 255;
}
System.out.println(fourBytes[0] + "." +
fourBytes[1] + "." +
fourBytes[2] + "." +
fourBytes[3]);
}
}

Page 51
Java Programming

Java Programming Lab

QUESTIONS

1. Write a program to display the greatest of the given 3 numbers. (ifelse.java)


2. Write a program to display the season given the month using switch case.
(switchcs.java)
3. Write a program to illustrate multiple inheritance to display the student’s marks
and the sports details. (mltinh.java)
4. Write a program to illustrate the checkbox of the swing component. (chkbox.java)
5. Write a program to create a moving banner. (banner.java)
6. Write a program to display stars * as shown using continue and break statements.
(contbr.java)
*
**
.....
.....
**********
7. Write a program to display the following using for loop: (forloop.java)
1
22
.....
.....
999999999
8. Write a program to draw applet using control loop. (ctrloop.java)
9. Create an applet to draw a polygon with one half as solid. (poly.java)
10. Write a program to accept values as datainputstream and calculate and print the
interest amount using wrapper classes. (wrapcls.java)
Annamalai University
11. Create an applet to draw a human face. (humface.java)
12. Write a program to display the URL details using java.net package.
(urldemo.java)
13. Write a program to copy the contents one file to another. (fcopy.java,source.txt)
14. Write an applet program for user interface to accept values and display the sum.
(inapt.java)
15. Write a servlet to initialize the counter. (Simplecounter.java)
16. Write a program to create a class with simple properties. (simprop.java)

Page 1
Java Programming

17. Write a program to create an applet to draw a lamp. (lamp.java)


18. Write a program to create an applet to draw a moving banner. (banr.java)
19. Write a program to create an applet to display a scrollbar. (scroll.java)
20. Write a program to create an applet to display a growing text. (marquee.java)
21. Write a program to create an applet to display a bouncing ball. (ball.java)
22. Write a program to create an applet to display check boxes to select font size and
display the text. (check.java)
23. Write a program to create an applet to copy text from one textarea to another.
(copytext.java)
24. Write a program to create an applet to display a piechart. (piechart.java)
25. Write a program to create an applet to display a system date/time as a string.
(strings.java)
26. Write a program to create a thread and display the time elapsed. (thread.java)
27. Write a program to create an applet to display fonts of different sizes. (font.java)
28. Write a program to demonstrate thread priority. (TestThread.java)
29. Write a program to create an applet to display message in the status bar.
(status.java)
30. Write a program to create an applet to display tabbedpanel. (tabbedpanel.java)
31. Write a program to display 9 * one below the other using 2 for loop and a
continue and break statements. (contbr.java)
32. Write a program to print the column details using resultsetmetadata and jdbc.
(eight.java, printcolumntypes.java)
33. Write a program to update a column using setAutoCommit. (false) (fifth.java)
34. Write a program to display the column names from the query which has been
given as the command line argument. (fourth.java)
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)

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

You might also like