Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
151 views

Java Programming II - Lab Report (Hari Rijal)

This document provides code examples for creating simple Java applets and a basic notepad application. It includes: 1) An applet that prints "Welcome to Applet" 2) An applet that reads and displays a parameter value passed to it 3) An applet that checks if a user-entered word is length 5 4) A notepad application with a menu bar for file open/save/new and edit options like copy/paste. It demonstrates copying text between files.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
151 views

Java Programming II - Lab Report (Hari Rijal)

This document provides code examples for creating simple Java applets and a basic notepad application. It includes: 1) An applet that prints "Welcome to Applet" 2) An applet that reads and displays a parameter value passed to it 3) An applet that checks if a user-entered word is length 5 4) A notepad application with a menu bar for file open/save/new and edit options like copy/paste. It demonstrates copying text between files.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

www.studynotesnepal.

com
1. Write a Simple Applet program to print "Welcome to Applet".
//AppletBook.java
import java.applet.Applet;
import java.awt.Graphics;
public class AppletBook extends Applet{
public void paint (Graphics g){
g.drawString("Welcome to Applet", 150, 150);
}
}

Output:

2. Create an applet that reads the parameter supplied from the <param> tag and display the
parameter value. Also create a suitable HTML file.
//MyApplet.java
import javax.swing.*;
public class MyApplet extends JApplet {
JPanel panel;
JButton b1;
JLabel label;
public void init(){
panel=new JPanel();
getContentPane().add(panel);
b1=new JButton("Click Me");
setVisible(true);
setSize(200,200);
panel.add(b1);

}
public void start(){
String str =getParameter("city");
label=new JLabel(str);
panel.add(label);

}
public void stop(){

}
public void destroy(){
System.out.println("Appplet Destroying...");
}

}
1|Page
Prepared By: Hari Rijal (Study Notes Nepal)
www.studynotesnepal.com

//MyApplet.html

<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<applet code="MyApplet.class" height="400" width="200">
<param name="city" value="Kathmandu">
</applet>

</body>
</html>

Output:

3. write an applet to check whether given word by user is of length 5 or not.


//AppletDemo.java
import java.applet.*;
import java.awt.*;
import java.awt.event.*;

public class AppletDemo extends Applet implements KeyListener{


TextField t1;
Label lab;

public void init(){


t1=new TextField();
add(t1);
lab=new Label();

add(lab);
setSize(300,300);
setLayout(new GridLayout(2,1));
}
public void start(){
t1.addKeyListener(this);
}
public void keyTyped(KeyEvent e){}
public void keyPressed(KeyEvent e){}

2|Page
Prepared By: Hari Rijal (Study Notes Nepal)
www.studynotesnepal.com
public void keyReleased(KeyEvent e){

String a=t1.getText();
if(a.length()==5){
lab.setText(a+" is of length 5");

}
else{
lab.setText(a+" is not of length 5");
}
}
}

Output:

4. Write a java program to create simple Notepad.


//FileDialogDemo
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import javax.swing.*;
import javax.swing.filechooser.*;

public class FileDialogDemo extends JFrame {


private static final int DEFAULT_WIDTH=300;
private static final int DEFAULT_HEIGHT=400;
private JFileChooser chooser;

public FileDialogDemo(){
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu menu = new JMenu("File");
menuBar.add(menu);
JFrame frame = new JFrame();
JPanel panel = new JPanel();
// Image icon =
Toolkit.getDefaultToolkit().getImage("D:\\JavaProject\\JavaApplication1\\src\\notepad.jpg");
JTextArea txtArea = new JTextArea(DEFAULT_HEIGHT, DEFAULT_WIDTH);
frame.add(panel);
panel.add(txtArea);

JLabel label = new JLabel();

3|Page
Prepared By: Hari Rijal (Study Notes Nepal)
www.studynotesnepal.com

JMenuItem openItem = new JMenuItem("Open");


openItem.setAccelerator(KeyStroke.getKeyStroke("Ctrl+O"));
openItem.setEnabled(true);
JMenuItem saveItem = new JMenuItem("Save");
JMenuItem newItem = new JMenuItem("New");
JMenuItem exitItem = new JMenuItem("Exit");

menu.add(newItem);
menu.add(openItem);
menu.add(saveItem);
menu.add(exitItem);

JMenu menu1 = new JMenu("Edit");


menuBar.add(menu1);

JMenuItem cutItem = new JMenuItem("Cut");


JMenuItem copyItem = new JMenuItem("Copy");
JMenuItem pasteItem = new JMenuItem("Paste");
JMenuItem selectAllItem = new JMenuItem("Select All");
menu1.add(cutItem);
menu1.add(copyItem);
menu1.add(pasteItem);
menu1.add(selectAllItem);

JMenu menu2 = new JMenu("Help");


menuBar.add(menu2);
JMenuItem aboutItem = new JMenuItem("About");
menu2.add(aboutItem);

chooser = new JFileChooser();

JTextArea tx = new JTextArea(10,10);


add(tx);

//Copy the file


copyItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try{
FileInputStream fis = new FileInputStream("test.txt");

InputStreamReader isr = new InputStreamReader(fis);


BufferedReader br = new BufferedReader(isr);
File a = new File("test.txt");
FileReader fr = new FileReader(a);

File b = new File("Copied.txt");


FileWriter fw = new FileWriter(b);

while(true){
String line = br.readLine();
if(line != null){
System.out.println(line);
4|Page
Prepared By: Hari Rijal (Study Notes Nepal)
www.studynotesnepal.com

} else{

br.close();
break;
}
}
} catch(FileNotFoundException ex){
System.out.println("Error: " + ex.getMessage());
} catch(IOException ex){
System.out.println("Error: " + ex.getMessage());
}
}
});

//Paste the Item


pasteItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try{
FileInputStream fis = new FileInputStream("test.txt");

InputStreamReader isr = new InputStreamReader(fis);


BufferedReader br = new BufferedReader(isr);
File a = new File("test.txt");
FileReader fr = new FileReader(a);

File b = new File("Copied.txt");


FileWriter fw = new FileWriter(b);

while(true){
String line = br.readLine();
if(line != null){
System.out.println(line);

} else{

br.close();
break;
}
}
} catch(FileNotFoundException ex){
System.out.println("Error: " + ex.getMessage());
} catch(IOException ex){
System.out.println("Error: " + ex.getMessage());
}
}
});

//Exit the Menu


exitItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
5|Page
Prepared By: Hari Rijal (Study Notes Nepal)
www.studynotesnepal.com
throw new UnsupportedOperationException("Not supported yet.");
}
});

newItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JTextArea txtArea = new JTextArea(DEFAULT_HEIGHT, DEFAULT_WIDTH);
panel.add(txtArea);
throw new UnsupportedOperationException("Not supported yet."); //To change body of
generated methods, choose Tools | Templates.
}
});
newItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
tx.setText("");
}
});
//code for save item
saveItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showConfirmDialog(rootPane, "Do you want to save ?");

chooser.setCurrentDirectory(new File("/home"));
int result = chooser.showSaveDialog(FileDialogDemo.this);
if(result==JFileChooser.APPROVE_OPTION){
File fileToSave =chooser.getSelectedFile();

try{
FileWriter fw = new FileWriter(fileToSave);
fw.write(tx.getText());
fw.flush();
}
catch(Exception ex){
ex.printStackTrace();
}
}
System.out.println("Result"+result);
}

});
//code for cut
cutItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
cutItem.addActionListener(this);
if(e.getSource()==cutItem)
tx.cut();
throw new UnsupportedOperationException("Not supported yet."); //To change body of
generated methods, choose Tools | Templates.
}
});
//code for copy
6|Page
Prepared By: Hari Rijal (Study Notes Nepal)
www.studynotesnepal.com
copyItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
copyItem.addActionListener(this);
if(e.getSource()==copyItem)
tx.copy();
throw new UnsupportedOperationException("Not supported yet."); //To change body of
generated methods, choose Tools | Templates.
}
});

//code for paste


pasteItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
pasteItem.addActionListener(this);
if(e.getSource()==pasteItem)
tx.paste();
throw new UnsupportedOperationException("Not supported yet."); //To change body of
generated methods, choose Tools | Templates.
}
});
//code for select all
selectAllItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
selectAllItem.addActionListener(this);
if(e.getSource()==selectAllItem)
tx.selectAll();
throw new UnsupportedOperationException("Not supported yet."); //To change body of
generated methods, choose Tools | Templates.
}
});
// code for about
aboutItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {

JOptionPane.showMessageDialog(null,"Notepad Version 1");


throw new UnsupportedOperationException("Not supported yet."); //To change body of
generated methods, choose Tools | Templates.
}
});

//code for open item


openItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
chooser.setCurrentDirectory(new File("/home"));
int result = chooser.showOpenDialog(FileDialogDemo.this);
if(result==JFileChooser.APPROVE_OPTION){
File fileToSave =chooser.getSelectedFile();

try{
7|Page
Prepared By: Hari Rijal (Study Notes Nepal)
www.studynotesnepal.com
FileWriter fw = new FileWriter(fileToSave);
fw.write(tx.getText());
fw.flush();
}
catch(Exception ex){
ex.printStackTrace();
}
}
System.out.println("Result"+result);
}
});
setSize(DEFAULT_WIDTH,DEFAULT_HEIGHT);
setVisible(true);
setTitle("Note Pad");

public static void main (String args[]){


new FileDialogDemo();
}

Output:

5. Write a java program to show the example of Swing Dialog.


//SwingDialogDemo
import javax.swing.*;
public class SwingDialogDemo extends JFrame {
public SwingDialogDemo(){
JPanel panel = new JPanel();
add(panel);
JButton btn = new JButton("Click");
panel.add(btn);
JOptionPane.showMessageDialog(null, "Message Body", "Title",
JOptionPane.ERROR_MESSAGE);
String inputValue = JOptionPane.showInputDialog("Please Input a value");

System.out.println("Input value:"+inputValue);

int selection;

8|Page
Prepared By: Hari Rijal (Study Notes Nepal)
www.studynotesnepal.com
selection = JOptionPane.showConfirmDialog(null, "Message", "Title",
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE);
if(selection == JOptionPane.OK_OPTION){
System.out.println("Ok.....");

}
else{
System.out.print("Cancel...");
}
Object[]possibleValues={"First", "Second", "Third"};
Object selectedValue = JOptionPane.showInputDialog(null, "Choose One", "inputValue",
JOptionPane.INFORMATION_MESSAGE,null,possibleValues,possibleValues[0]);
System.out.println("Selected value:"+selectedValue.toString());

setSize(300,300);
setVisible(true);
}
public static void main(String args[]){
new SwingDialogDemo();
}

Output:

6. Write a Java examples of AWT Components.

9|Page
Prepared By: Hari Rijal (Study Notes Nepal)
www.studynotesnepal.com
//ComponentDemo.java
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class ComponentDemo {
public ComponentDemo(){

Frame frame = new Frame();


frame.setVisible(true);
frame.setSize(300,300);

Checkbox sportChk = new Checkbox ("Sports", true);


Checkbox musicChk =new Checkbox("Music");

Panel panel = new Panel();


frame.add(panel);
panel.add(new Label("Hobbies"));
panel.add(sportChk);
panel.add(musicChk);

System.out.println("Sport is Checked:"+sportChk.getState());
System.out.println("Music is Checked:"+musicChk.getState());

Choice courseChoice = new Choice();


panel.add(courseChoice);

courseChoice.addItem("BIM");
courseChoice.addItem("BSC.CSIT");
courseChoice.addItem("BBA");
courseChoice.addItem("BBM");

courseChoice.select(0);

List semList = new List(2);


semList.add("First");
semList.add("Second");
semList.add("Third");
semList.add("Fourth");

panel.add(semList);

TextArea addressTxtArea = new TextArea (4,6);


panel.add(addressTxtArea);

Scrollbar scrollbar =new Scrollbar(Scrollbar.HORIZONTAL);


frame.add(scrollbar, BorderLayout.SOUTH);

panel.add(scrollbar);

System.out.println("Selected Course:"+courseChoice.getSelectedItem());
frame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
frame.dispose();
10 | P a g e
Prepared By: Hari Rijal (Study Notes Nepal)
www.studynotesnepal.com

}
});
}
public static void main(String args[]){
new ComponentDemo();

}
}

Output:

7. Write a java program to illustrate flow layout.


//FlowLayoutDemo.java
import java.awt.*;
import javax.swing.*;

public class FlowLayoutDemo{


JFrame f;
public FlowLayoutDemo(){
f=new JFrame();

JButton b1=new JButton("1");


JButton b2=new JButton("2");
JButton b3=new JButton("3");
JButton b4=new JButton("4");
JButton b5=new JButton("5");
JButton b6=new JButton("6");
JButton b7=new JButton("7");
JButton b8=new JButton("8");
JButton b9=new JButton("9");

f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
f.add(b6);f.add(b7);f.add(b8);f.add(b9);

f.setLayout(new FlowLayout());
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new FlowLayoutDemo();
}

11 | P a g e
Prepared By: Hari Rijal (Study Notes Nepal)
www.studynotesnepal.com
}
Output:

8. Write a java program to illustrate Border Layout.


//Border.java
import java.awt.*;
import javax.swing.*;

public class Border {


JFrame f;
Border(){
f=new JFrame();

JButton b1=new JButton("NORTH");;


JButton b2=new JButton("SOUTH");;
JButton b3=new JButton("EAST");;
JButton b4=new JButton("WEST");;
JButton b5=new JButton("CENTER");;

f.add(b1,BorderLayout.NORTH);
f.add(b2,BorderLayout.SOUTH);
f.add(b3,BorderLayout.EAST);
f.add(b4,BorderLayout.WEST);
f.add(b5,BorderLayout.CENTER);

f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new Border();
}
}

Output:

12 | P a g e
Prepared By: Hari Rijal (Study Notes Nepal)
www.studynotesnepal.com

9. Write a java program to illustrate GridBag Layout.


//GridBagLayoutExample.java
import java.awt.Button;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;

import javax.swing.*;
public class GridBagLayoutExample extends JFrame{
public static void main(String[] args) {
GridBagLayoutExample a = new GridBagLayoutExample();
}
public GridBagLayoutExample() {
GridBagLayout grid = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
setLayout(grid);
setTitle("GridBag Layout Example");
GridBagLayout layout = new GridBagLayout();
this.setLayout(layout);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = 0;
this.add(new Button("Button One"), gbc);
gbc.gridx = 1;
gbc.gridy = 0;
this.add(new Button("Button two"), gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.ipady = 20;
gbc.gridx = 0;
gbc.gridy = 1;
this.add(new Button("Button Three"), gbc);
gbc.gridx = 1;
gbc.gridy = 1;
this.add(new Button("Button Four"), gbc);
gbc.gridx = 0;
gbc.gridy = 2;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = 2;
this.add(new Button("Button Five"), gbc);
setSize(300, 300);
setPreferredSize(getSize());

13 | P a g e
Prepared By: Hari Rijal (Study Notes Nepal)
www.studynotesnepal.com
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);

Output:

10. Write a java program to illustrate Card Layout.


//CardLayoutExample.java
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("Apple");
b2=new JButton("Boy");
b3=new JButton("Cat");
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
c.add("a",b1);
c.add("b",b2);
c.add("c",b3);
}
public void actionPerformed(ActionEvent e){
card.next(c);
}
public static void main(String[] args) {
CardLayoutExample cl=new CardLayoutExample();
cl.setSize(400,400);
14 | P a g e
Prepared By: Hari Rijal (Study Notes Nepal)
www.studynotesnepal.com
cl.setVisible(true);
cl.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}

Output:

11. Write a java program to illustrate Mouse Listener.


//MouseListenerExample

import java.awt.*;
import java.awt.event.*;
public class MouseListenerExample extends Frame implements MouseListener {
Button b1;
Label l;
MouseListenerExample(){
b1 = new Button ("Click Me");
b1.setBounds(50,50,80,50);
l = new Label();
l.setBounds(60,80,100,100);
b1.addMouseListener(this);
add(b1);
add(l);
setLayout(null);
setSize(300,300);
setVisible(true);

@Override
public void mouseClicked(MouseEvent e) {
l.setText("Mouse Clicked");
}

@Override
15 | P a g e
Prepared By: Hari Rijal (Study Notes Nepal)
www.studynotesnepal.com
public void mousePressed(MouseEvent e) {
l.setText("Mouse pressed");
}

@Override
public void mouseReleased(MouseEvent e) {
l.setText("Mouse Released");
}

@Override
public void mouseEntered(MouseEvent e) {
l.setText("Mouse Entered");
}

@Override
public void mouseExited(MouseEvent e) {
l.setText("Mouse Exited");
}
public static void main(String args[]){
new MouseListenerExample();
}

Output:

12. Write a java program to illustrate window listener.


//WindowEventTest.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class WindowEventTest extends WindowAdapter {
JFrame frame;
public WindowEventTest(){
frame=new JFrame();
frame.setTitle("Handling Window Event");
frame.addWindowListener(this);
frame.setSize(400,300);
frame.setVisible(true);

}
public void windowClosing(WindowEvent we){
16 | P a g e
Prepared By: Hari Rijal (Study Notes Nepal)
www.studynotesnepal.com
JOptionPane.showMessageDialog(frame,"Good Byeeeee.........");
System.exit(1);
}
public void windowOpened(WindowEvent we){
JOptionPane.showMessageDialog(frame,"Wel-Come");
}
public void windowIconified(WindowEvent we){
JOptionPane.showMessageDialog(frame,"See You Later...........");
}
public void windowDeiconified(WindowEvent we){
JOptionPane.showMessageDialog(frame, "Wel-Come Back.........");
}
public static void main(String args[]){
new WindowEventTest();
}
}
Output:

13. Write a java program to make a simple bank system.


//BankSoftwareDemo.java
import java.awt.Frame;
import java.awt.Panel;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JOptionPane;

import java.awt.*;
import java.awt.event.*;

public class BankSoftwareDemo {


public BankSoftwareDemo() {
Frame frame = new Frame();
frame.setVisible(true);
frame.setSize(200,200);
frame.setTitle("Bank Software");
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});

17 | P a g e
Prepared By: Hari Rijal (Study Notes Nepal)
www.studynotesnepal.com
Label bankName = new Label("ABC Bank");

Label customerName = new Label("Customer Name:");


TextField inputCname = new TextField(5);

Label accountType = new Label("Accout Type:");


Choice accountChoice = new Choice();
accountChoice.addItem("Saving");
accountChoice.addItem("Current");

Label deposit = new Label("Deposit:");


TextField depositValue = new TextField(5);

Label withdraw = new Label("Withdraw:");


TextField withdrawValue = new TextField(5);

Button btnSave = new Button("Save");

Label finalBalance = new Label("Your Balance is:");


TextField bankBalanceShow = new TextField(5);

Panel panel = new Panel();


panel.add(bankName);
panel.add(customerName);
panel.add(inputCname);
panel.add(accountType);
panel.add(accountChoice);
panel.add(deposit);
panel.add(depositValue);
panel.add(withdraw);
panel.add(withdrawValue);
panel.add(btnSave);
panel.add(finalBalance);
panel.add(bankBalanceShow);

btnSave.addActionListener(new ActionListener(){

@Override
public void actionPerformed(ActionEvent e) {
String deposit = depositValue.getText();
// int deposit_result = Integer.parseInt(deposit);

String withdraw = withdrawValue.getText();


// int withdraw_result = Integer.parseInt(withdraw);

Integer bankBalance = Integer.parseInt(deposit) -


Integer.parseInt(withdraw);
JOptionPane.showMessageDialog(null,"Bank Balance:"
+bankBalance);
bankBalanceShow.setText(bankBalance.toString());

18 | P a g e
Prepared By: Hari Rijal (Study Notes Nepal)
www.studynotesnepal.com
});

frame.add(panel);

}
public static void main(String[] args) {
new BankSoftwareDemo();
}
}
Output:

14. Write a Java program to insert the data in database. Make your own assumptions about
the database and table.
//InsertionDemo.java
package database;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class InsertionDemo {


public static void main (String args[]) throws ClassNotFoundException, SQLException{
Class.forName("com.mysql.cj.jdbc.Driver");
System.out.println("Driver loaded");
Connection con=
DriverManager.getConnection("jdbc:mysql://localhost/asian?useUnicode=true&useJDBCCompliantT
imezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC","root","");
String sql ="INSERT INTO BIM(ID,NAME,DOB, EMAIL) VALUES(?,?,?,?)";

PreparedStatement ps = con.prepareStatement(sql);

ps.setInt(1, 100);
ps.setString(2, "Hari Rijal");
ps.setString(3, "1997-08-02");
19 | P a g e
Prepared By: Hari Rijal (Study Notes Nepal)
www.studynotesnepal.com
ps.setString(4,"reezalharee2015@gmail.com");
ps.executeUpdate();
System.out.println("Insertion success.");

}
}

Output:

15. Write a Java program to display the data from table BIM. Make your own assumptions
about the database.
//Display.java
package database;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

class Display {
public static void main (String args[]) throws ClassNotFoundException, SQLException{
Statement stmt;
ResultSet rs;
Class.forName("com.mysql.cj.jdbc.Driver");
System.out.println("Driver loaded");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost/asian?useUnicode=true&useJDBCCompliantT
imezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC","root","");
System.out.println("connection to mysql");
stmt = con.createStatement();
String sql ="select * from bim";
rs = stmt.executeQuery(sql);
while(rs.next()){
System.out.println("ID:"+rs.getString("ID"));
System.out.println("Name"+rs.getString("Name"));
System.out.println("DOB:"+rs.getString("DOB"));
System.out.println("Email:"+rs.getString("Email"));

}
}
}

Output:

20 | P a g e
Prepared By: Hari Rijal (Study Notes Nepal)
www.studynotesnepal.com

16. Write a Java program to update the data from table BIM and set the name Karan whose id
is 101. Make your own assumptions about the database.
//UpdateDemo.java
package database;
import java.sql.*;
public class UpdateDemo {
public static void main (String args[]) throws ClassNotFoundException, SQLException{
Class.forName("com.mysql.cj.jdbc.Driver");
System.out.println("Driver loaded");
Connection con=
DriverManager.getConnection("jdbc:mysql://localhost/asian?useUnicode=true&useJDBCCompliantT
imezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC","root","");
System.out.println("Connecton sucess");
String sql = "update bim set NAME = ? where ID =?";

PreparedStatement preparedStatement = con.prepareStatement(sql);


preparedStatement.setString(1,"Karan");
preparedStatement.setInt(2,101);
int result =preparedStatement.executeUpdate();
System.out.println("Affected rows:"+result);
}
}

Output:

17. Write a Java program to delete the details from table BIM whose id is 2. Make your own
assumptions about the database.
//DeleteDemo.java
package database;
import java.sql.*;
public class DeleteDemo {
public static void main (String args[]) throws ClassNotFoundException, SQLException{
Class.forName("com.mysql.cj.jdbc.Driver");
System.out.println("Driver loaded");

21 | P a g e
Prepared By: Hari Rijal (Study Notes Nepal)
www.studynotesnepal.com
Connection con=
DriverManager.getConnection("jdbc:mysql://localhost/asian?useUnicode=true&useJDBCCompliantT
imezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC","root","");

String sql = "delete from bim where ID =?";

PreparedStatement preparedStatement = con.prepareStatement(sql);

preparedStatement.setInt(1,2);
preparedStatement.executeUpdate();
System.out.println("Item was droped");
}
}

Output:

18. Write a servlet program to set session.


//SessionForm.html
html>
<head>
<title>Session Form</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="SetSession" method="POST">
Name: <input type ="text" name="name">
<input type ="submit" value="Go">
</form>
</body>
</html>

//SetSession.java

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

public class SetSession extends HttpServlet{

public void doPost(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n = request.getParameter("name");
out.print("Welcome"+n);
22 | P a g e
Prepared By: Hari Rijal (Study Notes Nepal)
www.studynotesnepal.com
HttpSession session =request.getSession();
session.setAttribute("name", n);
out.print("<a href='ReadSession.java'> Visit Here</a>");

//ReadSession.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class ReadSession extends HttpServlet {


public void doPost(HttpServletRequest request, HttpServletResponse response)throws
ServletException, IOException{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
HttpSession session = request.getSession(false);
String n=(String)session.getAttribute("name");
out.print("Hello"+n);
out.close();
}
}

//web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<servlet>
<servlet-name>SetSession</servlet-name>
<servlet-class>SetSession</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SetSession</servlet-name>
<url-pattern>/SetSession</url-pattern>
</servlet-mapping>

<servlet>
<servlet-name>ReadSession</servlet-name>
<servlet-class>ReadSession</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ReadSession</servlet-name>
<url-pattern>/ReadSession</url-pattern>
</servlet-mapping>

<session-config>
23 | P a g e
Prepared By: Hari Rijal (Study Notes Nepal)
www.studynotesnepal.com
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>

Output:

19. Write a Servlet program to set Cookie.


//SetCookie.java
import javax.servlet.http.*;
import java.io.*;
public class SetCookie extends HttpServlet{
public void doGet(HttpServletRequest request,HttpServletResponse response)
{
response.setContentType("text/html");
try{
PrintWriter pw = response.getWriter();
Cookie c1 = new Cookie("FirstName", "abc");
c1.setMaxAge(24*60*60);
Cookie c2 = new Cookie("SecondName", "bcd");
c2.setMaxAge(24*60*60);
response.addCookie(c1);
response.addCookie(c2);
pw.println("Hello user cookie has been set to your computer");

pw.close();

}
catch(Exception ex){

System.out.println(ex);
}
}
}

//web.xml
<servlet>
<servlet-name>SetCookie</servlet-name>
<servlet-class>SetCookie</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SetCookie</servlet-name>
<url-pattern>/SetCookie</url-pattern>
</servlet-mapping>

Output:

24 | P a g e
Prepared By: Hari Rijal (Study Notes Nepal)
www.studynotesnepal.com

20. Write a JSP program to print odd number from 10 to 50.


//OddNumber.jsp
<html>
<head>
<title>Printing odd numbers from 10 to 50</title>
</head>
<body>
<% out.print("<b> odd numbers from 10 to 50</><br>");
for( int i=10;i<=50;i++) {
if(i%2!=0){
out.print("<br><b>"+i+"</b>");
}
}
%>
</body>
</html>

Output:

21. Write a JSP program to add two numbers if they are even, if numbers are not even just display
their numbers.
//CheckNumber.html
<body>
<form action="CheckNumber.jsp" method="GET">
First Number: <input type="number" name="first">
Second Number: <input type="number" name="second">
<input type="submit" value=" Add">
</form>
</body>
//CheckNumber.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
25 | P a g e
Prepared By: Hari Rijal (Study Notes Nepal)
www.studynotesnepal.com
<body>
<%
int x= Integer.parseInt(request.getParameter("first"));
int y = Integer.parseInt(request.getParameter("second"));

if(x%2==0 && y%2==0){


int z=x+y;
out.println("Both the number are even and the sum is:"+z);
}

else{
out.println("Both the number are not even and entered numbers are:"+x+"and "+y+"");
}

%>
</body>
</html>

Output:

22. Write a JSP program to print "Apache Tomcat" eight times.


//Tomcat.jsp
<html>
<head>

</head>
<body>
<%
for(int i = 1; i <= 8; i++) {
out.println("Apache Tomcat <br />");
}
%>
</body>
</html>

Output:

23. Create a HTML document that contains header information of a page and include this HTML as a
header file in header.html.
//header.html
<!DOCTYPE html>
<html>
26 | P a g e
Prepared By: Hari Rijal (Study Notes Nepal)
www.studynotesnepal.com
<head>
<title>Insert title here</title>
</head>
<body>
<center>
<h1>Asian School of Management and Technology</h1>
<h3>Gongabu, Kathmandu</h3>
</center>
</body>
</html>

//headerinclude.jsp
<html>
<body>
<%@include file = "header.html" %>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut
labore et dolore magna aliqua.

</p></body>
</html>

Output:

24. Create a JSP that takes an integer from HTML and display its reverse.
//Reverse.html
<html>
<body>
<form action = "Reverse.jsp">
Enter a number: <input type = "number" name = "number" />
<input type = "submit" value="Go" />
</form>
</body>
</html>

//Reverse.jsp
<html>
<body>
<%
int num = Integer.parseInt(request.getParameter("number"));
int rev = 0, rem;
while(num > 0){
rem = num % 10;
rev = rem + rev * 10;
num = num / 10;
}

27 | P a g e
Prepared By: Hari Rijal (Study Notes Nepal)
www.studynotesnepal.com
out.println("Reverse is: "+rev);
%>
</body>
</html>

Output:

25. Write a JSP to print the current server time.


//useBean.jsp

<html>
<head>

<title>JSP useBean</title>
</head>
<body>
<jsp:useBean id="date" class="java.util.Date"/>
<p> The Date / Time is <%=date %></p>
</body>
</html>

Output:

26. Write a JSP example that handle the JSP Exception.


//JSPException.jsp
<%@page errorPage="error.jsp" %>
<%
int a=10;
int b=0;
int c=a/b;
out.println("division of numbers is :"+c);
%>

//error.jsp
<%@page isErrorPage="true" %>
<h3>Sorry an exception occured ! </h3>
Exception is : <%= exception.getMessage() %>

Output:

28 | P a g e
Prepared By: Hari Rijal (Study Notes Nepal)

You might also like