Professional Documents
Culture Documents
Sc IT Part II
___________________________________________________________________________
Practical 01
Problem Statement:
Description:
JFrame
The size of the frame includes any area designated for the border. The dimensions of the
border area may be obtained using the getInsets method, however, since these dimensions
are platform-dependent, a valid insets value cannot be obtained until the frame is made
displayable by either calling pack or show. Since the border area is included in the overall size
of the frame, the border effectively obscures a portion of the frame, constraining the area
available for rendering and/or displaying subcomponents to the rectangle which has an upper-
left corner location of (insets.left, insets.top), and has a size of width - (insets.left +
insets.right) by height - (insets.top + insets.bottom).
ActionListener:
The listener interface for receiving action events. The class that is interested in
processing an action event implements this interface, and the object created with that class is
registered with a component, using the component's addActionListener method. When the
action event occurs, that object's actionPerformed method is invoked.
_________________________________________________________________________
1
Java Technology M.Sc IT Part II
___________________________________________________________________________
Source Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.Container;
class SavingAccount extends JFrame implements ActionListener
{
JButton jb,jb1,jb2;
JTextField t1,t11;
double amount;String accountName;
SavingAccount(double amt,String Aname)
{
super("BANK ACCOUNT INFORMATION");
amount=amt;
accountName=Aname;
}
public void init()
{
Container c = getContentPane();
JPanel panel = new JPanel();
jb.setActionCommand("AddAmount");
jb1.setActionCommand("CheckAmount");
jb2.setActionCommand("ShowBalanceAndName");
jb.addActionListener(this);
jb1.addActionListener(this);
jb2.addActionListener(this);
panel.setLayout(new GridLayout(3,3));
panel.add(new JLabel("ENTER THE AMOUNT"));
panel.add(jb);
panel.add(new JLabel("WITHDRAWING AMOUNT"));
panel.add(t11 = new JTextField(20));
panel.add(jb1);
panel.add(jb2);
c.add(panel);
setSize(1000,100);
_________________________________________________________________________
2
Java Technology M.Sc IT Part II
___________________________________________________________________________
setVisible(true);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
public void actionPerformed(ActionEvent evt)
{
if(evt.getSource() == jb)
{
String a=t1.getText();
double b=Double.parseDouble(a);
amount+=b;
JOptionPane.showMessageDialog(null, "THE AMOUNT
IS="+amount,"DISPLAYING AMOUNT",JOptionPane.INFORMATION_MESSAGE);
}
if(evt.getActionCommand() == "CheckAmount")
{
if(amount>=500)
{ t11.setEditable(true);
String s=t11.getText();
double b=Double.parseDouble(s);
amount=amount-b;
if(amount<500)
{
JOptionPane.showMessageDialog(null,"YOUR
MINIMUM BALANACE SHOULD NOT BE LESS THAN 500 \n","WARNING
MESSAGE",JOptionPane.INFORMATION_MESSAGE);
amount=amount+b;
}
else
{
JOptionPane.showMessageDialog(null,"YOUR TOTAL
AMOUNT IS="+amount,"DISPLAYING
AMOUNT",JOptionPane.INFORMATION_MESSAGE);
}
}
}
if(evt.getActionCommand() == "ShowBalanceAndName")
{
JOptionPane.showMessageDialog(null,"TOTAL BALANCE
IS="+amount+"\n ACCOUNT HOLDER NAME IS="+accountName, "DISPLAYING
_________________________________________________________________________
3
Java Technology M.Sc IT Part II
___________________________________________________________________________
BALANCE AND ACCOUNTHOLDER
NAME",JOptionPane.INFORMATION_MESSAGE);
}
}
}
class AccountDepositerName extends SavingAccount
{
String typeOfAccount;
String depositer;
_________________________________________________________________________
4
Java Technology M.Sc IT Part II
___________________________________________________________________________
Output:
_________________________________________________________________________
5
Java Technology M.Sc IT Part II
___________________________________________________________________________
Practical 02-A
Write an Applet Application
Problem Statement:
A graphic program that displays your name four times in a large serif font in plain, bold italic
and bold italic. The name should be displayed on top of each other with equal distance between
them. Each of them should be centered horizontally.
Description:
java.applet package:
Provides the classes necessary to create an applet and the classes an applet uses to
communicate with its applet context. The applet framework involves two entities: the applet
and the applet context. An applet is an embeddable window (see the Panel class) with a few
extra methods that the applet context can use to initialize, start, and stop the applet.The applet
context is an application that is responsible for loading and running applets. For example, the
applet context could be a Web browser or an applet development environment.
Applet class:
An applet is a small program that is intended not to be run on its own, but rather to be
embedded inside another application. The Applet class must be the superclass of any applet
that is to be embedded in a Web page or viewed by the Java Applet Viewer. The Applet class
provides a standard interface between applets and their environment.
_________________________________________________________________________
6
Java Technology M.Sc IT Part II
___________________________________________________________________________
Source Code:
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*
<applet code="font" width=400 height=200>
</applet>
*/
String str,fontName;
Font font;
}
public void start()
{
}
public void paint(Graphics g)
{
font=new Font("Serif",Font.BOLD,18);
g.setFont(font);
g.drawString(str, 150, 80);
font=new Font("Serif",Font.PLAIN,18);
g.setFont(font);
g.drawString(str, 150, 100);
font=new Font("Serif",Font.ITALIC,18);
g.setFont(font);
g.drawString(str, 150, 120);
font=new Font("Serif",Font.BOLD|Font.ITALIC,18);
g.setFont(font);
g.drawString(str, 150, 140);
}
}
_________________________________________________________________________
7
Java Technology M.Sc IT Part II
___________________________________________________________________________
Output:
_________________________________________________________________________
8
Java Technology M.Sc IT Part II
___________________________________________________________________________
Practical 02-B
Problem Statement:
Write a graphics program to prompt user to enter radius. Draw a circle of that radius. Similarly
display different geometric shapes like line, square, rectangle, ellipse and polygon (with more
than four sides) as per the user co-ordinates.
Description:
javax.swing package:
Provides a set of "lightweight" (all-Java language) components that, to the maximum
degree possible, work the same on all platforms
ActionListener:
The listener interface for receiving action events. The class that is interested in
processing an action event implements this interface, and the object created with that class is
registered with a component, using the component's addActionListener method. When the
action event occurs, that object's actionPerformed method is invoked.
ItemListener:
The listener interface for receiving item events. The class that is interested in
processing an item event implements this interface. The object created with that class is then
registered with a component using the component's addItemListener method. When an item-
selection event occurs, the listener object's itemStateChanged method is invoked.
_________________________________________________________________________
9
Java Technology M.Sc IT Part II
___________________________________________________________________________
Source Code:
import javax.swing.*;
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
xpolygon5=new int[5];
ypolygon5=new int[5];
b1=new Button("Display");
b2=new Button("Display");
b3=new Button("Display");
b4=new Button("Display");
b5=new Button("Display");
b6=new Button("Enter Coordinate");
t1=new TextField(10);
t2=new TextField(10);
t3=new TextField(10);
t4=new TextField(10);
t5=new TextField(10);
t6=new TextField(10);
t7=new TextField(10);
t8=new TextField(10);
t9=new TextField(10);
t10=new TextField(10);
t11=new TextField(10);
t12=new TextField(10);
t13=new TextField(10);
t14=new TextField(10);
co=new CardLayout();
p1=new Panel();
p1.setLayout(co);
p2=new Panel();
p2.setLayout(new FlowLayout());
p2.add(l1);
p2.add(t1);
p2.add(b1);
p3=new Panel();
p3.setLayout(new GridLayout(3,3));
p3.add(l2);
p3.add(t2);
p3.add(l3);
p3.add(t3);
p3.add(b2);
_________________________________________________________________________
11
Java Technology M.Sc IT Part II
___________________________________________________________________________
p4=new Panel();
p4.setLayout(new GridLayout(3,3));
p4.add(l4);
p4.add(t4);
p4.add(b3);
p5=new Panel();
p5.setLayout(new GridLayout(5,3));
p5.add(l5);
p5.add(t5);
p5.add(l6);
p5.add(t6);
p5.add(l7);
p5.add(t7);
p5.add(l8);
p5.add(t8);
p5.add(b4);
p6=new Panel();
p6.setLayout(new GridLayout(3,2));
p6.add(l9);
p6.add(t9);
p6.add(l10);
p6.add(t10);
p6.add(b5);
p7=new Panel();
p7.setLayout(new GridLayout(4,2));
p7.add(l11);
p7.add(t11);
p7.add(l12);
p7.add(t12);
p7.add(l13);
p7.add(t13);
p7.add(b6);
p1.add(p2,"Circle");
p1.add(p3,"Rectangle");
p1.add(p4,"Square");
p1.add(p5,"Line");
p1.add(p6,"Oval");
p1.add(p7,"Polygon");
add(line);
add(circle);
add(oval);
_________________________________________________________________________
12
Java Technology M.Sc IT Part II
___________________________________________________________________________
add(rectangle);
add(square);
add(polygon);
add(p1);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
b5.addActionListener(this);
b6.addActionListener(this);
circle.addItemListener(this);
oval.addItemListener(this);
rectangle.addItemListener(this);
square.addItemListener(this);
line.addItemListener(this);
polygon.addItemListener(this);
_________________________________________________________________________
14
Java Technology M.Sc IT Part II
___________________________________________________________________________
else if(ae.getSource()==b6)
{
ch=6;
str=t11.getText();
no=Integer.parseInt(str);
while(flag<5)
{
str=t12.getText();
xpolygon5[flag]=Integer.parseInt(str);
str=t13.getText();
ypolygon5[flag]=Integer.parseInt(str);
t12.setText("");
t13.setText("");
flag++;
}
t11.setEnabled(false);
t12.setEnabled(false);
t13.setEnabled(false);
repaint();
}
}
_________________________________________________________________________
15
Java Technology M.Sc IT Part II
___________________________________________________________________________
else if(cbg.getSelectedCheckbox().getLabel().equals("Oval"))
{
repaint();
co.show(p1,"Oval");
}
else if(cbg.getSelectedCheckbox().getLabel().equals("Polygon"))
{
repaint();
co.show(p1,"Polygon");
}
}
}
_________________________________________________________________________
16
Java Technology M.Sc IT Part II
___________________________________________________________________________
Output:
_________________________________________________________________________
17
Java Technology M.Sc IT Part II
___________________________________________________________________________
_________________________________________________________________________
18
Java Technology M.Sc IT Part II
___________________________________________________________________________
_________________________________________________________________________
19
Java Technology M.Sc IT Part II
___________________________________________________________________________
Practical 03-A
Description:
java.util package:
Contains the collections framework, legacy collection classes, event model, date and
time facilities, internationalization, and miscellaneous utility classes (a string tokenizer, a
random-number generator, and a bit array).
java.awt.event package:
Provides interfaces and classes for dealing with different types of events fired by AWT
components. Events are fired by event sources. An event listener registers with an event source
to receive notifications about the events of a particular type. This package defines events and
event listeners, as well as event listener adapters, which are convenience classes to make easier
the process of writing event listeners.
java.awt package:
Provides interfaces and classes for dealing with different types of events fired by AWT
components. Contains all of the classes for creating user interfaces and for painting graphics
and images.
_________________________________________________________________________
20
Java Technology M.Sc IT Part II
___________________________________________________________________________
Source Code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JFrame;
import java.util.*;
JButton refstart,refstop,refexit;
JPanel refbuttonpanel,refcanvaspanel;
Container c;
drawcanvas refdc;
bouncestring()
{
c=getContentPane();
c.setLayout(new BorderLayout());
refdc=new drawcanvas();
refstart=new JButton("Start");
refstop=new JButton("Stop");
refexit=new JButton("Exit");
refbuttonpanel=new JPanel();
refcanvaspanel=new JPanel();
refbuttonpanel.add(refstart);
refbuttonpanel.add(refstop);
refbuttonpanel.add(refexit);
c.add(refbuttonpanel,BorderLayout.SOUTH);
c.add(refdc);
refstart.addActionListener(this);
refstop.addActionListener(this);
refexit.addActionListener(this);
setSize(200,300);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
_________________________________________________________________________
21
Java Technology M.Sc IT Part II
___________________________________________________________________________
refdc.move();
}
else if(ae.getSource()==refstop)
{
refdc.halt();
}
}
}
dx = 11; dy = 7;
dx1 = 11; dy1 = 11;
dx2 = 17; dy2 = 10;
}
public void paint(Graphics g)
{
g.setColor(Color.red);
_________________________________________________________________________
22
Java Technology M.Sc IT Part II
___________________________________________________________________________
g.drawString("India", x-r, y-r);
g.setColor(Color.green);
g.drawString("Germany", x1-r, y1-r);
g.setColor(Color.blue);
g.drawString("France", x2-r, y2-r);
}
public void run()
{
while(!stop)
{
refcurthread=Thread.currentThread();
System.out.println(Thread.currentThread());
if(refcurthread.getName().equalsIgnoreCase("First"))
{
if ((x - r + dx < 0) || (x + r + dx > getWidth()))
dx = -dx;
}
else if(refcurthread.getName().equalsIgnoreCase("Third"))
{
if ((x2 - r + dx2 < 0) || (x2 + r + dx2 > getWidth()))
dx2 = -dx2;
}
repaint();
try
{
Thread.sleep(60);
}
catch(Exception e)
{
}
}
}
public void move()
{
first=new Thread(this,"First");
second=new Thread(this,"Second");
third=new Thread(this,"Third");
first.start();
second.start();
third.start();
stop=false;
}
public void halt()
{
stop=true;
}
}
_________________________________________________________________________
24
Java Technology M.Sc IT Part II
___________________________________________________________________________
Output:
_________________________________________________________________________
25
Java Technology M.Sc IT Part II
___________________________________________________________________________
Practical 03-B
Problem Statement:
Write a program for bouncing ball. Each ball should be displayed with a different color.
Description:
JFrame:
An extended version of java.awt.Frame that adds support for the JFC/Swing
component architecture. The JFrame class is slightly incompatible with Frame. Like all other
JFC/Swing top-level containers, a JFrame contains a JRootPane as its only child. The content
pane provided by the root pane should, as a rule, contain all the non-menu components
displayed by the JFrame. This is different from the AWT Frame case. Unlike a Frame, a
JFrame has some notion of how to respond when the user attempts to close the window. The
default behavior is to simply hide the JFrame when the user closes the window.
Container:
A generic Abstract Window Toolkit(AWT) container object is a component that can
contain other AWT components.Components added to a container are tracked in a list. The
order of the list will define the components' front-to-back stacking order within the container.
If no index is specified when adding a component to a container, it will be added to the end of
the list .
_________________________________________________________________________
26
Java Technology M.Sc IT Part II
___________________________________________________________________________
Source Code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
/**
* This JFrame subclass is a simple "paint" application.
**/
public class DrawingPane extends JFrame
{
/**
* This constructor creates the GUI for this application.
**/
public DrawingPane()
{
super("Multiple Bouncing Balls - Thread based"); // Call superclass
constructor and set window title
//LookAndFeelPrefs.setPreferredLookAndFeel(ScribbleApp.class);
_________________________________________________________________________
27
Java Technology M.Sc IT Part II
___________________________________________________________________________
DrawingPane refDrawingPane = new DrawingPane();
}
class BouncingBallPane extends JComponent implements Runnable
{
int x, y, r; // Position and radius of the circle
int dx, dy; // Trajectory of circle
int x1, y1; // Position and radius of the circle
int dx1, dy1; // Trajectory of circle
int x2, y2; // Position and radius of the circle
int dx2, dy2; // Trajectory of circle
Thread refCurrentThread;
int ballNumber;
boolean pleaseStop; // A flag to ask the thread to stop
public BouncingBallPane()
{
setPreferredSize(new Dimension(450,200)); // We need a default size
ballNumber = 0;
}
_________________________________________________________________________
28
Java Technology M.Sc IT Part II
___________________________________________________________________________
// Let the superclass do its painting first
super.paintComponent(g);
// Make a copy of the Graphics context so we can modify it
// We cast it at the same time so we can use Java2D graphics
Graphics2D g2 = (Graphics2D) (g.create());
g.setColor(Color.red);
g.fillOval(x-r, y-r, r*2, r*2);
g.setColor(Color.green);
g.fillOval(x1-r, y1-r, r*2, r*2);
g.setColor(Color.blue);
g.fillOval(x2-r, y2-r, r*2, r*2);
//g.drawString(refCurrentThread.getName(), getWidth()/2,
getHeight()/2);
}
/**
* This method moves (and bounces) the circle and then requests a redraw.
* The animator thread calls this method periodically.
**/
public void animate()
{
// Bounce if we've hit an edge.
switch(ballNumber)
{
case 1:
if ((x - r + dx < 0) || (x + r + dx > getWidth()))
dx = -dx;
case 2:
if ((x1 - r + dx1 < 0) || (x1 + r + dx1 > getWidth()))
dx1 = -dx1;
_________________________________________________________________________
29
Java Technology M.Sc IT Part II
___________________________________________________________________________
// Move the second ball.
x1 += dx1; y1 += dy1;
break;
case 3:
if ((x2 - r + dx2 < 0) || (x2 + r + dx2 > getWidth()))
dx2 = -dx2;
}//end of switch
// Ask the browser to call our paint() method to draw the circle
// at its new position.
repaint();
}
/**
* This method is from the Runnable interface. It is the body of the
* thread that performs the animation. The thread itself is created
* and started in the start() method.
**/
animate();
try
{
Thread.sleep(30);
} // Wait 'n' milliseconds
_________________________________________________________________________
31
Java Technology M.Sc IT Part II
___________________________________________________________________________
Output:
_________________________________________________________________________
32
Java Technology M.Sc IT Part II
___________________________________________________________________________
Practical 04
Problem Statement:
Implement user-defined exception. Create throw and catch user-defined exception and handle
runtime exception.
Description:
InputStreamReader:
It extends from Reader class. An InputStreamReader is a bridge from byte streams to
character streams: It reads bytes and decodes them into characters using a specified charset.
Each invocation of one of an InputStreamReader's read() methods may cause one or more
bytes to be read from the underlying byte-input stream. For top efficiency, consider wrapping
an InputStreamReader within a BufferedReader. For example:
BufferedReader in= new BufferedReader(new InputStreamReader(System.in));
Dimension class:
The Dimension class encapsulates the width and height of a component (in integer
precision) in a single object. The class is associated with certain properties of components.
Several methods defined by the Component class and the LayoutManager interface return a
Dimension object.
_________________________________________________________________________
33
Java Technology M.Sc IT Part II
___________________________________________________________________________
Source Code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JFrame;
import java.util.*;
class demo
{
private int x,y;
void div() throws ArithmeticException
{
if(y==0)
{
throw new ArithmeticException("Divide by zero");
}
int z=x/y;
System.out.println("The division is:"+z);
}
void call(int m,int n)
{
try
{
x=m;y=n;div();
}
catch(ArithmeticException e)
{
System.out.println("Error:"+e);
}
}
}
class excep
{
public static void main(String args[])
{
try
{
int a=Integer.parseInt(args[0]);
int b=Integer.parseInt(args[1]);
demo d=new demo();
d.call(a,b);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Error:Command Line arguments not found");
}
}
}
_________________________________________________________________________
34
Java Technology M.Sc IT Part II
___________________________________________________________________________
Output:
_________________________________________________________________________
35
Java Technology M.Sc IT Part II
___________________________________________________________________________
Practical 05-A
Write a program for File Handling
Problem Statement:
Description:
FileInputStream:
A FileInputStream obtains input bytes from a file in a file system. What files are
available depends on the host environment.FileInputStream is meant for reading streams of
raw bytes such as image data. For reading streams of characters, consider using FileReader.
FileOutputStream:
A file output stream is an output stream for writing data to a File or to a FileDescriptor.
Whether or not a file is available or may be created depends upon the underlying platform.
Some platforms, in particular, allow a file to be opened for writing by only one
FileOutputStream (or other file-writing object) at a time. In such situations the constructors in
this class will fail if the file involved is already open.
FileOutputStream is meant for writing streams of raw bytes such as image data. For writing
streams of characters, consider using FileWriter.
read():
Reads a byte of data from this input stream. This method blocks if no input is yet
available.
_________________________________________________________________________
36
Java Technology M.Sc IT Part II
___________________________________________________________________________
Source Code:
import java.io.*;
class CopyFile5a
{
public static void main(String args[]) throws IOException
{
int i;
FileInputStream fin;
FileOutputStream fout;
try
{
try{
fin=new FileInputStream(args[0]);
}
catch(FileNotFoundException e){
System.out.println("Input file not found");return;
}
try{
fout=new FileOutputStream(args[1]);
}
catch(FileNotFoundException e){
System.out.println("Output File file not found");return;
}
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndex OutOf Bounds");return;
}
try
{
do
{
i=fin.read();
if(i!=-1)
{
fout.write((char)i);
}
}while(i!=-1);
}catch(IOException e){}
System.out.println("\nFile Copied!\nCopied File name is f2.txt");
fin.close();
fout.close();
}
}
_________________________________________________________________________
37
Java Technology M.Sc IT Part II
___________________________________________________________________________
Output:
Input File:
So she went into the garden to cut a cabbage-leaf, to make an apple-pie; and at the same time a
great she-bear, coming up the street, pops its head into the
shop. 'What! no soap?' So he died, and she very imprudently married the barber; and there
were present the Picninnies, and the Joblillies, and the Garyalies, and the grand Panjandrum
himself, with the little round button at top, and they all fell to playing the game of catch as
catch can, till the gun powder ran out at the heels of their boots.
Output File:
So she went into the garden to cut a cabbage-leaf, to make an apple-pie; and at the same time a
great she-bear, coming up the street, pops its head into the
shop. 'What! no soap?' So he died, and she very imprudently married the barber; and there
were present the Picninnies, and the Joblillies, and the Garyalies, and the grand Panjandrum
himself, with the little round button at top, and they all fell to playing the game of catch as
catch can, till the gun powder ran out at the heels of their boots.
_________________________________________________________________________
38
Java Technology M.Sc IT Part II
___________________________________________________________________________
Practical 05-B
Problem Statement:
Implement Caeser Cipher – Convert the text from an input file to cipher text. The cipher text
shifts all the alphabets by an amount. For e.g. if the amount is 5 then ‘a’ will be ‘f’, ‘b’ will
become ‘g’ and so on.
Description:
FileNotFoundException:
Signals that an attempt to open the file denoted by a specified pathname has failed.This
exception will be thrown by the FileInputStream, FileOutputStream, and RandomAccessFile
constructors when a file with the specified pathname does not exist. It will also be thrown by
these constructors if the file does exist but for some reason is inaccessible, for example when
an attempt is made to open a read-only file for writing.
IOException:
Signals that an I/O exception of some sort has occurred. This class is the general class
of exceptions produced by failed or interrupted I/O operations.
ArrayIndexOutOfBoundsException:
Thrown to indicate that an array has been accessed with an illegal index. The index is
either negative or greater than or equal to the size of the array.
_________________________________________________________________________
39
Java Technology M.Sc IT Part II
___________________________________________________________________________
Source Code:
import java.io.*;
public class Copy
{
int c, count = 0;
public void copyFile(File inputFile, File outputFile);
{
try
{
FileReader in = new FileReader(inputFile);
FileWriter out = new FileWriter(outputFile);
while ((c = in.read()) != -1)
{
++count;
out.write(c);
}
in.close();
out.close();
}
catch(IOException e) {}
}
public void cipherFile(File inputFile)
{
try
{
FileReader in = new FileReader(inputFile);
FileWriter out = new FileWriter("CaeserCipher.txt");
for(int i = 1; i <= count; i++)
{
c = in.read();
c = c + 5;
out.write(c);
}
in.close();
out.close();
}
catch(IOException e) {}
}
public void plainFile()
{
try
{
FileReader in = new FileReader("CaeserCipher.txt");
FileWriter out = new FileWriter("CaeserPlain.txt");
for(int i = 1; i <= count; i++)
{
_________________________________________________________________________
40
Java Technology M.Sc IT Part II
___________________________________________________________________________
c = in.read();
c = c - 5;
out.write(c);
}
in.close();
out.close();
System.out.println("File Converted to Cipher Text");
}
catch(IOException e) {}
}
public static void main(String[] args) throws IOException
{
Copy refCopy = new Copy();
File inputFile = new File(args[0]); //"farrago.txt");
File outputFile = new File(args[1]); //"outagain.txt");
refCopy.copyFile(inputFile, outputFile);
refCopy.cipherFile(inputFile);
refCopy.plainFile();
}
}
_________________________________________________________________________
41
Java Technology M.Sc IT Part II
___________________________________________________________________________
Output:
So she went into the garden to cut a cabbage-leaf, to make an apple-pie; and at the same time a
great she-bear, coming up the street, pops its head into the
shop. 'What! no soap?' So he died, and she very imprudently married the barber; and there
were present the Picninnies, and the Joblillies, and the Garyalies, and the grand Panjandrum
himself, with the little round button at top, and they all fell to playing the game of catch as
catch can, till the gun powder ran out at the heels of their boots.
Ouput File:
Xt%xmj%|jsy%nsyt%ymj%lfwijs%yt%hzy%f%hfggflj2qjfk1%yt¤rfpj%fs%fuuqj2unj@%fsi
%fy%ymj%xfrj%ynrj%f%lwjfy¤xmj2gjfw1%htrnsl%zu%ymj%xywjjy1%utux%nyx%mjfi
%nsyt%ymj¤xmtu3%,\mfy&%st%xtfuD,%Xt%mj%inji1%fsi%xmj%{jw~¤nruwzijsyq~
%rfwwnji%ymj%gfwgjw@%fsi%ymjwj%|jwj¤uwjxjsy%ymj%Unhsnssnjx1%fsi%ymj
%Otgqnqqnjx1%fsi%ymj¤Lfw~fqnjx1%fsi%ymj%lwfsi%Ufsofsiwzr%mnrxjqk1%|nym
%ymj¤qnyyqj%wtzsi%gzyyts%fy%ytu1%fsi%ymj~%fqq%kjqq%yt%uqf~nsl¤ymj%lfrj%tk
%hfyhm%fx%hfyhm%hfs1%ynqq%ymj%lzs%ut|ijw%wfs¤tzy%fy%ymj%mjjqx%tk%ymjnw
%gttyx3¤¤Xfrzjq%Kttyj%6<7526<<<¤
_________________________________________________________________________
42
Java Technology M.Sc IT Part II
___________________________________________________________________________
Practical 06
Problem Statement:
Description:
java.lang package:
Provides classes that are fundamental to the design of the Java programming language.
The most important classes are Object, which is the root of the class hierarchy, and Class,
instances of which represent classes at run time.
Runtime:
Every Java application has a single instance of class Runtime that allows the
application to interface with the environment in which the application is running. The current
runtime can be obtained from the getRuntime method.An application cannot create its own
instance of this class.
JFileChooser:
JFileChooser provides a simple mechanism for the user to choose a file.
_________________________________________________________________________
43
Java Technology M.Sc IT Part II
___________________________________________________________________________
Source Code:
Code for login form
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
passwordField.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
JPasswordField input = (JPasswordField)e.getSource();
char[] password = input.getPassword();
if (isPasswordCorrect(password))
{
new ComboProgram();
f.setVisible(false);
}
else
{
JOptionPane.showMessageDialog(f,"Invalid password. Try
again.","ErrorMessage",JOptionPane.ERROR_MESSAGE);
passwordField.setText("");
}
}
});
f.getContentPane().add(label, BorderLayout.CENTER);
f.getContentPane().add(passwordField, BorderLayout.CENTER);
f.getContentPane().setLayout(null);
_________________________________________________________________________
44
Java Technology M.Sc IT Part II
___________________________________________________________________________
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
f.setVisible(true);
f.setSize(400,100);
f.setResizable(false);
f.setLocation(300,250);
f.validate();
f.repaint();
}
import java.awt.FlowLayout;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.Color;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
import javax.swing.JLabel;
import javax.swing.JFrame;
_________________________________________________________________________
45
Java Technology M.Sc IT Part II
___________________________________________________________________________
import javax.swing.JComboBox;
import javax.swing.ImageIcon;
ComboProgram()
{
frmShow = new JFrame("ComboBox Demo");
setVisible(true);
setLocation(300,250);
contentPane.add(jc);
// Create label
jl = new JLabel(new ImageIcon("france.gif"));
contentPane.add(jl);
setTitle("Draw Objects");
pack();
}
if(s == "Line")
{
g.drawLine(150,150,400,400);
}
if(s == "Rectangles")
{
g.drawRect(100,100,400,400);
}
if(s == "Circle")
{
g.drawOval(150,150,400,400);
}
if(s == "Ellipse")
{
g.drawOval(150,150,500,400);
}
}
_________________________________________________________________________
47
Java Technology M.Sc IT Part II
___________________________________________________________________________
Output:
_________________________________________________________________________
48
Java Technology M.Sc IT Part II
___________________________________________________________________________
Practical 07-A
Swing Application
Problem Statement:
Write swings program for creating a single frame and display a text and change its font and
text color
Description:
JLabel:
A display area for a short text string or an image, or both. A label does not react to
input events. As a result, it cannot get the keyboard focus. A label can, however, display a
keyboard alternative as a convenience for a nearby component that has a keyboard alternative
but can't display it.A JLabel object can display either text, an image, or both. You can specify
where in the label's display area the label's contents are aligned by setting the vertical and
horizontal alignment. By default, labels are vertically centered in their display area. Text-only
labels are leading edge aligned, by default; image-only labels are horizontally centered, by
default.
JList:
A component that allows the user to select one or more objects from a list. A separate
model, ListModel, represents the contents of the list. It's easy to display an array or vector of
objects, using a JList constructor that builds a ListModel instance for you.
Font:
The Font class represents fonts, which are used to render text in a visible way. A font
provides the information needed to map sequences of characters to sequences of glyphs and to
render sequences of glyphs on Graphics and Component objects.
_________________________________________________________________________
49
Java Technology M.Sc IT Part II
___________________________________________________________________________
Source Code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
p1=new JPanel();
p1.setLayout(new FlowLayout());
p2=new JPanel();
p2.setLayout(new FlowLayout());
p3=new JPanel();
p3.setLayout(new FlowLayout());
p1.add(lblStr);
p2.add(jlName);
p2.add(jlColor);
//p2.setBorder(BorderFactory.createTitledBorder(BorderFactory.
createEtchedBorder(),"Select"));
Change=new JButton("Change");
p3.add(Change);
Change.addActionListener(this);
Exit=new JButton("Exit");
p3.add(Exit);
Exit.addActionListener(this);
refCon.add(p1);
refCon.add(p2);
_________________________________________________________________________
50
Java Technology M.Sc IT Part II
___________________________________________________________________________
refCon.add(p3);
setVisible(true);
pack();
_________________________________________________________________________
52
Java Technology M.Sc IT Part II
___________________________________________________________________________
if(jlName.getSelectedIndex()==2 && jlColor.getSelectedIndex()==2)
{
Font font=new Font("Monospaced",Font.BOLD|Font.ITALIC,15);
lblStr.setFont(font);
lblStr.setForeground(Color.cyan);
}
}
}
_________________________________________________________________________
53
Java Technology M.Sc IT Part II
___________________________________________________________________________
Output:
_________________________________________________________________________
54
Java Technology M.Sc IT Part II
___________________________________________________________________________
Practical 07-B
Problem Statement:
Description:
JButton:
An implementation of a "push" button.
JPanel:
JPanel is a generic lightweight container.
ImageIcon:
An implementation of the Icon interface that paints Icons from Images. Images that are
created from a URL, filename or byte array are preloaded using MediaTracker to monitor the
loaded state of the image.
getContentPane():
A Container that manages the contentPane and in some cases a menu bar. The
layeredPane can be used by descendants that want to add a child to the RootPaneContainer that
isn't layout managed. For example an internal dialog or a drag and drop effect component.
_________________________________________________________________________
55
Java Technology M.Sc IT Part II
___________________________________________________________________________
Source Code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
ImageViewer()
{
String str[]={"Geen baby","White baby","Blue baby"};
jl1=new JList(str);
ii1=new ImageIcon("1.jpg");
ii2=new ImageIcon("2.jpg");
ii3=new ImageIcon("3.jpg");
lblImage1=new JLabel();
refLabel2 = new JLabel("Select to view Imagies of Babies", JLabel.LEFT);
show=new JButton("Show");
}
public void display()
{
setTitle("Image Viewer");
Container refCon=getContentPane();
refCon.setLayout(new FlowLayout());
refCon.add(refLabel2);
refCon.add(jl1);
refCon.add(show);
refCon.add(lblImage1);
show.addActionListener(this);
setVisible(true);
pack();
_________________________________________________________________________
57
Java Technology M.Sc IT Part II
___________________________________________________________________________
Output:
_________________________________________________________________________
58
Java Technology M.Sc IT Part II
___________________________________________________________________________
Practical 07-C
Problem Statement:
Create a data entry form to store student information and display it on other frame
Description:
JTabbedPane:
A component that lets the user switch between a group of components by clicking
on a tab with a given title and/or icon. Tabs/components are added to a TabbedPane object by
using the addTab and insertTab methods. A tab is represented by an index corresponding to the
position it was added in, where the first tab has an index equal to 0 and the last tab has an index
equal to the tab count minus 1.
JTextField:
JTextField is a lightweight component that allows the editing of a single line of
text. TextField is intended to be source-compatible with java.awt.TextField where it is
reasonable to do so. This component has capabilities not found in the java.awt.TextField class.
The superclass should be consulted for additional capabilities.JTextField has a method to
establish the string used as the command string for the action event that gets fired. The
java.awt.TextField used the text of the field as the command string for the ActionEvent.
JTextField will use the command string set with the setActionCommand method if not null,
otherwise it will use the text of the field as a compatibility with java.awt.TextField.
JRadioButton:
An implementation of a radio button -- an item that can be selected or deselected,
and which displays its state to the user. Used with a ButtonGroup object to create a group of
buttons in which only one button at a time can be selected. (Create a ButtonGroup object and
use its add method to include the JRadioButton objects in the group.)
_________________________________________________________________________
59
Java Technology M.Sc IT Part II
___________________________________________________________________________
Source Code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java .sql.*;
import java.util.Vector;
setTitle("Student Records");
Container refCon=getContentPane();
refCon.setLayout(new BorderLayout());
refCon.add(lblTitle,BorderLayout.NORTH);
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection c= DriverManager.getConnection
("jdbc:odbc:StudInfo");
Statement s=c.createStatement();
String strQuery="select * from StudentInfo";
ResultSet rs=s.executeQuery(strQuery);
ResultSetMetaData rsmd=rs.getMetaData();
refCol = new Vector();
refData = new Vector();
_________________________________________________________________________
60
Java Technology M.Sc IT Part II
___________________________________________________________________________
while(rs.next())
{
refRow=new Vector();
for(int i=1 ; i<=rsmd.getColumnCount() ; i++)
{
refRow.add(rs.getString(i));
}
refData.add(refRow);
rs.close();
s.close();
c.close();
}
catch(Exception e)
{
System.out.println("Exception Occured .................." +e);
}
refTable=new JTable(refData,refCol);
System.out.println(refCol);
refCon.add(refTable,BorderLayout.CENTER);
setVisible(true);
pack();
}
}
_________________________________________________________________________
61
Java Technology M.Sc IT Part II
___________________________________________________________________________
Output:
_________________________________________________________________________
62
Java Technology M.Sc IT Part II
___________________________________________________________________________
_________________________________________________________________________
63
Java Technology M.Sc IT Part II
___________________________________________________________________________
Practical 08
Problem Statement:
Description:
GraphicsEnviroment:
The GraphicsEnvironment class describes the collection of GraphicsDevice
objects and Font objects available to a Java(tm) application on a particular platform. The
resources in this GraphicsEnvironment might be local or on a remote machine. GraphicsDevice
objects can be screens, printers or image buffers and are the destination of Graphics2D
drawing methods. Each GraphicsDevice has a number of GraphicsConfiguration objects
associated with it. These objects specify the different configurations in which the
GraphicsDevice can be used.
javax.swing.text.StyledEditorKit:
This is the set of things needed by a text component to be a reasonably
functioning editor for some type of text document. This implementation provides a default
implementation which treats text as styled text and provides a minimal set of actions for
editing styled text.
_________________________________________________________________________
64
Java Technology M.Sc IT Part II
___________________________________________________________________________
Source Code:
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.event.KeyEvent;
import java.io.File.*;
import java.io.*;
import java.util.*;
import javax.swing.text.StyledEditorKit.*;
import javax.swing.event.*;
import javax.swing.undo.*;
toolbar.addSeparator();
Toggle_Bold=new JToggleButton(new StyledEditorKit.BoldAction());
Toggle_Bold.setText("Bold");
//Toggle_Bold.setIcon(new ImageIcon("icons/bold.gif"));
toolbar.add(Toggle_Bold);
Toggle_Italic=new JToggleButton(new StyledEditorKit.ItalicAction());
Toggle_Italic.setText("Italic");
//Toggle_Italic.setIcon(new ImageIcon("icons/italic.gif"));
toolbar.add(Toggle_Italic);
Toggle_Underline=new JToggleButton(new
StyledEditorKit.UnderlineAction());
Toggle_Underline.setText("Underline");
//Toggle_Underline.setIcon(new ImageIcon("icons/underline.gif"));
toolbar.add(Toggle_Underline);
toolbar.addSeparator();
File.setMnemonic('F');
Edit.setMnemonic(KeyEvent.VK_E);
menuBar.add(File);
menuBar.add(Edit);
File_Open=new JMenuItem("Open");
File_Open.setMnemonic(KeyEvent.VK_O);
File.add(File_Open);
File_Close=new JMenuItem("Close",new ImageIcon("icons/close.gif"));
File_Close.setMnemonic(KeyEvent.VK_C);
File.add(File_Close);
File.addSeparator();
File_Exit=new JMenuItem("Exit");
File_Exit.setMnemonic(KeyEvent.VK_X);
File.add(File_Exit);
//OPEN FILE
File_Open.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Open();
}
});
}
});
//FONT COLOR
Format_FontColor.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
FontColor();
}
});
Color color=StyleConstants.getForeground(a);
if(color!=Button_Color.getBackground())
Button_Color.setBackground(color);
}
});
while((str=br.readLine())!=null)
text.getDocument().insertString(text.getCaretPosition(), str+"\n", null);
}catch(Exception ex)
{}
SetEnable_JTextPane();
}
if(confirm == JOptionPane.YES_OPTION)
{
//Save();
text.selectAll();
try
{
text.getDocument().remove(text.getSelectionStart(),text.getSelectionEnd());
}
catch(Exception ex)
{}
_________________________________________________________________________
70
Java Technology M.Sc IT Part II
___________________________________________________________________________
text.setBackground(Color.gray);
text.setEnabled(false);
}
else if(confirm == JOptionPane.CANCEL_OPTION)
{
return;
}
else
{
text.selectAll();
try
{
text.getDocument().remove(text.getSelectionStart(),text.getSelectionEnd());
}
catch(Exception ex)
{}
text.setBackground(Color.gray);
text.setEnabled(false);
}
_________________________________________________________________________
71
Java Technology M.Sc IT Part II
___________________________________________________________________________
}*/
Toggle_Bold.setEnabled(false);
Toggle_Italic.setEnabled(false);
Toggle_Underline.setEnabled(false);
Button_Color.setEnabled(false);
Format_FontColor.setEnabled(false);
File_Close.setEnabled(false);
}
*/
/////////// FUNCTION FOR FONT COLOR ///////////
private void FontColor()
{
Color color = JColorChooser.showDialog(
Editor.this,
"Choose Text Color",
Button_Color.getBackground());
if(color!=null)
{
Button_Color.setBackground(color);
Color fontColor=Button_Color.getBackground();
MutableAttributeSet attr=new SimpleAttributeSet();
StyleConstants.setForeground(attr,fontColor);
text.setCharacterAttributes(attr,false);
}
text.requestFocus();
}
String look="com.sun.java.swing.plaf.windows.WindowsLookAndFeel";
try
{
UIManager.setLookAndFeel(look);
}
catch (Exception exc)
{
System.err.println("Error loading L&F: " + exc);
_________________________________________________________________________
72
Java Technology M.Sc IT Part II
___________________________________________________________________________
}
Editor mainWindow = new Editor();
mainWindow.setVisible(true);
}
}
_________________________________________________________________________
73
Java Technology M.Sc IT Part II
___________________________________________________________________________
Output:
_________________________________________________________________________
74
Java Technology M.Sc IT Part II
___________________________________________________________________________
_________________________________________________________________________
75
Java Technology M.Sc IT Part II
___________________________________________________________________________
Practical 09-A
Write a JDBC (Java Database Connectivity) application using frames
Problem Statement:
Description:
java.sql package:
Provides the API for accessing and processing data stored in a data source (usually a
relational database) using the JavaTM programming language.
JTable:
The JTable is used to display and edit regular two-dimensional tables of cells. The
JTable has many facilities that make it possible to customize its rendering and editing but
provides defaults for these features so that simple tables can be set up easily.
Connection:
A connection (session) with a specific database. SQL statements are executed and
results are returned within the context of a connection.A Connection object's database is able to
provide information describing its tables, its supported SQL grammar, its stored procedures,
the capabilities of this connection, and so on. This information is obtained with the
getMetaData method.
_________________________________________________________________________
76
Java Technology M.Sc IT Part II
___________________________________________________________________________
Source Code:
import java.sql.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
JTable reftable;
String col[],rows[][];
int n;
void UI()
{
reftable=new JTable(rows,col);
Container c=getContentPane();
c.add(reftable);
setTitle("Bank Database");
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
setVisible(true);
}
void get_data()
{
try
{
n=0;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:Bank");
int columns=rsmd.getColumnCount();
col=new String[columns];
_________________________________________________________________________
77
Java Technology M.Sc IT Part II
___________________________________________________________________________
for(int i=1;i<=columns;i++)
{
col[i-1]=rsmd.getColumnName(i);
System.out.println(rsmd.getColumnName(i));
}
while(rs.next())
n++;
rs.beforeFirst();
rows=new String[n][5];
int x=0;
while(rs.next())
{
for(int i=1,y=0;i<=rsmd.getColumnCount();i++,y++)
{
rows[x][y]=rs.getString(i);
}
x++;
}
System.out.println(n);
System.out.println(rsmd.getColumnCount());
new bank();
}
catch(Exception e)
{
}
}
_________________________________________________________________________
78
Java Technology M.Sc IT Part II
___________________________________________________________________________
Output:
_________________________________________________________________________
79
Java Technology M.Sc IT Part II
___________________________________________________________________________
Practical 09-B
Problem Statement:
Description:
Integer.parseInt():
Parses the string argument as a signed decimal integer. The characters in the string
must all be decimal digits, except that the first character may be an ASCII minus sign '-'
('\u002D') to indicate a negative value. The resulting integer value is returned.
File:
An abstract representation of file and directory pathnames.User interfaces and
operating systems use system-dependent pathname strings to name files and directories. This
class presents an abstract, system-independent view of hierarchical pathnames.
PreparedStatement:
An object that represents a precompiled SQL statement.A SQL statement is
precompiled and stored in a PreparedStatement object. This object can then be used to
efficiently execute this statement multiple times.
_________________________________________________________________________
80
Java Technology M.Sc IT Part II
___________________________________________________________________________
Source Code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.sql.*;
import java.io.*;
getImg()
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:ImageDSN","scott","tiger");
}
catch(Exception e)
{
}
Container c=getContentPane();
c.setLayout(new BorderLayout());
reflabelcourse=new JLabel("Course");
reflabelpic=new JLabel("Image");
reflabelimage=new JLabel();
reftextroll=new JTextField();
reftextname=new JTextField();
reftextcourse=new JTextField();
refok=new JButton("OK");
refretrieve=new JButton("Retrieve");
refexit=new JButton("Exit");
_________________________________________________________________________
81
Java Technology M.Sc IT Part II
___________________________________________________________________________
refbutton=new JPanel();
reftext.add(reflabelroll);
reftext.add(reftextroll);
reftext.add(reflabelname);
reftext.add(reftextname);
reftext.add(reflabelcourse);
reftext.add(reftextcourse);
reftext.add(reflabelpic);
reftext.add(reflabelimage);
refbutton.add(refok);
refbutton.add(refretrieve);
refbutton.add(refexit);
c.add(reftext,BorderLayout.NORTH);
c.add(refbutton,BorderLayout.SOUTH);
refok.addActionListener(this);
refretrieve.addActionListener(this);
refexit.addActionListener(this);
setTitle("Student Application");
//setSize(300,200);
//setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
setVisible(true);
}
void insertdata()
{
try
{
int roll=Integer.parseInt(reftextroll.getText());
String name=reftextname.getText();
String course=reftextcourse.getText();
ps.setInt(1,roll);
ps.setString(2,name);
ps.setString(3,course);
ps.setBinaryStream(4,reffis,(int)reffile.length());
ps.executeUpdate();
JOptionPane.showMessageDialog(null,"Data
Inserted","Information",JOptionPane.INFORMATION_MESSAGE);
reftextroll.setText("");
reftextname.setText("");
reftextcourse.setText("");
}
catch(Exception e)
{
System.out.println(e);
}
}
void retrievedata()
{
try
{
byte imgByte[]=new byte[2048];
Statement s=con.createStatement();
String refQuery="select * from imageTable where RollNo=2";
_________________________________________________________________________
83
Java Technology M.Sc IT Part II
___________________________________________________________________________
ResultSet rs=s.executeQuery(refQuery);
System.out.println("conn made");
while(rs.next())
{
reftextroll.setText(rs.getString("rollno"));
reftextname.setText(rs.getString("Name"));
reftextcourse.setText(rs.getString("Course"));
imgByte=rs.getBytes("Image");
}
ImageIcon ai=new ImageIcon(imgByte);
reflabelimage.setIcon(ai);
}
catch(Exception e)
{
}
Output:
_________________________________________________________________________
84
Java Technology M.Sc IT Part II
___________________________________________________________________________
Practical 10
_________________________________________________________________________
85
Java Technology M.Sc IT Part II
___________________________________________________________________________
Problem Statement:
Description:
DriverManager:
The basic service for managing a set of JDBC drivers. As part of its
initialization, the DriverManager class will attempt to load the driver classes referenced in the
"jdbc.drivers" system property. This allows a user to customize the JDBC Drivers used by their
applications.
Statement:
The object used for executing a static SQL statement and returning the results it
produces.By default, only one ResultSet object per Statement object can be open at the same
time. Therefore, if the reading of one ResultSet object is interleaved with the reading of
another, each must have been generated by different Statement objects. All execution methods
in the Statement interface implicitly close a statment's current ResultSet object if an open one
exists.
ResultSet:
A table of data representing a database result set, which is usually generated by
executing a statement that queries the database.A ResultSet object maintains a cursor pointing
to its current row of data. Initially the cursor is positioned before the first row. The next
method moves the cursor to the next row, and because it returns false when there are no more
rows in the ResultSet object, it can be used in a while loop to iterate through the result set.
Source Code:
_________________________________________________________________________
86
Java Technology M.Sc IT Part II
___________________________________________________________________________
<!-- Create a simple java server page (JSP) for web application -->
<%@page import="java.sql.*"%>
<%!
String firstname_str, middlename_str, lastname_str, class_str, age_str, rollno_str;
Connection c;
Statement s;
ResultSet rs;
%>
<head>
<title>Database Connection</title>
</head>
<body>
<p align="center"><b><font size="5">Student Database</font></b></p>
<table border="1" cellpadding="0" cellspacing="0" style="border-collapse: collapse"
bordercolor="#111111" width="100%" id="AutoNumber1">
<tr>
<td width="16%" align="center"><b>First Name</b></td>
<td width="16%" align="center"><b>Middle Name</b></td>
<td width="17%" align="center"><b>Last Name</b></td>
<td width="17%" align="center"><b>Class</b></td>
<td width="17%" align="center"><b>Age</b></td>
<td width="17%" align="center"><b>Roll No.</b></td>
</tr>
<%
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
c = DriverManager.getConnection("jdbc:odbc:Students");
s = c.createStatement();
rs = s.executeQuery("Select * from StudentTable order by FirstName");
while(rs.next())
{
firstname_str = rs.getString(1);
middlename_str = rs.getString(2);
lastname_str = rs.getString(3);
class_str = rs.getString(4);
age_str = rs.getString(5);
rollno_str = rs.getString(6);
%>
<tr>
<td width="16%" align="center"><%=firstname_str%></td>
<td width="16%" align="center"><%=middlename_str%></td>
<td width="17%" align="center"><%=lastname_str%></td>
<td width="17%" align="center"><%=class_str%></td>
<td width="17%" align="center"><%=age_str%></td>
<td width="17%" align="center"><%=rollno_str%></td>
</tr>
<%
}
_________________________________________________________________________
87
Java Technology M.Sc IT Part II
___________________________________________________________________________
c.close();
}
catch(Exception e)
{}
%>
</table>
</body>
</html>
Output:
_________________________________________________________________________
88
Java Technology M.Sc IT Part II
___________________________________________________________________________
_________________________________________________________________________
89
Java Technology M.Sc IT Part II
___________________________________________________________________________
Practical 11
Problem Statement:
Description:
javax.servlet package:
The javax.servlet package contains a number of classes and interfaces that describe and
define the contracts between a servlet class and the runtime environment provided for an
instance of such a class by a conforming servlet container.
javax.servlet.http package:
The javax.servlet.http package contains a number of classes and interfaces that describe
and define the contracts between a servlet class running under the HTTP protocol and the
runtime environment provided for an instance of such a class by a conforming servlet
container.
_________________________________________________________________________
90
Java Technology M.Sc IT Part II
___________________________________________________________________________
Source Code:
login.html
HTML code:
<html>
</html>
Java code:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:TwoServletsDeptDatabase");
// String Query="insert into login Values(?,?,?)";
Statement st=con.createStatement();
PreparedStatement ps;
PrintWriter out=res.getWriter();
// ps=con.prepareStatement(Query);
a=(String)req.getParameter("Name");
b=(String)req.getParameter("Password");
}
out.println("</table>");
con.commit();
out.println("</body></html>");
}
else
{
out.println("<br> <br><b> <center>LOGIN
UNSUCCESSFULL</center> </b><br> <br>");
out.println("<center><a href =
http://localhost:8888/loginform.html> <b>Try Again</b> </a></center>");
}
con.close();
}
catch (Exception ae)
{
System.out.println(ae.getMessage());
}
}
}
_________________________________________________________________________
92
Java Technology M.Sc IT Part II
___________________________________________________________________________
Output:
_________________________________________________________________________
93
Java Technology M.Sc IT Part II
___________________________________________________________________________
_________________________________________________________________________
94
Java Technology M.Sc IT Part II
___________________________________________________________________________
Practical 12
Problem Statement:
Write a program to implement a Remote Procedure Call
Description:
java.rmi.Remote:
The Remote interface serves to identify interfaces whose methods may be invoked from
a non-local virtual machine. Any object that is a remote object must directly or indirectly
implement this interface. Only those methods specified in a "remote interface", an interface
that extends java.rmi.Remote are available remotely.
java.rmi package:
Provides the Remote Method Invocation package.
UnicastRemoteObject:
Used for exporting a remote object with JRMP and obtaining a stub that communicates
to the remote object.
_________________________________________________________________________
95
Java Technology M.Sc IT Part II
___________________________________________________________________________
Source Code:
processinterface.java
import java.rmi.Remote;
import java.rmi.RemoteException;
processimplement.java
import java.rmi.*;
import java.rmi.server.*;
import java.rmi.*;
import java.rmi.server.*;
System.out.println("Server Registered");
System.out.println("\nWaiting for Client........");
}
catch(Exception e)
{
}
}
}
processclient.java
import java.rmi.*;
import java.io.*;
System.out.println("\n**********************Welcome to World of
RMI*********************");
while(true)
{
System.out.println("\n\n1.Factorial\n2.Reverse\n3.Sum of
Digits");
System.out.print("\nPlease enter a option from the above
menu(Bye to exit):");
String choice=br.readLine();
if(choice.equalsIgnoreCase("bye"))
_________________________________________________________________________
97
Java Technology M.Sc IT Part II
___________________________________________________________________________
{
System.exit(0);
}
System.out.print("\nEnter a number:");
int num=Integer.parseInt(br.readLine());
if(choice.equals("1"))
System.out.println("\nThe Factorial of the number
is:"+pi.fact(num));
else if(choice.equals("2"))
System.out.println("\nThe Reverse of the number
is:"+pi.rev(num));
else if (choice.equals("3"))
System.out.println("\nThe Sum of digits of the number
is:"+pi.sum(num));
}
}
catch(Exception e)
{
}
}
}
_________________________________________________________________________
98
Java Technology M.Sc IT Part II
___________________________________________________________________________
Output:
_________________________________________________________________________
99