You are on page 1of 116

PRACTICAL FILE

OF

ADVANCE OBJECT TECHNOLOGY

DAV INSTITUTE OF MANAGEMENT

SUBMITTED TO:- SUBMITTED BY:-

Ms ESHA KHANNA YACHNA SHARMA

REGISTRATION NO - 1811341364

MCA SECTION-B

1
2
Index
S. No. Content Page no. Signature
1. Write a program for making 6-7
smiling face using applets.
2. Write a program for passing 8-10
parameter values from HTML
applet tag in applet.
3. Write a program to create a menu 11-12
in frame .
4. Create a GUI page using AWT (on 13-18
frame or applet) with any 6
components(button ,text field ,label
,list ,radio button ,scroll bar ,etc.)
5. Write a program to implement Flow 19
layout in frame.
6. Write a program to implement 20-21
Border layout.
7. Write a program to implement Grid 22-23
layout(3 rows and 2 columns)
8. Write a program to implement 24-26
Card layout.
9. Write a program to implement 27-29
Gridbag layout.
10. Write a program to implement 30-32
ActionListener on a Button.
11. Write a program to implement 31-33
Window Events.
12. Write a program to implement 34-36
ItemListener on Radio button.
13. Write a program to implement 37-38
Mouse Events.

3
14. Write a program to implement Key 39-40
Events.
15. Write a program to implement Text 41
Event.
16. Write a program to implement 42-47
MouseWheel Events.
17. Create a student table with 5 47-49
columns and 5 rows JTable in
JFrame.
18. Create a hierarchal tree structure 50-52
using JTree component on MCA
course(add atleast 20 nodes)
19. Create tabbed pane components 53-54
using JTabbedPane.
20. Write a program to create a hut in 55-57
JApplet.
21. Create a home page using Swing 58-60
components.
22. Create an HTML form for entering 61-62
marks of 4 subjects and Write a
code for finding average using
Javascript.
23. 63-64
Write a code for form field
validation using
Javascript(name,address,ph no.)

24. 65-67
Create alert box using JavaScript.

25. 68-70
Create a confirm box using
JavaScript.

4
26. 71-72
Create prompt box using
JavaScript.

27. 73-74
Write a code to call a function
within another function using
JavaScript.

28. 75-76
Create an XML for a bookstore.

29 Connect Java application to a 77-80


database(oracle or Mysql) and
perform the following queries.
 Insert data to table(executeUpdate).

 Retrieve Data from a


table(executeQuery).

 Update table data(execute).

30 Write a program to insert values to 81-83


a table using batchquery
31 Write a java application to show the 84-89
use of parameterized query.
32 Implement form processing using 90-92
servlets.
33 . Create and fetch cookies using 93-95
Servlet.
34 Write a JSP code showing the use of 96-97
scriptlet, expression, declaration
and comments.
35 Write a program to illustrate 98-100
sharing of data between jsp
pages(action tags).

5
36 Write a code Access a database 101-103
from Servlet(or JSP).
37 Write a program to create a 104-108
calculator using swing components.
38 . Write a Program to create Billing 109-114
System

6
Q1. Write a program for making Smiling face using applets.

import java.applet.*;

import java.awt.*;

/*

<applet code=Smiley height=500 width=500>

</applet>

*/

public class Smiley extends Applet

public void paint(Graphics g)

g.drawOval(80,70,150,150);

g.setColor(Color.BLACK);

g.fillOval(120,120,15,15);

g.fillOval(170,120,15,15);

g.drawArc(130,180,50,20,180,180);

7
8
Q2. Write a program for passing parameter values from HTML applet tag in applet.

import java.applet.*;

import java.awt.*;

/*

<applet code=parameter height=500 width=500>

<param name="Name" value="Roger">

<param name="Age" value="26">

<param name="Sport" value="Tennis">

<param name="Food" value="Pasta">

<param name="Fruit" value="Apple">

<param name="Destination" value="California">

</applet>

*/

public class parameter extends Applet

String name;

String age;

String sport;

String food;

String fruit;

String destination;

public void init()

name = getParameter("Name");

9
age = getParameter("Age");

sport = getParameter("Sport");

food = getParameter("Food");

fruit = getParameter("Fruit");

destination = getParameter("Destination");

public void paint(Graphics g)

g.drawString("Reading parameters passed to this applet -",20,20);

g.drawString("Name-" +name,20,40);

g.drawString("Age-" +age,20,60);

g.drawString("Favourite fruit-" +fruit,20,80);

g.drawString("Favourite food-" +food,20,100);

g.drawString("Favourite destination-" +destination,20,120);

g.drawString("Favourite sport-" +sport,20,140);

10
11
Q3. Write a program to create a menu in frame.

import java.awt.*;

public class awtmenu extends Frame

public awtmenu()

setTitle("AWT menu");

setSize(400,400);

setVisible(true);

MenuBar mb = new MenuBar();

Menu file = new Menu("File");

MenuItem open = new MenuItem("Open");

MenuItem save = new MenuItem("Save");

MenuItem saveas = new MenuItem("Save as");

CheckboxMenuItem a = new CheckboxMenuItem("one");

Menu sb = new Menu("Edit");

MenuItem one = new MenuItem("copy");

MenuItem two = new MenuItem("cut");

file.add(open);

file.add(save);

file.addSeparator();

sb.add(one);

sb.add(two);

file.add(saveas);

12
file.add(sb);

mb.add(file);

setMenuBar(mb);

public static void main(String args[])

new awtmenu();

13
Q4. Create a GUI page using AWT(on frame or applet) with any 6
components(button,text field,label,list,radio button,scroll bar etc).

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

class Calculator extends frame implements ActionListener

Label lb1,lb2,lb3;

TextField txt1,txt2,txt3;

Button btn1,btn2,btn3,btn4,btn5,btn6,btn7;

public Calculator()

lb1= new Label("Var1");

lb2= new Label("Var2");

lb3= new Label("Result");

txt1 = new TextField(10);

txt2 = new TextField(10);

txt3 = new TextField(10);

btn1 = new Button("Add");

btn2 = new Button("Sub");

btn3 = new Button("Mul");

btn4 = new Button("Div");

14
btn5 = new Button("Mod");

btn6 = new Button("Reset");

btn7 = new Button("Close");

add(lb1);

add(txt1);

add(lb2);

add(txt2);

add(lb3);

add(txt3);

add(btn1);

add(btn2);

add(btn3);

add(btn4);

add(btn5);

add(btn6);

add(btn7);

setSize(200,200);

setTitle("calculator");

setLayout(new FlowLayout());

btn1.addActionListener(this);

btn2.addActionListener(this);

btn3.addActionListener(this);

15
btn4.addActionListener(this);

btn5.addActionListener(this);

btn6.addActionListener(this);

btn7.addActionListener(this);

public void actionPerformed(ActionEvent ae)

double a=0,b=0,c=0;

try

a = Double.parseDouble(txt1.getText());

catch(NumberFormatException e)

txt1.setText("Invalid input");

try

b = Double.parseDouble(txt2.getText());

catch(NumberFormatException e)

txt2.setText("Invalid input");

16
if(ae.getSource()==btn1)

c=a+b;

txt3.setText(String.valueOf(c));

if(ae.getSource()==btn2)

c=a-b;

txt3.setText(String.valueOf(c));

if(ae.getSource()==btn3)

c=a*b;

txt3.setText(String.valueOf(c));

if(ae.getSource()==btn4)

c=a/b;

txt3.setText(String.valueOf(c));

17
if(ae.getSource()==btn5)

c=a%b;

txt3.setText(String.valueOf(c));

if(ae.getSource()==btn6)

txt1.setText("0");

txt2.setText("0");

txt3.setText("0");

if(ae.getSource()==btn7)

System.exit(0);

public static void main(String args[])

Calculator calC = new Calculator();

calC.setVisible(true);

calC.setLocation(300,300);

18
19
Q5. Write a program to implement flow layout in frame.

import java.awt.*;

public class flowlayoutframe

public static void main(String args[])

Frame f = new Frame("My Frame");

Button b= new Button("OK");

TextField tf = new TextField("Programming in Java",20);

FlowLayout ff = new FlowLayout();

f.setLayout(ff);

f.add(b);

f.add(tf);

f.setSize(300,300);

f.setVisible(true);

20
Q6. Write a program to implement border layout in applet.

import java.awt.*;

public class BorderLayout1 extends Frame

public BorderLayout1()

setTitle("My Frame");

setSize(300,400);

Button northButton = new Button("North");

add(northButton,BorderLayout.NORTH);

Button southButton = new Button("South");

add(southButton,BorderLayout.SOUTH);

Button eastButton = new Button("East");

add(eastButton,BorderLayout.EAST);

Button westButton = new Button("West");

add(westButton,BorderLayout.WEST);

Button centerButton = new Button("Center");

add(centerButton,BorderLayout.CENTER);

setVisible(true);

public static void main(String args[])

BorderLayout1 t = new BorderLayout1();

21
}

22
Q7. Write a program to implement Grid layout (3 rows 2 columns).

import java.awt.*;

public class layoutgrid extends Frame

public layoutgrid()

setTitle("GridLayout");

setSize(200,220);

GridLayout g = new GridLayout(3,2);

setLayout(g);

Button button1 = new Button("one");

Button button2 = new Button("two");

Button button3 = new Button("three");

Button button4 = new Button("four");

Button button5 = new Button("five");

Button button6 = new Button("six");

Button button7 = new Button("seven");

add(button1);

add(button2);

add(button3);

add(button4);

add(button5);

add(button6);

add(button7);

23
setVisible(true);

public static void main(String args[])

layoutgrid t = new layoutgrid();

24
Q8. Write a program to implement card layout

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class CardLayoutExample extends JFrame implements ActionListener

CardLayout card;

JButton b1,b2,b3;

Container c;

CardLayoutExample()

c=getContentPane();

card=new CardLayout(40,30);

c.setLayout(card);

b1=new JButton("MCA Java");

b2=new JButton("MCA DBMS");

b3=new JButton("MCA Software Engg.");

b1.addActionListener(this);

b2.addActionListener(this);

b3.addActionListener(this);

c.add("a",b1);

c.add("b",b2);

c.add("c",b3);

25
public void actionPerformed(ActionEvent e)

card.next(c);

public static void main(String[] args)

CardLayoutExample cl=new CardLayoutExample();

cl.setSize(400,400);

cl.setVisible(true);

cl.setDefaultCloseOperation(EXIT_ON_CLOSE);

26
27
Q9. Write a program to implement gridbag layout.

import java.awt.*;

import java.awt.event.*;

import javax.swing.JFrame;

import javax.swing.*;

public class GridbagDemo extends JFrame

GridbagDemo()

setTitle("GridBagLayoutDemo");

JPanel p = new JPanel();

p.setLayout(new GridBagLayout());

GridBagConstraints c = new GridBagConstraints();

c.insets = new Insets(2, 2, 2, 2);

c.gridx = 0;

c.gridy = 0;

c.ipadx = 15;

c.ipady = 50;

p.add(new JButton("Java Swing"), c);

c.gridx = 1;

c.ipadx = 90;

c.ipady = 40;

p.add(new JButton("Layout"), c);

28
c.gridx = 0;

c.gridy = 1;

c.ipadx = 20;

c.ipady = 20;

p.add(new JButton("Manager"), c);

c.ipadx = 10;

c.gridx = 1;

p.add(new JButton("Demo"), c);

WindowListener wndCloser = new WindowAdapter()

public void windowClosing(WindowEvent e)

System.exit(0);

};

addWindowListener(wndCloser);

getContentPane().add(p);

setSize(600, 400);

setVisible(true);

public static void main(String[] args)

new GridbagDemo();

29
}

30
Q10. Write a program to implement ActionListener on a button.

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class SwingListenerDemo

private JFrame mainFrame;

private JLabel headerLabel;

private JLabel statusLabel;

private JPanel controlPanel;

public SwingListenerDemo()

prepareGUI();

public static void main(String[] args){

SwingListenerDemo swingListenerDemo = new SwingListenerDemo();

swingListenerDemo.showActionListenerDemo();

private void prepareGUI()

mainFrame = new JFrame("Java SWING Examples");

mainFrame.setSize(400,400);

mainFrame.setLayout(new GridLayout(3, 1));

31
headerLabel = new JLabel("",JLabel.CENTER );

statusLabel = new JLabel("",JLabel.CENTER);

statusLabel.setSize(350,100);

mainFrame.addWindowListener(new WindowAdapter()

public void windowClosing(WindowEvent windowEvent)

System.exit(0);

});

controlPanel = new JPanel();

controlPanel.setLayout(new FlowLayout());

mainFrame.add(headerLabel);

mainFrame.add(controlPanel);

mainFrame.add(statusLabel);

mainFrame.setVisible(true);

private void showActionListenerDemo()

headerLabel.setText("Listener in action: ActionListener");

32
JPanel panel = new JPanel();

panel.setBackground(Color.magenta);

JButton okButton = new JButton("OK");

okButton.addActionListener(new CustomActionListener());

panel.add(okButton);

controlPanel.add(panel);

mainFrame.setVisible(true);

class CustomActionListener implements ActionListener

public void actionPerformed(ActionEvent e) {

statusLabel.setText("Ok Button Clicked.");

33
34
Q11. Write a program to implement Window Events.

import java.awt.*;

import java.awt.event.WindowEvent;

import java.awt.event.WindowListener;

public class WindowExample extends Frame implements WindowListener

WindowExample()

addWindowListener(this);

setSize (400, 400);

setLayout (null);

setVisible (true);

public static void main(String[] args)

new WindowExample();

public void windowActivated (WindowEvent arg0)

System.out.println("activated");

public void windowClosed (WindowEvent arg0)

35
{

System.out.println("closed");

public void windowClosing (WindowEvent arg0)

System.out.println("closing");

dispose();

public void windowDeactivated (WindowEvent arg0)

System.out.println("deactivated");

public void windowDeiconified (WindowEvent arg0)

System.out.println("deiconified");

public void windowIconified(WindowEvent arg0)

System.out.println("iconified");

36
public void windowOpened(WindowEvent arg0)

System.out.println("opened");

} }

37
Q12. Write a program to implement ItemListener on Radio button.

<html>

<body>

<br><b> Choose your favroite season: </b><br>

<input type="radio" id="summer" value="Summer">Summer<br>

<input type="radio" id="winter" value="Winter">Winter<br>

<input type="radio" id="rainy" value="Rainy">Rainy<br>

<input type="radio" id="autumn" value="Autumn">Autumn<br><br>

<button type="button" onclick=" checkButton()"> Submit </button>

<h3 id="disp" style= "color:green"> </h3>

<h4 id="error" style= "color:red"> </h4>

</body>

<script>

function checkButton() {

if(document.getElementById('summer').checked) {

document.getElementById("disp").innerHTML

= document.getElementById("summer").value

+ " radio button is checked";

else if(document.getElementById('winter').checked) {

document.getElementById("disp").innerHTML

= document.getElementById("winter").value

+ " radio button is checked";

38
}

else if(document.getElementById('rainy').checked) {

document.getElementById("disp").innerHTML

= document.getElementById("rainy").value

+ " radio button is checked";

else if(document.getElementById('autumn').checked) {

document.getElementById("disp").innerHTML

= document.getElementById("autumn").value

+ " radio button is checked";

else {

document.getElementById("error").innerHTML

= "You have not selected any season";

</script>

</html>

39
Q14. Write a program to implement Mouse Events.

<!DOCTYPE html>

<html>

<head>

<title>JS Mouse Events - Button Demo</title>

</head>

<body>

<button id="btn">Click me with any mouse button: left, right, middle, ...</button>

<p id="message"></p>

<script>

let btn = document.querySelector('#btn');

// disable context menu when right-mouse clicked

btn.addEventListener('contextmenu', (e) => {

e.preventDefault();

});

// show the mouse event message

btn.addEventListener('mouseup', (e) => {

let msg = document.querySelector('#message');

switch (e.button) {

case 0:

msg.textContent = 'Left mouse button clicked.';

break;

40
case 1:

msg.textContent = 'Middle mouse button clicked.';

break;

case 2:

msg.textContent = 'Right mouse button clicked.';

break;

default:

msg.textContent = `Unknown mouse button code: ${event.button}`;

});

</script>

</body>

</html>

41
Q15. Write a program to implement Key Events.

<!DOCTYPE html>

<html>

<body>

<p>Whenever a character key other than left arrow key or end key or home key is typed
inside the text field, an alert is displayed.</p>

<input type="text" onkeypress="Function()">

<script>

function Function() {

alert("A character key is typed in the text field and prompting this alert to be displayed");

</script>

</body>

</html>

After the key pressed it shows an Alert Box

42
Q16. Write a program to Mouse Wheel Events.

import java.awt.BorderLayout;

import java.awt.Dimension;

import java.awt.event.MouseWheelEvent;

import java.awt.event.MouseWheelListener;

import javax.swing.BorderFactory;

import javax.swing.JComponent;

import javax.swing.JFrame;

import javax.swing.JPanel;

import javax.swing.JScrollPane;

import javax.swing.JTextArea;

public class MouseWheelEventDemo extends JPanel implements MouseWheelListener {

JTextArea textArea;

JScrollPane scrollPane;

final static String newline = "\n";

public MouseWheelEventDemo() {

super(new BorderLayout());

textArea = new JTextArea();

43
textArea.setEditable(false);

scrollPane = new JScrollPane(textArea);

scrollPane

.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

scrollPane.setPreferredSize(new Dimension(400, 250));

add(scrollPane, BorderLayout.CENTER);

textArea.append("This text area displays information "

+ "about its mouse wheel events." + newline);

textArea.addMouseWheelListener(this);

setPreferredSize(new Dimension(450, 350));

setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

public void mouseWheelMoved(MouseWheelEvent e) {

String message;

int notches = e.getWheelRotation();

if (notches < 0) {

message = "Mouse wheel moved UP " + -notches + " notch(es)"

+ newline;

} else {

message = "Mouse wheel moved DOWN " + notches + " notch(es)"

+ newline;

44
if (e.getScrollType() == MouseWheelEvent.WHEEL_UNIT_SCROLL) {

message += " Scroll type: WHEEL_UNIT_SCROLL" + newline;

message += " Scroll amount: " + e.getScrollAmount()

+ " unit increments per notch" + newline;

message += " Units to scroll: " + e.getUnitsToScroll()

+ " unit increments" + newline;

message += " Vertical unit increment: "

+ scrollPane.getVerticalScrollBar().getUnitIncrement(1)

+ " pixels" + newline;

} else { //scroll type == MouseWheelEvent.WHEEL_BLOCK_SCROLL

message += " Scroll type: WHEEL_BLOCK_SCROLL" + newline;

message += " Vertical block increment: "

+ scrollPane.getVerticalScrollBar().getBlockIncrement(1)

+ " pixels" + newline;

saySomething(message, e);

void saySomething(String eventDescription, MouseWheelEvent e) {

textArea.append(e.getComponent().getClass().getName() + ": "

+ eventDescription);

textArea.setCaretPosition(textArea.getDocument().getLength());

45
private static void createAndShowGUI() {

//Make sure we have nice window decorations.

JFrame.setDefaultLookAndFeelDecorated(true);

JFrame frame = new JFrame("MouseWheelEventDemo");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JComponent newContentPane = new MouseWheelEventDemo();

newContentPane.setOpaque(true); //content panes must be opaque

frame.setContentPane(newContentPane);

//Display the window.

frame.pack();

frame.setVisible(true);

public static void main(String[] args) {

//Schedule a job for the event-dispatching thread:

//creating and showing this application's GUI.

javax.swing.SwingUtilities.invokeLater(new Runnable() {

public void run() {

createAndShowGUI();

});

46
47
Q17. Create a student table with 5 columns and 5 rows JTable in JFrame .

import javax.swing.JFrame;

import javax.swing.JScrollPane;

import javax.swing.JTable;

public class JTableExamples {

// frame

JFrame f;

// Table

JTable j;

// Constructor

JTableExamples()

// Frame initialization

f = new JFrame();

// Frame Title

f.setTitle("JTable Example");

// Data to be displayed in the JTable

String[][] data = {

{ "Kundan Kumar Jha", "4031", "CSE" },

{ "Anand Jha", "6014", "IT" },

48
{ "Rajesh Ahuja", "4321", "CS" },

{ "Satish Rajput", "5833", "AI" },

{ "Shweta Sharma", "3673", "ML" }

};

// Column Names

String[] columnNames = { "Name", "Roll Number", "Department" };

// Initializing the JTable

j = new JTable(data, columnNames);

j.setBounds(30, 40, 200, 300);

// adding it to JScrollPane

JScrollPane sp = new JScrollPane(j);

f.add(sp);

// Frame Size

f.setSize(500, 200);

// Frame Visible = true

f.setVisible(true);

// Driver method

public static void main(String[] args)

49
new JTableExamples();

50
Q18. Create a hierarchal strurcture using JTree component on MCA course(add atleast
20 nodes).

import javax.swing.*;

import javax.swing.tree.DefaultMutableTreeNode;

public class Tree {

JFrame f;

Tree(){

f=new JFrame();

DefaultMutableTreeNode country=new DefaultMutableTreeNode("DAVIM");

DefaultMutableTreeNode mca=new DefaultMutableTreeNode("MCA");

country.add(mca);

DefaultMutableTreeNode ad=new DefaultMutableTreeNode("Advance Java");

DefaultMutableTreeNode os=new DefaultMutableTreeNode("Operating System");

DefaultMutableTreeNode ab=new DefaultMutableTreeNode("Advance Database");

DefaultMutableTreeNode cs=new DefaultMutableTreeNode("Communication Skills");

DefaultMutableTreeNode lx=new DefaultMutableTreeNode("Linux");

DefaultMutableTreeNode cc=new DefaultMutableTreeNode("Cloud Computing");

DefaultMutableTreeNode db=new DefaultMutableTreeNode("Database");

DefaultMutableTreeNode cg=new DefaultMutableTreeNode("Computer Graphics");

DefaultMutableTreeNode jv=new DefaultMutableTreeNode("Java");

DefaultMutableTreeNode ds=new DefaultMutableTreeNode("Data Structure");

DefaultMutableTreeNode php=new DefaultMutableTreeNode("PHP");

DefaultMutableTreeNode cn=new DefaultMutableTreeNode("Computer Networking");

DefaultMutableTreeNode wd=new DefaultMutableTreeNode("Web Designing");

DefaultMutableTreeNode as=new DefaultMutableTreeNode("Digital Design");

51
mca.add(ad); mca.add(os); mca.add(ab); mca.add(cs); mca.add(lx); mca.add(cc);
mca.add(db); mca.add(cg); mca.add(jv); mca.add(ds); mca.add(php); mca.add(cn);
mca.add(wd); mca.add(as);

JTree jt=new JTree(mca);

f.add(jt);

f.setSize(500,500);

f.setVisible(true);

public static void main(String[] args) {

new Tree();

52
53
Q19. Create a Tabbed Pane component using JTabbedPane.

import javax.swing.*;

public class TabbedPaneExample {

JFrame f;

TabbedPaneExample(){

f=new JFrame();

JTextArea ta=new JTextArea(200,200);

JPanel p1=new JPanel();

p1.add(ta);

JPanel p2=new JPanel();

JPanel p3=new JPanel();

JTabbedPane tp=new JTabbedPane();

tp.setBounds(50,50,200,200);

tp.add("main",p1);

tp.add("visit",p2);

tp.add("help",p3);

f.add(tp);

f.setSize(400,400);

f.setLayout(null);

f.setVisible(true);

public static void main(String[] args) {

new TabbedPaneExample();

}}

54
55
Q20. Create a program to create a hut in Applet.

import java.awt.*;

/*

<applet code=Hut height=500 width=500>

</applet>

*/

public class Hut extends java.applet.Applet

public void paint(Graphics g)

g.drawLine(100,400,300,400);

g.drawLine(100,400,70,450);

g.drawLine(300,400,350,450);

g.drawLine(300,400,250,450);

g.drawLine(70,450,350,450);

g.drawLine(70,450,70,600);

g.drawLine(250,450,250,600);

g.drawLine(350,450,350,600);

g.drawLine(70,600,350,600);

g.drawRect(270,600,90,110);

setBackground(Color.black);

setForeground(Color.white);

g.drawOval(700,10,75,100);

56
g.fillOval(700,10,75,100);

g.drawOval(500,350,5,10);

g.fillOval(500,350,5,10);

g.drawOval(400,10,5,10);

g.fillOval(400,10,5,10);

g.drawOval(420,10,5,10);

g.fillOval(420,10,5,10);

g.drawOval(380,10,5,10);

g.fillOval(380,10,5,10);

g.drawOval(350,10,2,10);

g.fillOval(350,10,2,10);

g.drawOval(320,10,3,10);

g.fillOval(320,10,3,10);

g.drawOval(200,10,5,10);

g.fillOval(200,10,5,10);

g.drawOval(190,10,4,10);

g.fillOval(190,10,4,10);

g.drawOval(180,10,5,10);

g.fillOval(180,10,5,10);

g.drawOval(160,10,1,10);

g.fillOval(160,10,1,10);

g.drawOval(110,10,2,10);

g.fillOval(110,10,2,10);

g.drawOval(100,10,3,10);

57
g.fillOval(100,10,3,10);

g.drawOval(80,10,5,10);

g.fillOval(800,10,5,10);

g.drawOval(60,10,5,10);

g.fillOval(60,10,5,10);

58
Q21. Create a home page using Swing Components.

import javax.swing.*;

import java.awt.*;

class gui {

public static void main(String args[]) {

JFrame frame = new JFrame("Chat Frame");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setSize(400, 400);

JMenuBar mb = new JMenuBar();

JMenu m1 = new JMenu("FILE");

JMenu m2 = new JMenu("Help");

mb.add(m1);

mb.add(m2);

JMenuItem m11 = new JMenuItem("Open");

JMenuItem m22 = new JMenuItem("Save as");

m1.add(m11);

m1.add(m22);

JPanel panel = new JPanel();

JLabel label = new JLabel("Enter Text");

JTextField tf = new JTextField(10);

JButton send = new JButton("Send");

JButton reset = new JButton("Reset");

59
panel.add(label);

panel.add(tf);

panel.add(send);

panel.add(reset);

JTextArea ta = new JTextArea();

frame.getContentPane().add(BorderLayout.SOUTH, panel);

frame.getContentPane().add(BorderLayout.NORTH, mb);

frame.getContentPane().add(BorderLayout.CENTER, ta);

frame.setVisible(true);

60
61
Q22. Create a HTML form for entering marks of 4 subjects and write a code for finding
average using Javascript.

<html>

<head>

<script type="text/javascript">

function total()

const s1=parseInt(form1.OS.value)

const s2=parseInt(form1.java.value)

const s3=parseInt(form1.adbms.value)

const s4=parseInt(form1.cloud.value)

const s5=parseInt(form1.web.value)

function calculate()

const total=s1+s2+s3+s4+s5

result=total/5

form1.answer.value=result+"%"

result=calculate()

</script></head>

<body>

<form name="form1">

Enter marks in OS:

<input type="text" name="OS" ><br><br>

62
Enter marks in Java :

<input type="text" name="java" ><br><br>

enter marks in ADBMS:

<input type="text" name="adbms" ><br><br>

enter marks in Cloud:

<input type="text" name="cloud" ><br><br>

enter marks in WebTech:

<input type="text" name="web" ><br><br>

Result

<input type="button" value="calculate" onclick="total()"><br><br>

Your result:

<input type="text" name="answer" ><br><br>

</form>

</body>

</html>

63
Q23. Write a code for form field validations using Javascript(name,address,phn no).

<html>

<head>

<script type = "text/javascript">

function validate()

if(document.form1.yourname.value.length<2)

alert("please enter your full name")

if(document.form1.address.value.length<3)

alert("please enter your full address")

if(document.form1.mobileno.value.length!==10)

alert("please enter valid mobileno")

</script>

</head>

<body>

<form name="form1">

Name:<input type ="text" name="yourname">

64
Address:<input type ="text" name="address">

MobileNo:<input type ="text" name="mobileno">

<input type ="button" value="submit"

onclick="validate()">

</form>

</body>

</html>

65
Q24. Create alert box using Javascript.

<!DOCTYPE html>

<html>

<head>

<title>

Alert() Method in JavaScript

</title>

<style>

h1 {

color: Blue;

h2 {

font-family: Impact;

body {

text-align: center;

</style>

</head>

<body>

<h1>Welcome to DAVIM</h1>

<h2>Alert in JavaScript</h2>

66
<p>

To Display the alert message,

click on the "Show Alert Message" button:

</p>

<button ondblclick="myalert()">

Show Alert Message

</button>

<script>

function myalert() {

alert("This is the Alert Message!");

</script>

</body>

</html>

67
68
Q25. Create confirm box using Javascript.

<!DOCTYPE html>

<html>

<title>Confirm Box</title>

<!--CSS Styles-->

<style>

<p>

border: double 8px red;

font-size: 28px;

color: green;

text-align: justify;

<h1>

color: blue;

text-align:center;

</style>

<!--JavaScript Logic-->

<script>

function getYourDecision() {//function definition

var course = confirm("Are you interested to take online course in DAVIM?");//taking


confirm action from user

if (course==true) //if press ok then value is true

69
{

document.write("<h2 style='color:green'>Congratulations! You have taken right decision!


You will be landed in right website to learn IT Courses.</h2>");//if we press OK then it will
display this message

else //if press Cancel then value is false

document.write("<h2 style='color:red'>Sorry! you can think about this why don't you take
courses in DAVIM!");//if we press Cancel then it will display this message

getYourDecision();

</script>

<body>

<div>

<h1>Confirm Box Real Time Example</h1>

<p>Real time Example: Let suppose we have online application form for payment method.
After filling online payment application form, if you want to proceed with payment then it
will display pop up box. If you want to move further we have to click Ok button, if we click
Cancel button then payment stop there will itself and come back to home page.</p>

</div>

</body>

</html>

70
71
Q26. Create a prompt box using Javascript.

<!DOCTYPE html>

<html>

<head>

<title>

JavaScript prompt() method

</title>

<script>

function fun() {

var a = prompt("Enter some text", "the javatpoint.com");

if (a != null) {

document.getElementById("para").innerHTML = "Welcome to " + a;

</script>

</head>

<body style = "text-align: center;">

<h1 style = "color: red;">

Hello World

</h1>

<h2>

Example of the JavaScript prompt() method

72
</h2>

<button onclick = "fun()">

Click me

</button>

<p id = "para"></p>

</body>

</html>

73
Q27. Write a code to call afunction within another function using Javascript.

<html>

<head>

<script type="text/javascript">

function product()

const s1=parseInt(form1.num1.value)

const s2=parseInt(form1.num2.value)

const s3=parseInt(form1.num3.value)

function calculate()

const product1=s1*s2*s3

form1.answer.value=product1

result=calculate()

</script></head>

<body>

<form name="form1">

Enter first num:

<input type="text" name="num1" ><br><br>

Enter 2nd num:

<input type="text" name="num2" ><br><br>

Enter 3rd num:

74
<input type="text" name="num3" ><br><br>

Result

<input type="button" value="calculate" onclick="product()"><br><br>

Your result:

<input type="text" name="answer" ><br><br>

</form>

</body>

</html>

75
Q28. Create an XML for a bookstore.

<!DOCTYPE html>

<html>

<body>

<h2>JavaScript Functions</h2>

<p>This example creates an object with 3 properties (firstName,

lastName, fullName).</p>

<p>The fullName property is a method:</p>

<p id="demo"></p>

<script>

const myObject = {

firstName:"AYUSHI",

lastName: "RAJPUT", fullName: function() {

return this.firstName + " " + this.lastName;

document.getElementById("demo").innerHTML = myObject.fullName();

</script>

</body>

</html>

76
77
Q29. Connect Java application to a database (oracle or Mysql) and
perform the following queries

 Insert data to table (execute Update).


import java.sql.*;
public class My sql Insertion
{
public static void main(String args[])
{
Connection conn = null;
try{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("This Program is done by Nikita valecha");
System.out.println("connecting to database....");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/sample","root","tige
r");
//here librarydb is the database name, root is the username and tiger is the password
System.out.println("Database Connected....");
// create a statement to insert a row
Statement stmt=con.createStatement();
int norows=stmt.executeUpdate("insert into samp1 value('Nikita','MCA','DAVIM
College')");
System.out.println("NO of Rows Affected = "+ norows);
con.close();
System.out.println("Database Closed....");
}catch(Exception e)
{
System.out.println(e);
}
}
}

78
 Retrieve Data from a table(executeQuery).
import java.sql.*
public class Example
{
public static void main(String args[])
{
Connection conn = null;
try{
System.out.println("This Program is done by Nikita");
Class.forName("com.mysql.jdbc.Driver");
System.out.println("connecting to database....");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/sample","root","tige
r");
//here librarydb is the database name, root is the username and tiger is the password
System.out.println("Database Connected....");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from college");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2));
con.close();
System.out.println("Database Closed....");

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

 Update table data(execute).

import java.sql.*;

public class ExampleUpdate

public static void main(String args[])

Connection conn = null;

try{

System.out.println("This Program is done by Nikita");

Class.forName("com.mysql.jdbc.Driver");

System.out.println("connecting to database....");

80
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/sample","root","tige
r");

//here librarydb is the database name, root is the username and tiger is the password

System.out.println("Database Connected....");

Statement stmt=con.createStatement();

boolean rs=stmt.execute("update samp1 set class='MCA 4th'");

System.out.println("Database Updated Successfully........"+rs);

con.close();

System.out.println("Database Closed....");

}catch(Exception e)

System.out.println(e);

} }

81
Q30. Write a program to insert values to a table using batch query.

import java.sql.*;

public class Batch

public static void main(String args[])

Connection conn = null;

try{

System.out.println("This Program is done by Nikita");

Class.forName("com.mysql.jdbc.Driver");

System.out.println("connecting to database....");

Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/sample","root","tiger");

//here librarydb is the database name, root is the username and tiger is the password

System.out.println("Database Connected....");

Statement stmt=con.createStatement();

//create a sql statement

String sql="insert into college values(101,'Dayanand college');";

stmt.addBatch(sql);

String sql1="insert into college values(102,'DAVIM college');";

stmt.addBatch(sql1);

String sql2="insert into college values(103,'Aggarwal college');";

stmt.addBatch(sql2);

String sql3="insert into college values(104,'KL Mehta college');";

82
stmt.addBatch(sql3);

String sql4="insert into college values(105,'Nehru College');";

stmt.addBatch(sql4);

stmt.executeBatch();

System.out.println("Query Execute Successfully...... ");

con.close();

System.out.println("Database Closed....");

}catch(Exception e)

System.out.println(e);

}}

83
84
Q31. Write a java application to show the use of parameterized query.

import java.sql.*;

public class Input extends javax.swing.JFrame {

public Input() {

initComponents();

@SuppressWarnings("unchecked")

// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-


BEGIN:initComponents

private void initComponents() {

jPanel1 = new javax.swing.JPanel();

jLabel1 = new javax.swing.JLabel();

jLabel2 = new javax.swing.JLabel();

name = new javax.swing.JTextField();

age = new javax.swing.JTextField();

jButton1 = new javax.swing.JButton();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

jLabel1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N

jLabel1.setText("Name");

jLabel2.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N

jLabel2.setText("Age");

jButton1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N

jButton1.setText("Record");

jButton1.addActionListener(new java.awt.event.ActionListener() {

85
public void actionPerformed(java.awt.event.ActionEvent evt) {

jButton1ActionPerformed(evt);

});

javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);

jPanel1.setLayout(jPanel1Layout);

jPanel1Layout.setHorizontalGroup(

jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGroup(jPanel1Layout.createSequentialGroup()

.addGap(64, 64, 64)

.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADI
NG, false)

.addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)

.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))

.addGap(47, 47, 47)

.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADI
NG)

.addComponent(jButton1)

.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADI
NG, false)

.addComponent(name)

.addComponent(age, javax.swing.GroupLayout.DEFAULT_SIZE, 179,


Short.MAX_VALUE)))

.addContainerGap(56, Short.MAX_VALUE))

86
);

jPanel1Layout.setVerticalGroup(

jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGroup(jPanel1Layout.createSequentialGroup()

.addGap(27, 27, 27)

.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASEL
INE)

.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 27,


javax.swing.GroupLayout.PREFERRED_SIZE)

.addComponent(name, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE))

.addGap(18, 18, 18)

.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASEL
INE)

.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 26,


javax.swing.GroupLayout.PREFERRED_SIZE)

.addComponent(age, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE))

.addGap(18, 18, 18)

.addComponent(jButton1)

.addContainerGap(19, Short.MAX_VALUE))

);

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());

getContentPane().setLayout(layout);

layout.setHorizontalGroup(

87
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGroup(layout.createSequentialGroup()

.addGap(53, 53, 53)

.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.


GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)

.addContainerGap(29, Short.MAX_VALUE))

);

layout.setVerticalGroup(

layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()

.addContainerGap(31, Short.MAX_VALUE)

.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)

.addGap(20, 20, 20))

);

setSize(new java.awt.Dimension(477, 247));

setLocationRelativeTo(null);

}// </editor-fold>//GEN-END:initComponents

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-


FIRST:event_jButton1ActionPerformed

// TODO add your handling code here:

try{

System.out.println("This Program is done by Nikita");

Class.forName("com.mysql.jdbc.Driver");

88
System.out.println("connecting to database....");

//here librarydb is the database name, root is the username and tiger is the password

try (Connection con =


DriverManager.getConnection("jdbc:mysql://localhost:3306/sample","root","tiger")) {

//here librarydb is the database name, root is the username and tiger is the password

System.out.println("Database Connected....");

PreparedStatement stmt=con.prepareStatement("insert into samp2 values(?,?)");

stmt.setString(1,name.getText());

stmt.setString(2,age.getText());

stmt.executeUpdate();

System.out.println("Database Closed....");

catch(ClassNotFoundException | SQLException e)

System.out.println(e);

}//GEN-LAST:event_jButton1ActionPerformed

public static void main(String args[]) {

new Input().setVisible(true);

// Variables declaration - do not modify//GEN-BEGIN:variables

private javax.swing.JTextField age;

private javax.swing.JButton jButton1;

private javax.swing.JLabel jLabel1;

89
private javax.swing.JLabel jLabel2;

private javax.swing.JPanel jPanel1;

private javax.swing.JTextField name;

// End of variables declaration//GEN-END:variables

90
Q32. Implement form processing using servlets.

Index.html
<html>
<head>
<title>Register Form</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form method="post" action="Register">
Name:<input type="text" name="Name"/><br/>
Email ID:<input type="text" name="Email"/><br/>
Password:<input type="text" name="Password"/><br/>
<input type="submit" value="Register"/>
</form>
</body>
</html>
Register.html
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Register extends HttpServlet
{
@Override
@SuppressWarnings("UseSpecificCatch")

91
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out=response.getWriter();
String name=request.getParameter("Name");
String email=request.getParameter("Email");
String pass=request.getParameter("Password");
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/sample","root","tiger");
PreparedStatement pst=con.prepareStatement("insert into pro2 values(?,?,?)");
pst.setString(1,name);
pst.setString(2,email);
pst.setString(3,pass);
int i=pst.executeUpdate();
if(i>0)
{
out.println("You are Successfully Registered");
}
else
{
out.println("Got problem in Registering the data in database");
}
}
catch(Exception se)
{
System.out.println("Error"+se);
}
}}

92
93
Q33. Create and fetch cookies using Servlet.
Index.html
<html>
<head>
<title>
</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="firstservlet" method="post">
Name:<input type="text" name="Username"/><br/>
<input type="submit" value="GO"/>
</form>
</body>
</html>
firstservlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class firstservlet extends HttpServlet {
@Override
@SuppressWarnings("ConvertToTryWithResources")
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
response.setContentType("text/html");
PrintWriter out=response.getWriter();
String n=request.getParameter("Username");

94
out.println("welcome"+n);
Cookie ck=new Cookie("Username",n);
response.addCookie(ck);
out.println("<form action='secondservlet'>");
out.println("<input type='submit' value='go'>");
out.println("</form>");
out.close();
}
catch(Exception e)
{
System.out.print(e);
}
}}
secondservlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
@WebServlet(urlPatterns = {"/secondservlet"})
public class secondservlet extends HttpServlet {
@Override
@SuppressWarnings("ConvertToTryWithResources")
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Cookie ck[] = request.getCookies();
out.println("Hello "+ ck[0].getValue());
out.close();
}
catch(Exception e)
{

95
System.out.println(e);
}
}}

OUTPUT:-

96
Q34. Write a JSP code showing the use of scriptlet, expression, declaration
and comments.

Index.html
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="sum.jsp" method="post">
Enter Your Name<input type="text" name="Name"/><br/>
<input type="submit" value="Welcome"/>
</form>
</body>
</html>
Sum.Jsp
<%--
Document : sum
Created on : Apr 3, 2017, 12:06:00 AM
Author : Nikita
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%!
int Sum(int n,int m)

97
{
return(n+m);
}
%>
<%
String n=request.getParameter("Name");
out.println("Welcome"+n);
out.println(Sum(20,30));
%>
<%= 30+50 %>
</body>
</html>
OUTPUT:-

98
Q35.Write a program to illustrate sharing of data between jsp pages(action
tags).

Index.html

<html>

<head>

<title>TODO supply a title</title>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

</head>

<body>

<form action="MCA.jsp" method="post">

Enter Your Name<input type="text" name="Name"/><br/>

<input type="submit" value="Ready For Exam"/>

</form>

</body>

</html>

Exam.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Exam Page</title>

</head>

99
<body>

<%

out.println("Stary Studing");

%>

</body>

</html>

MCA.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>


<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>
</title>
</head>
<body>
<%
String n=request.getParameter("Name");
out.print("Hello "+n );
%>
<br/>
<jsp:include page="Exam.jsp"></jsp:include>
<br/>
<%
out.print("All the Best" );
%>
</body>
</html>

100
OUTPUT:-

101
Q36. Write a code Access a database from Servlet(or JSP).

Index.html
<html>
<head>
<title>Register Form</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form method="post" action="Register">
Name:<input type="text" name="Name"/><br/>
Email ID:<input type="text" name="Email"/><br/>
Password:<input type="text" name="Password"/><br/>
<input type="submit" value="Register"/>
</form>
</body>
</html>
Register.html
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Register extends HttpServlet
{
@Override
@SuppressWarnings("UseSpecificCatch")
protected void doPost(HttpServletRequest request, HttpServletResponse response)

102
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out=response.getWriter();
String name=request.getParameter("Name");
String email=request.getParameter("Email");
String pass=request.getParameter("Password");
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/sample","root","tiger");
PreparedStatement pst=con.prepareStatement("insert into pro2 values(?,?,?)");
pst.setString(1,name);
pst.setString(2,email);
pst.setString(3,pass);
int i=pst.executeUpdate();
if(i>0)
{
out.println("You are Successfully Registered");
}
else
{
out.println("Got problem in Registering the data in database");
}
}
catch(Exception se)
{
System.out.println("Error"+se);
}
}}

103
OUTPUT:-

104
Q37. Write a program to create a calculator using swing components

import java.awt.BorderLayout;

import java.awt.GridBagConstraints;

import java.awt.GridBagLayout;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JPanel;

import javax.swing.JTextField;

public class Calculator implements ActionListener {

private static JTextFieldinputBox;

Calculator(){}

public static void main(String[] args) {

createWindow();

private static void createWindow() {

JFrame frame = new JFrame("Calculator");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

createUI(frame);

frame.setSize(200, 200);

frame.setLocationRelativeTo(null);

frame.setVisible(true);

105
private static void createUI(JFrame frame) {

JPanel panel = new JPanel();

Calculator calculator = new Calculator();

GridBagLayout layout = new GridBagLayout();

GridBagConstraintsgbc = new GridBagConstraints();

panel.setLayout(layout);

inputBox = new JTextField(10);

inputBox.setEditable(false);

JButton button0 = new JButton("0");JButton button1 = new JButton("1");

JButton button2 = new JButton("2");JButton button3 = new JButton("3");

JButton button4 = new JButton("4");JButton button5 = new JButton("5");

JButton button6 = new JButton("6");JButton button7 = new JButton("7");

JButton button8 = new JButton("8");JButton button9 = new JButton("9");

JButtonbuttonPlus = new JButton("+");JButtonbuttonMinus = new JButton("-");

JButtonbuttonDivide = new JButton("/");JButtonbuttonMultiply = new JButton("x");

JButtonbuttonClear = new JButton("C");JButtonbuttonDot = new JButton(".");

JButtonbuttonEquals = new JButton("=");

button1.addActionListener(calculator);button2.addActionListener(calculator);

button3.addActionListener(calculator);button4.addActionListener(calculator);

button5.addActionListener(calculator);button6.addActionListener(calculator);
button7.addActionListener(calculator);button8.addActionListener(calculator);

button9.addActionListener(calculator);button0.addActionListener(calculator);

buttonPlus.addActionListener(calculator);buttonMinus.addActionListener(calculator);

buttonDivide.addActionListener(calculator);buttonMultiply.addActionListener(calculator);

buttonClear.addActionListener(calculator);buttonDot.addActionListener(calculator);

106
buttonEquals.addActionListener(calculator);

gbc.fill = GridBagConstraints.HORIZONTAL;

gbc.gridx = 0; gbc.gridy = 0; panel.add(button1, gbc);

gbc.gridx = 1; gbc.gridy = 0; panel.add(button2, gbc);

gbc.gridx = 2; gbc.gridy = 0; panel.add(button3, gbc);

gbc.gridx = 3; gbc.gridy = 0; panel.add(buttonPlus, gbc);

gbc.gridx = 0; gbc.gridy = 1; panel.add(button4, gbc);

gbc.gridx = 1; gbc.gridy = 1; panel.add(button5, gbc);

gbc.gridx = 2; gbc.gridy = 1; panel.add(button6, gbc);

gbc.gridx = 3; gbc.gridy = 1; panel.add(buttonMinus, gbc);

gbc.gridx = 0; gbc.gridy = 2; panel.add(button7, gbc);

gbc.gridx = 1; gbc.gridy = 2; panel.add(button8, gbc);

gbc.gridx = 2; gbc.gridy = 2; panel.add(button9, gbc);

gbc.gridx = 3; gbc.gridy = 2; panel.add(buttonDivide, gbc);

gbc.gridx = 0; gbc.gridy = 3; panel.add(buttonDot, gbc);

gbc.gridx = 1; gbc.gridy = 3; panel.add(button0, gbc);

gbc.gridx = 2; gbc.gridy = 3; panel.add(buttonClear, gbc);

gbc.gridx = 3; gbc.gridy = 3; panel.add(buttonMultiply, gbc);

gbc.gridwidth = 3;

gbc.gridx = 0; gbc.gridy = 4; panel.add(inputBox, gbc);

gbc.gridx = 3; gbc.gridy = 4; panel.add(buttonEquals, gbc);

frame.getContentPane().add(panel, BorderLayout.CENTER);

public void actionPerformed(ActionEvent e) {

107
String command = e.getActionCommand();

if (command.charAt(0) == 'C') {

inputBox.setText("");

}else if (command.charAt(0) == '=') {

inputBox.setText(evaluate(inputBox.getText()));

}else {

inputBox.setText(inputBox.getText() + command);

public static String evaluate(String expression) {

char[] arr = expression.toCharArray();

String operand1 = "";String operand2 = "";String operator = "";

double result = 0;

for (int i = 0; i<arr.length; i++) {

if (arr[i] >= '0' &&arr[i] <= '9' || arr[i] == '.') {

if(operator.isEmpty()){

operand1 += arr[i];

}else{

operand2 += arr[i];

if(arr[i] == '+' || arr[i] == '-' || arr[i] == '/' || arr[i] == '*') {

operator += arr[i];

108
}

if (operator.equals("+"))

result = (Double.parseDouble(operand1) + Double.parseDouble(operand2));

else if (operator.equals("-"))

result = (Double.parseDouble(operand1) - Double.parseDouble(operand2));

else if (operator.equals("/"))

result = (Double.parseDouble(operand1) / Double.parseDouble(operand2));

else

result = (Double.parseDouble(operand1) * Double.parseDouble(operand2));

return operand1 + operator + operand2 + "=" +result;

OUTPUT:-

109
Q38. Write a Program to create Billing System.

import java.awt.event.*;

import javax.swing.*;

import java.util.*;

//itvoyagers.in

public class MyStationery extends JFrame implements ActionListener

HashMap<String, String>product_and_price;

DefaultListModel<String>product_name_bill, product_quantity_bill,product_price_bill;

JLabelproduct_name, price_per_unit, quantity_label, price_of_product, price_per_unit_label,


total, total_amount, bill_product, bill_quantity, bill_price;

JComboBoxproduct_list, quantity_list;

JListproduct_bill, product_quantity, product_price;

JButtonadd_product;

public MyStationery()

product_and_price = new HashMap<String, String>();

product_and_price.put("Book", "80");

product_and_price.put("Pen", "10");

product_and_price.put("Pencil", "7");

product_and_price.put("Marker", "40");

product_and_price.put("Eraser", "5");

//itvoyagers.in

product_name_bill = new DefaultListModel<>();

110
product_price_bill = new DefaultListModel<>();

product_quantity_bill = new DefaultListModel<>();

product_name = new JLabel("Product Name");

quantity_label = new JLabel("Quantity");

price_per_unit = new JLabel("Price Per Unit(₹)");

price_per_unit_label = new JLabel("80");

product_list = new JComboBox();

quantity_list = new JComboBox();

product_and_price.forEach((key,value)->

product_list.addItem(key);

});

for(int i=1; i<=10; i++)

quantity_list.addItem(Integer.toString(i));

//itvoyagers.in

bill_product = new JLabel("Item");

bill_quantity = new JLabel("Quantity");

bill_price = new JLabel("Cost");

product_bill = new JList(product_name_bill);

product_price = new JList(product_price_bill);

product_quantity = new JList(product_quantity_bill);

111
add_product = new JButton("Add Product");

total = new JLabel("Total Amount : ");

total_amount = new JLabel();

product_name.setBounds(10, 30, 100, 20);

price_per_unit.setBounds(160, 30, 100, 20);

quantity_label.setBounds(310, 30, 100, 20);

price_per_unit_label.setBounds(160, 50, 100, 20);

product_list.setBounds(10, 50, 100, 20);

quantity_list.setBounds(310, 50, 100, 20);

//itvoyagers.in

add_product.setBounds(10, 80, 400, 50);

bill_product.setBounds(10, 150, 150, 20);

bill_quantity.setBounds(170, 150, 90, 20);

bill_price.setBounds(270, 150, 140, 20);

product_bill.setBounds(10, 175, 150, 400);

product_quantity.setBounds(170, 175, 90, 400);

product_price.setBounds(270, 175, 140, 400);

total.setBounds(140, 575, 200, 20);

total_amount.setBounds(310, 575, 90, 20);

add(product_name);

add(price_per_unit);

add(quantity_label);

add(price_per_unit_label);

add(product_list);

112
add(quantity_list);

add(add_product);

//itvoyagers.in

add(bill_product);

add(bill_quantity);

add(bill_price);

add(product_bill);

add(product_quantity);

add(product_price);

add(total);

add(total_amount);

product_list.addActionListener(this);

add_product.addActionListener(this);

setSize(435,650);

setLayout(null);

setVisible(true);

setTitle("My Stationery");

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//itvoyagers.in

public void actionPerformed(ActionEvent e)

if(e.getSource()==add_product)

113
product_name_bill.addElement((String) product_list.getSelectedItem());

product_quantity_bill.addElement((String) quantity_list.getSelectedItem());

int unit_price =
Integer.parseInt(product_and_price.get(product_list.getSelectedItem()));

int product_quantity = Integer.parseInt((String) quantity_list.getSelectedItem());

int total_for_product = unit_price*product_quantity;

int total_cost = 0;

product_price_bill.addElement(Integer.toString(total_for_product));

for(int i=0;i<product_price_bill.getSize();i++)

total_cost += Integer.parseInt(product_price_bill.getElementAt(i));

total_amount.setText(Integer.toString(total_cost));

else if(e.getSource()==product_list)

price_per_unit_label.setText(product_and_price.get(product_list.getSelectedItem()));

//itvoyagers.in

public static void main(String[] args)

MyStationeryms = new MyStationery();

114
}

OUTPUT:-

115
116

You might also like