You are on page 1of 58

1.

Write a Program to print the “Hello World”

Program:
class Simple
{
public static void main(String args[])
{
System.out.println("Hello World");
}
}

Save the above file as Simple.java.

To compile:

javac Simple.java

2. Display the messages using print() & println()


methods.

class Demo
{
public static void main(String args[])
{
System.out.print("Hello ");
System.out.print("Java");
}
}

Output:
Hello Java
1
Java println() method
The println() method is similar to print() method except that it moves the
cursor to the next line after printing the result. It is used when you want the result
in two separate lines. It is called with "out" object. If we want the result in two
separate lines, then we should use the println() method.

Example
The following example, the println() method display the string in two separate
lines.

class Demo
{
public static void main(String args[])
{
System.out.println("Hello ");
System.out.println("Java");
}
}

Output:

Hello

Java

3. WAP to print the addition of two numbers using


command line arguments.

Program:
public class CommandLineArguments
{
public static void main(String[] args)
{
int a = Integer.parseInt(args[0]);
2
int b = Integer.parseInt(args[1]);
int sum = a + b;
System.out.println("Sum is: " + sum);
}
}

Run above program from command prompt


Compile:
javac CommandLineArguments.java

Run:
java CommandLineArguments 20 50

Output:

Sum is: 70

4. WAP to find the largest number among 3


numbers.

Program:
public class Largest
{
public static void main(String[] args)
{
int num1 = 10, num2 = 20, num3 = 7;
if( num1 >= num2 && num1 >= num3)
System.out.println(num1+" is the largest Number");
else if (num2 >= num1 && num2 >= num3)
System.out.println(num2+" is the largest Number");
else
System.out.println(num3+" is the largest Number");
}
}
3
Output:

20 is the largest Number

5. WAP to calculate the factorial of a given number.

Program:

import java.util.Scanner;
class FactorialExample
{
public static void main(String args[])
{
int i,fact=1, n;
Scanner s1=new Scanner(System.in);
System.out.print(“Enter a number :”);
n=s1.nextInt();

for(i=1;i<=n; i++)
{
fact=fact*i;
}
System.out.println("Factorial of "+n+" is: "+fact);
}
}

Output:

4
Enter a number : 5
Factorial of 5 is : 120

6. WAP to sort the array elements.


Program

import java.util.Arrays;
public class SortArrayExample1
{
public static void main(String[] args)
{
int [] array = new int [] {90, 23, 5, 109, 12, 22, 67, 34};
Arrays.sort(array);
System.out.println("Elements of array sorted in ascending order: ");
for (int i = 0; i < array.length; i++)
{
System.out.println(array[i]);
}
}
}

Output:
Array elements in ascending order:
5
12
22
23
34
67
90
5
109

7. WAP to print the multiplication of two matrices.

Program:
import java.util.Scanner;

public class Multiplication


{
public static void main(String[] args)
{
int i, j, k, sum=0;
int[][] matrixOne = new int[3][3];
int[][] matrixTwo = new int[3][3];
int[][] matrixThree = new int[3][3];
Scanner scan = new Scanner(System.in);
System.out.print("Enter Elements of First Matrix: ");
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
matrixOne[i][j] = scan.nextInt();
}
}
System.out.print("Enter Elements of Second Matrix: ");
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
matrixTwo[i][j] = scan.nextInt();
}
}
// multiplying the two matrices
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
6
sum = 0;
for(k=0; k<3; k++)
{
sum = sum + (matrixOne[i][k] * matrixTwo[k][j]);
}
matrixThree[i][j] = sum;
}
}
System.out.println("\nMultiplication of Two Matrices is:");
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
System.out.print(matrixThree[i][j]+ " ");
}
System.out.print("\n");
}
}
}

Output:
Enter elements of First Matrix:
1
2
3
4
5
6
7
8
9
Enter elements of Second Matrix:
1
2
1
2

7
4
6
7
2
5
Multiplication of two Matrices is :

26 16 28
56 40 64
86 64 100

8. WAP to demonstrate the Vector Class.

Program:
import java.util.*;
public class VectorExample1
{
public static void main(String args[])
{
Vector<String> vec = new Vector<String>(4);
vec.add("Tiger");
vec.add("Lion");
vec.add("Dog");
vec.add("Elephant");
System.out.println("Size is: "+vec.size());
System.out.println("Default capacity is: "+vec.capacity());
System.out.println("Vector element is: "+vec);
vec.addElement("Rat");
vec.addElement("Cat");
vec.addElement("Deer");
System.out.println("Size after addition: "+vec.size());
8
System.out.println("Capacity after addition is: "+vec.capacity());
System.out.println("Elements are: "+vec);
if(vec.contains("Tiger"))
{
System.out.println("Tiger is present at the index " +vec.indexOf("Tiger"));
}
else
{
System.out.println("Tiger is not present in the list.");
}
System.out.println("The first animal of the vector is = "+vec.firstElement());
System.out.println("The last animal of the vector is = "+vec.lastElement());
}
}

Output:
Size is: 4
Default capacity is: 4
Vector element is: [Tiger, Lion, Dog, Elephant]
Size after addition: 7
Capacity after addition is: 8
Elements are: [Tiger, Lion, Dog, Elephant, Rat, Cat, Deer]
Tiger is present at the index 0
The first animal of the vector is = Tiger
The last animal of the vector is = Deer

9
9. WAP to show the method overloading and
overriding.

Method Overloading: changing no. of arguments

class Adder
{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}
class TestOverloading1
{
public static void main(String[] args)
{
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}
}

Output:
22

33

Method Overloading: changing data type of arguments

class Adder
{
10
static int add(int a, int b)
{
return a+b;
}
static double add(double a, double b)
{
return a+b;
}
}
class TestOverloading2
{
public static void main(String[] args)
{
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}
}

Output:
22

24.9

Example:

class Bank
{
int getRateOfInterest()
{
return 0;
}
11
}
class SBI extends Bank
{
int getRateOfInterest()
{
return 8;
}
}
class ICICI extends Bank
{
int getRateOfInterest()
{
return 7;
}
}
class AXIS extends Bank
{
int getRateOfInterest()
{
return 9;
}
}

class Test2
{
public static void main(String args[])
{
SBI s=new SBI();
ICICI i=new ICICI();
AXIS a=new AXIS();
System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
12
System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
}
}

Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9

13
10. WAP to calculate the area of rectangle using
parameterized constructor.

Example:
import java.util.Scanner;

class Rectangle

int area;

Rectangle(int l, int w)

area = l * w;

void display()

System.out.println("Area of rectangle is: " + area);

class Test

public static void main(String args[])

int length, width;

Scanner sc = new Scanner(System.in);


14
System.out.print("Enter length of rectangle:");

length = sc.nextInt();

System.out.print("Enter width of rectangle:");

width = sc.nextInt();

Rectangle t = new Rectangle(length, width);

t.display();

Output:
Enter length of rectangle:12

Enter width of rectangle: 3

Area of rectangle is: 36

15
11: Write a program to create a package and store
class in this package.

Program:
Create a package named as Calculator and store Add class in this package –
package p1;
import java.util.*;
public class Add
{
int s;
public void sum()
{
System.out.print("Enter the first number: ");
Scanner scan=new Scanner(System.in);
int x=scan.nextInt();
System.out.print("Enter the second number: ");
Scanner scan1=new Scanner(System.in);
int y=scan1.nextInt();
s=x+y;
System.out.println("sum="+s);
}
}

How to compile java package


Syntax:
javac -d directory javafilename

16
For Example
javac -d . Sum.java

Add another class Sub in the same package


package p1;
import java.util.*;
public class Sub
{
int s;
public void minus()
{
System.out.print("Enter the first number: ");
Scanner scan=new Scanner(System.in);
int x=scan.nextInt();
System.out.print("Enter the second number: ");
Scanner scan1=new Scanner(System.in);
int y=scan1.nextInt();
s=x-y;
System.out.println("sub="+s);
}
}

Now, Compile this file again


Syntax:
javac -d directory javafilename

17
For example
javac -d . Sub.java

Calculator.java
import java.util.*;
import p1.Add;
import p2.Sub;
public class Calculator
{
public static void main(String args[])
{
System.out.print("Enter your choice: ");
Scanner scan=new Scanner(System.in);
int t=scan.nextInt();
switch(t)
{
case 1:
Add a=new Add();
a.sum();
break;
case 2:
Sub s=new Sub();
s.minus();
break;
default:
System.out.println(“Invalid Choice”);
}

18
}
}

Output:
Enter your choice: 1
Enter the first number: 20
Enter the second number: 10
Sum= 30

Enter your choice: 2


Enter the first number: 20
Enter the second number: 10
Sub= 10

19
12: Write a program to demonstrate the multithreading.

Program:
class A extends Thread
{
public void run()
{
for(int i=1; i<=5; i++)
{
System.out.println("From Thread A : "+i);
}
System.out.println("Exit from A");
}
}
class B extends Thread
{
public void run()
{
for(int j=1; j<=5; j++)
{
System.out.println("From Thread B : "+j);
}
System.out.println("Exit from B");
}
}
class C extends Thread

20
{
public void run()
{
for(int k=1; k<=5; k++)
{
System.out.println("From Thread C : "+k);
}
System.out.println("Exit from C");
}
}
class TestThread
{
public static void main(String arg[])
{
A a1=new A();
B b1=new B();
C c1=new C();
a1.start();
b1.start();
c1.start();
}
}

Output:

21
13: WAP to draw a Human Face using Applet.

Program:

import java.applet.*;
import java.awt.*;
public class Human_Face extends Applet
{
public void init()
{
setBackground(Color.white);
}
public void paint(Graphics g)
{

22
Color clr=new Color(255,179,86);
g.setColor(clr);
g.drawOval(100,100,250,300);
g.fillOval(100,100,250,300);
g.setColor(Color.black);
g.drawOval(160,185,40,25);
g.fillOval(160,185,40,25);
g.drawOval(250,185,40,25);
g.fillOval(250,185,40,25);
g.drawArc(160,170,35,10,0,180);
g.drawArc(250,170,35,10,0,180);
g.drawLine(210,265,210,275);
g.drawLine(240,265,240,275);
g.drawArc(210,275,30,10,0,-180);
g.drawArc(175,300,100,50,0,-180);
}
}
/*
<applet code = Human_Face.class width=500 height=500>
</applet>
*/

To execute the applet use the following commands:


javac Human_Face.java

appletviewer Human_Face.java

23
Output:

14: Write a program to show the IP address and host


name of your system.

Program
import java.net.*;
public class Demo
{
public static void main(String[] args)
{
Try
{
InetAddress my_address = InetAddress.getLocalHost();
System.out.println("The IP address is : " + my_address.getHostAddress());
System.out.println("The host name is : " + my_address.getHostName());

24
}
catch (UnknownHostException e)
{
System.out.println( "Couldn't find the local address.");
}
}
}

Output:

15: Write a program to design an interface of Login


Form using AWT.
Program:

LoginFormDemo.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.lang.Exception;
class CreateLoginForm extends JFrame implements ActionListener
{
25
JButton b1;
JPanel newPanel;
JLabel userLabel, passLabel;
final JTextField textField1, textField2;
CreateLoginForm()
{
userLabel = new JLabel();
userLabel.setText("Username");
textField1 = new JTextField(15);
passLabel = new JLabel();
passLabel.setText("Password");
textField2 = new JPasswordField(15);
b1 = new JButton("SUBMIT");
newPanel = new JPanel(new GridLayout(3, 1));
newPanel.add(userLabel);
newPanel.add(textField1);
newPanel.add(passLabel);
newPanel.add(textField2);
newPanel.add(b1);
add(newPanel, BorderLayout.CENTER);
b1.addActionListener(this);
setTitle("LOGIN FORM");
}
public void actionPerformed(ActionEvent ae)
{
String userValue = textField1.getText(); //get user entered username from th
e textField1 String passValue = textField2.getText();
26
if (userValue.equals("bca") && passValue.equals("123"))
{
NewPage page = new NewPage();
page.setVisible(true);
JLabel wel_label = new JLabel("Welcome: "+userValue);
page.getContentPane().add(wel_label);
}
Else
{
System.out.println("Please enter valid username and password");
}
}
}
//create the main class
class LoginFormDemo
{
//main() method start
public static void main(String arg[])
{
try
{
CreateLoginForm form = new CreateLoginForm();
form.setSize(300,100);
form.setVisible(true);
}
catch(Exception e)
{
27
JOptionPane.showMessageDialog(null, e.getMessage());
}
}
}
NewPage.java
//import required classes and packages
import javax.swing.*;
import java.awt.*;
class NewPage extends JFrame
{
NewPage()
{
setDefaultCloseOperation(javax.swing.
WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Welcome");
setSize(400, 200);
}
}

Output:
Javac CreateLoginForm.java
Java CreateLoginForm

28
16: Write a program to design an interface of
Calculator to perform basic arithmetic operations.

Aim:
To design an interface of Calculator to perform basic arithmetic operations

Program:
import java.awt.*;
import java.awt.event.*;
class Calculator extends Frame implements ActionListener
{
Button b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, bm, bd, bs, ba, be, bc;
TextField screen;
int n1 = 0, sign = 4;

Calculator()
{
b0 = new Button("0");
29
b1 = new Button("1");
b2 = new Button("2");
b3 = new Button("3");
b4 = new Button("4");
b5 = new Button("5");
b6 = new Button("6");
b7 = new Button("7");
b8 = new Button("8");
b9 = new Button("9");
bm = new Button("*");
bd = new Button("/");
bs = new Button("-");
ba = new Button("+");
be = new Button("=");
bc = new Button("Clear");
b7.setBounds(10,100,50,50);
b8.setBounds(60,100,50,50);
b9.setBounds(110,100,50,50);
bm.setBounds(160,100,50,50);
b4.setBounds(10,150,50,50);
b5.setBounds(60,150,50,50);
b6.setBounds(110,150,50,50);
bd.setBounds(160,150,50,50);
b1.setBounds(10,200,50,50);
b2.setBounds(60,200,50,50);
b3.setBounds(110,200,50,50);
bs.setBounds(160,200,50,50);
30
b0.setBounds(10,250,50,50);
be.setBounds(60,250,100,50);
ba.setBounds(160,250,50,50);
bc.setBounds(10,80,200,20);
bc.setBackground(Color.red);
be.setBackground(Color.blue);
screen = new TextField();
screen.setBounds(10,50,200,30);
add(b7);
add(b8);
add(b9);
add(bm);
add(b4);
add(b5);
add(b6);
add(bd);
add(b1);
add(b2);
add(b3);
add(bs);
add(b0);
add(be);
add(ba);
add(bc);
add(screen);
b0.addActionListener(this);
b1.addActionListener(this);
31
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
b5.addActionListener(this);
b6.addActionListener(this);
b7.addActionListener(this);
b8.addActionListener(this);
b9.addActionListener(this);
bd.addActionListener(this);
bm.addActionListener(this);
bs.addActionListener(this);
ba.addActionListener(this);
be.addActionListener(this);
bc.addActionListener(this);
setSize(220,310);
setLayout(null);
setVisible(true);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
dispose();
}
};
}
public void append(int a)
{
32
int c;
if(screen.getText().equals(""))
{
screen.setText(Integer.toString(a));
}

else
{
c = Integer.parseInt(screen.getText());
screen.setText(Integer.toString((c*10)+a));
}
}

public void actionPerformed(ActionEvent e)


{
int n2 = 1, res;
if(e.getSource()==b0)
{
append(0);
}
if(e.getSource()==b1)
{
append(1);
}
if(e.getSource()==b2)
{
append(2);

33
}
if(e.getSource()==b3)
{
append(3);
}
if(e.getSource()==b4)
{
append(4);
}

if(e.getSource()==b5)
{
append(5);
}
if(e.getSource()==b6)
{
append(6);
}
if(e.getSource()==b7)
{
append(7);
}
if(e.getSource()==b8)
{
append(8);
}
if(e.getSource()==b9)
34
{
append(9);
}
if(e.getSource()==be)
{

System.out.print(n1);
if(n1>0)
{
n2 = Integer.parseInt(screen.getText());
if(sign < 4)
{
switch(sign)
{
case 0:
screen.setText(Integer.toString(n1*n2));
break;
case 1:
screen.setText(Integer.toString(n1/n2));
break;
case 2:
screen.setText(Integer.toString(n1-n2));
break;
default:
screen.setText(Integer.toString(n1+n2));
break;
}
35
}
}
else
{
screen.setText("");
}
}
if(e.getSource()==bd || e.getSource()==bm || e.getSource()==bs ||
e.getSource()==ba || e.getSource()==bc)
{
if(screen.getText().equals(""))
{
screen.setText("");
}
else if(e.getSource()==bm)
{
n1 = Integer.parseInt(screen.getText());
System.out.print(n1);
screen.setText("");
sign = 0;
}
else if(e.getSource()==bd)
{
n1 = Integer.parseInt(screen.getText());
screen.setText("");
sign = 1;
}
36
else if(e.getSource()==bs)
{
n1 = Integer.parseInt(screen.getText());
screen.setText("");
sign = 2;
}
else if(e.getSource()==ba)
{
n1 = Integer.parseInt(screen.getText());
screen.setText("");
sign = 3;
}
else if(e.getSource()==bc)
{
screen.setText("");
}
}
}
public static void main(String[] args)
{
new Calculator();
}
}

Output:

37
17: Write a program to design a registration form in
HTML.
Program:
Registration Form
<Html>
<head>
<title> Registration Page </title>
</head>
<body bgcolor="Lightskyblue">
<br> <br>
<form>
<label> Firstname </label>
<input type="text" name="firstname" size="15"/> <br> <br>
<label> Middlename: </label>
<input type="text" name="middlename" size="15"/> <br> <br>
<label> Lastname: </label>
38
<input type="text" name="lastname" size="15"/> <br> <br>
<label> Course : </label>
<select>
<option value="Course">Course</option>
<option value="BCA">BCA</option>
<option value="BBA">BBA</option>
<option value="B.Tech">B.Tech</option>
<option value="MBA">MBA</option>
<option value="MCA">MCA</option>
<option value="M.Tech">M.Tech</option>
</select>
<br>
<br>
<label> Gender : </label><br>
<input type="radio" name="male"/> Male <br>
<input type="radio" name="female"/> Female <br>
<input type="radio" name="other"/> Other
<br>
<br>
<label> Phone : </label>
<input type="text" name="country code" value="+91" size="2"/>
<input type="text" name="phone" size="10"/> <br> <br>
Address
<br>
<textarea cols="80" rows="5" value="address"> </textarea>
<br> <br>
Email:
39
<input type="email" id="email" name="email"/> <br>
<br> <br>
Password:
<input type="Password" id="pass" name="pass"> <br>
<br> <br>
Re-type password:
<input type="Password" id="repass" name="repass"> <br> <br>
<input type="button" value="Submit"/>
</form>
</body>
</html>

Output:

40
18. WAP to design an interface to save, modify and
delete the student’s record.

41
Program:

import java.sql.*;
import javax.swing.JOptionPane;
public class Student extends javax.swing.JFrame
{
Connection con;
Statement st;
ResultSet rs;
public Student()
{
initComponents();
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:stud");
st=con.createStatement();
int i=st.executeUpdate("insert into Student values("+Integer.parseInt(tid.getText() )
+",'" + tname.getText()+"','"+tclass.getText()+"','"+tcontact.getText()+"')");
if(i>0)
{
JOptionPane.showMessageDialog(null, "Record Saved....");
tid.setText(null);
tname.setText(null);
tclass.setText(null);
tcontact.setText(null);
}
}
catch(Exception e)
42
{
System.out.print(e);

}
}
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt)
{
if(tid.getText().equals(""))
{
JOptionPane.showMessageDialog(null, "Fill Dept Id");
tid.requestFocus();
}
else
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:stud");
st=con.createStatement();
rs=st.executeQuery("select * from Student where sid="+Integer.parseInt(tid.getText())
+"" );
if(rs.next())
{
tname.setText(rs.getString(2));
tclass.setText(rs.getString(3));
tcontact.setText(rs.getString(4));
}
else
{
JOptionPane.showMessageDialog(null, "Record not found");
}

43
}
catch(Exception e)
{
System.out.print(e);

}}
}
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt)
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");// load the driver
con=DriverManager.getConnection("jdbc:odbc:Stud");// Create the connection with
datanase
st=con.createStatement();// Create the statement for the database
int a=st.executeUpdate("delete from Student where sid="+Integer.parseInt(tid.getText() )
+"");
if(a>0)
{
JOptionPane.showMessageDialog(null, "Student Information deleted...");
tid.setText(null);
tname.setText(null);
tclass.setText(null);
tcontact.setText(null);
}
else
{
JOptionPane.showMessageDialog(null, "Student Information not deleted...");
}
}
catch(Exception e)

44
{
System.out.print(e);
}
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt)
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");// load the driver
con=DriverManager.getConnection("jdbc:odbc:Stud");
st=con.createStatement();// Create the statement for the database
int a=st.executeUpdate("update Student set sname='"+tname.getText()+"',
sclass='"+tclass.getText()+"', SContact='"+tcontact.getText()+"' where
sid="+Integer.parseInt(tid.getText())+"");
if(a>0)
{
JOptionPane.showMessageDialog(null, "Record Updated");
tname.setEnabled(false);
tid.setEnabled(false);
tclass.setEnabled(false);
tcontact.setEnabled(true);
}
else
{
JOptionPane.showMessageDialog(null, "Record not Updated");
}
}
catch(Exception e)
{
System.out.print(e);
}

45
}
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt)
{
System.exit(0);
}
public static void main(String args[])
{
try {
for (javax.swing.UIManager.LookAndFeelInfo info :
javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex)
{ java.util.logging.Logger.getLogger(Student.class.getName()).log(java.util.logging.Level.SEV
ERE, null, ex);
} catch (InstantiationException ex)
{ java.util.logging.Logger.getLogger(Student.class.getName()).log(java.util.logging.Level.SE
VERE, null, ex);
} catch (IllegalAccessException ex)
{ java.util.logging.Logger.getLogger(Student.class.getName()).log(java.util.logging.Level.SEV
ERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex)
{ java.util.logging.Logger.getLogger(Student.class.getName()).log(java.util.logging.Level.SE
VERE, null, ex);
}
java.awt.EventQueue.invokeLater(new Runnable()
{
public void run() {

46
new Student().setVisible(true);
}
});
}

47
Output:

19: WAP to design the File and Edit menus in java.

Program:
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

48
import java.awt.event.ActionEvent;
public class MenuDialog extends Frame implements ActionListener ,ItemListener
{
Dialog dialog;
Label l;
MenuDialog()
{
MenuBar mBar = new MenuBar();
setMenuBar(mBar);
Menu file = new Menu("File");
MenuItem new_file = new MenuItem("New");
MenuItem open_file = new MenuItem("Open");
MenuItem save_file = new MenuItem("Save");
new_file.addActionListener(this);
open_file.addActionListener(this);
save_file.addActionListener(this);
file.add(new_file);
file.add(open_file);
file.add(save_file);
mBar.add(file);
Menu edit = new Menu("Edit");
MenuItem undo_edit = new MenuItem("Undo");
CheckboxMenuItem cut_edit = new CheckboxMenuItem("Cut");
CheckboxMenuItem copy_edit = new CheckboxMenuItem("Copy");
CheckboxMenuItem edit_edit = new CheckboxMenuItem("Paste");
undo_edit.addActionListener(this);
cut_edit.addItemListener(this);
49
copy_edit.addItemListener(this);
edit_edit.addItemListener(this);
edit.add(undo_edit);
edit.add(cut_edit);
edit.add(copy_edit);
edit.add(edit_edit);
mBar.add(edit);
dialog = new Dialog(this,false);
dialog.setSize(200,200);
dialog.setTitle("Dialog Box");
Button b = new Button("Close");
b.addActionListener(this);
dialog.add(b);
dialog.setLayout(new FlowLayout());
l = new Label();
dialog.add(l);
}
public void actionPerformed(ActionEvent ie)
{
String selected_item = ie.getActionCommand();
switch(selected_item)
{
case "New": l.setText("New");
break;
case "Open": l.setText("Open");
break;
case "Save": l.setText("Save");
50
break;
case "Undo": l.setText("Undo");
break;
case "Cut": l.setText("Cut");
break;
case "Copy": l.setText("Copy");
break;
case "Paste": l.setText("Paste");
break;
default: l.setText("Invalid Input");
}
dialog.setVisible(true);
if(selected_item.equals("Close"))
{
dialog.dispose();
}
}
public void itemStateChanged(ItemEvent ie)
{
this.repaint();
}
public static void main(String[] args)
{
MenuDialog md = new MenuDialog();
md.setVisible(true);
md.setSize(400,400);
}
51
}
Output:

52
20. WAP to display the student’s data in a table.

Program:

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.sql.*;
import java.awt.event.*;

public class SearchResult implements ActionListener


{
JFrame frame, frame1;
JTextField textbox;
JLabel label;
JButton button;
JPanel panel;
static JTable table;
String[] columnNames = {"Roll No", "Name", "Class", "Section"};
public void createUI()
{
frame = new JFrame("Database Search Result");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);
textbox = new JTextField();
textbox.setBounds(120,30,150,20);
label = new JLabel("Enter your roll no");
53
label.setBounds(10, 30, 100, 20);
button = new JButton("search");
button.setBounds(120,130,150,20);
button.addActionListener(this);
frame.add(textbox);
frame.add(label);
frame.add(button);
frame.setVisible(true);
frame.setSize(500, 400);
}
public void actionPerformed(ActionEvent ae)
{
button = (JButton)ae.getSource();
System.out.println("Showing Table Data.......");
showTableData();
}
public void showTableData()
{
frame1 = new JFrame("Database Search Result");
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.setLayout(new BorderLayout());
DefaultTableModel model = new DefaultTableModel();
model.setColumnIdentifiers(columnNames);
table = new JTable();
table.setModel(model);
table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
table.setFillsViewportHeight(true);
54
JScrollPane scroll = new JScrollPane(table);
scroll.setHorizontalScrollBarPolicy(
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scroll.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
String textvalue = textbox.getText();
String roll= "";
String name= "";
String cl = "";
String sec = "";
try
{
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
Connection con = DriverManager.getConnection(“jdbc:odbc:mydsn”);
String sql = "select * from student where rollno = "+textvalue;
PreparedStatement ps = con.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
int i =0;
if(rs.next())
{
roll = rs.getString("rollno");
name = rs.getString("name");
cl = rs.getString("class");
sec = rs.getString("section");
model.addRow(new Object[]{roll, name, cl, sec});
i++;
}
55
if(i <1)
{
JOptionPane.showMessageDialog(null, "No Record Found","Error",
JOptionPane.ERROR_MESSAGE);
}
if(i ==1)
{
System.out.println(i+" Record Found");
}
else
{
System.out.println(i+" Records Found");
}
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null, ex.getMessage(),"Error",
JOptionPane.ERROR_MESSAGE);
}
frame1.add(scroll);
frame1.setVisible(true);
frame1.setSize(400,300);
}
public static void main(String args[])
{
SearchResult sr = new SearchResult();
sr.createUI();
56
}
}
Output :

When you will execute the SearchResult.java class you will get the output as
follows :
1. At first a GUI window will be opened for taking input to fetch the corresponding
record into the database table as follows :

2. When you will input the value into the textbox (say, give the value 125 into the
textbox) and click on search button then the output will be as follows :

57
58

You might also like