Advance Java Lab Programs

BCA 6th Semester TU · 32 laboratory experiments in a clean, searchable, collapsible format.

32Lab Programs
5Units
17Swing / GUI Labs
15JDBC, Beans, Web & RMI

Program / Code

import javax.swing.*; 
 
public class CreateFrame { 
    public static void main(String[] args) { 
        JFrame frame = new JFrame("Simple Frame"); 
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
        frame.setSize(400, 300); 
        frame.setVisible(true); 
    } 
}

Expected Output

  • A window (frame) titled "Simple Frame" appears on the screen with dimensions 400x300 pixels.
  • The frame has a default close operation (clicking the close button exits the application).

Program / Code

import javax.swing.*; 
import java.awt.*; 
 
public class PositionFrame { 
    public static void main(String[] args) { 
        JFrame frame = new JFrame("Positioned Frame"); 
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
        frame.setSize(400, 300); 
        frame.setLocation(100, 100); // Position at (100, 100) 
        frame.setResizable(false); // Frame property: non-resizable 
        frame.setVisible(true); 
    } 
}

Expected Output

  • A window titled "Positioned Frame" appears at coordinates (100, 100) on the screen with
  • dimensions 400x300 pixels.
  • The frame cannot be resized (resizable property set to false).

Program / Code

import javax.swing.*; 
import java.awt.*; 
 
public class DisplayInfoComponent extends JPanel { 
    @Override 
    protected void paintComponent(Graphics g) { 
        super.paintComponent(g); 
        g.drawString("Hello, this is a custom component!", 50, 50); 
    } 
 
    public static void main(String[] args) { 
        JFrame frame = new JFrame("Display Info"); 
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
        frame.setSize(300, 200); 
        frame.add(new DisplayInfoComponent()); 
        frame.setVisible(true); 
    } 
}

Expected Output

  • A window titled "Display Info" appears with dimensions 300x200 pixels.
  • Inside the window, the text "Hello, this is a custom component!" is displayed at coordinates (50,
  • 50).

Program / Code

import javax.swing.*; 
import java.awt.*; 
import java.awt.geom.*; 
 
public class DrawShapes extends JPanel { 
    @Override 
    protected void paintComponent(Graphics g) { 
        super.paintComponent(g); 
Graphics2D g2d = (Graphics2D) g; 
        g2d.draw(new Rectangle2D.Double(50, 50, 100, 80)); 
        g2d.draw(new Ellipse2D.Double(160, 50, 100, 80)); 
    } 
 
    public static void main(String[] args) { 
        JFrame frame = new JFrame("2D Shapes"); 
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
        frame.setSize(300, 200); 
        frame.add(new DrawShapes()); 
        frame.setVisible(true); 
    } 
}

Expected Output

  • A window titled "2D Shapes" appears with dimensions 300x200 pixels.
  • Inside the window:
  • A rectangle is drawn at (50, 50) with width 100 and height 80.
  • An ellipse is drawn at (160, 50) with width 100 and height 80.

Program / Code

import javax.swing.*; 
import java.awt.*; 
 
public class UseColor extends JPanel { 
    @Override 
    protected void paintComponent(Graphics g) { 
        super.paintComponent(g); 
        g.setColor(Color.BLUE); 
        g.fillRect(50, 50, 100, 80); 
        g.setColor(Color.RED); 
        g.drawString("Colored Text", 50, 150); 
    } 
 
    public static void main(String[] args) { 
        JFrame frame = new JFrame("Use Color"); 
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
        frame.setSize(300, 200); 
        frame.add(new UseColor()); 
        frame.setVisible(true); 
    } 
}

Expected Output

  • A window titled "Use Color" appears with dimensions 300x200 pixels.
  • Inside the window:
  • A blue filled rectangle is drawn at (50, 50) with width 100 and height 80.
  • The text "Colored Text" in red is displayed at (50, 150).

Program / Code

import javax.swing.*; 
import java.awt.*; 
 
public class SpecialFonts extends JPanel { 
    @Override 
    protected void paintComponent(Graphics g) { 
        super.paintComponent(g); 
        Font font = new Font("Serif", Font.BOLD | Font.ITALIC, 20); 
        g.setFont(font); 
        g.drawString("Special Font Text", 50, 50); 
    } 
 
    public static void main(String[] args) { 
        JFrame frame = new JFrame("Special Fonts"); 
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
        frame.setSize(300, 200); 
        frame.add(new SpecialFonts()); 
        frame.setVisible(true); 
    } 
}

Expected Output

  • A window titled "Special Fonts" appears with dimensions 300x200 pixels.
  • Inside the window, the text "Special Font Text" is displayed at (50, 50) in a bold, italic Serif font
  • with size 20.

Program / Code

import javax.swing.*; 
import java.awt.*; 
 
public class DisplayImage extends JPanel { 
    private Image image; 
 
    public DisplayImage() { 
        // Replace "path/to/image.jpg" with the actual path to an image file 
        image = new ImageIcon("path/to/image.jpg").getImage(); 
    } 
 
    @Override 
    protected void paintComponent(Graphics g) { 
        super.paintComponent(g); 
        if (image != null) { 
            g.drawImage(image, 50, 50, this); 
        } else { 
            g.drawString("Image not found!", 50, 50); 
        } 
    } 
 
    public static void main(String[] args) { 
        JFrame frame = new JFrame("Display Image"); 
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
        frame.setSize(300, 300); 
        frame.add(new DisplayImage()); 
        frame.setVisible(true); 
    } 
}

Expected Output

  • A window titled "Display Image" appears with dimensions 300x300 pixels.
  • If the image file is found, the image is displayed at (50, 50).
  • If the image file is not found, the text "Image not found!" is displayed at (50, 50).

Program / Code

import javax.swing.*; 
import java.awt.event.*; 
 
public class EventHandling { 
    public static void main(String[] args) { 
        JFrame frame = new JFrame("Event Handling"); 
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
        frame.setSize(300, 200); 
 
        JButton button = new JButton("Click Me"); 
        button.addActionListener(e -> JOptionPane.showMessageDialog(frame, "Button Clicked!")); 
        frame.add(button); 
 
        frame.addWindowListener(new WindowAdapter() { 
            @Override 
            public void windowClosing(WindowEvent e) { 
                System.out.println("Window is closing..."); 
            } 
        }); 
 
        frame.setVisible(true); 
    } 
}

Expected Output

  • A window titled "Event Handling" appears with dimensions 300x200 pixels.
  • A button labeled "Click Me" is displayed in the center.
  • Clicking the button shows a dialog box with the message "Button Clicked!".
  • When the window is closed, the console prints: Window is closing....

Program / Code

import javax.swing.*; 
import java.awt.event.*; 
 
// Model 
class CounterModel { 
    private int counter = 0; 
 
    public void increment() { 
        counter++; 
    } 
 
    public int getValue() { 
        return counter; 
    } 
} 
 
// View 
class CounterView extends JFrame { 
    private JLabel label; 
    private JButton button; 
 
    public CounterView() { 
        setTitle("MVC Counter"); 
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
        setSize(300, 200); 
 
        label = new JLabel("Counter: 0"); 
        button = new JButton("Increment"); 
        setLayout(new java.awt.FlowLayout()); 
        add(label); 
        add(button); 
    } 
 
    public JButton getButton() { 
        return button; 
    } 
 
    public void updateLabel(int value) { 
        label.setText("Counter: " + value); 
    } 
} 
 
// Controller 
class CounterController { 
    private CounterModel model; 
    private CounterView view; 
 
    public CounterController(CounterModel model, CounterView view) { 
        this.model = model; 
        this.view = view; 
 
        view.getButton().addActionListener(e -> { 
model.increment(); 
            view.updateLabel(model.getValue()); 
        }); 
    } 
} 
 
public class MVCCounter { 
    public static void main(String[] args) { 
        CounterModel model = new CounterModel(); 
        CounterView view = new CounterView(); 
        new CounterController(model, view); 
        view.setVisible(true); 
    } 
}

Expected Output

  • A window titled "MVC Counter" appears with dimensions 300x200 pixels.
  • The window contains a label displaying "Counter: 0" and a button labeled "Increment".
  • Each time the "Increment" button is clicked, the counter value increases by 1, and the label
  • updates (e.g., "Counter: 1", "Counter: 2", etc.).

Program / Code

import javax.swing.*; 
import java.awt.*; 
 
public class BorderLayoutDemo { 
    public static void main(String[] args) { 
        JFrame frame = new JFrame("Border Layout Demo"); 
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
        frame.setSize(400, 300); 
 
        frame.setLayout(new BorderLayout()); 
        frame.add(new JButton("North"), BorderLayout.NORTH); 
        frame.add(new JButton("South"), BorderLayout.SOUTH); 
        frame.add(new JButton("East"), BorderLayout.EAST); 
        frame.add(new JButton("West"), BorderLayout.WEST); 
        frame.add(new JButton("Center"), BorderLayout.CENTER); 
frame.setVisible(true); 
    } 
}

Expected Output

  • A window titled "Border Layout Demo" appears with dimensions 400x300 pixels.
  • The window is divided into five regions:
  • A "North" button at the top.
  • A "South" button at the bottom.
  • An "East" button on the right.
  • A "West" button on the left.
  • A "Center" button in the middle.

Program / Code

import javax.swing.*; 
import java.awt.*; 
 
public class GridLayoutDemo { 
    public static void main(String[] args) { 
        JFrame frame = new JFrame("Grid Layout Demo"); 
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
        frame.setSize(400, 300); 
 
        frame.setLayout(new GridLayout(2, 3)); // 2 rows, 3 columns 
        frame.add(new JButton("Button 1")); 
        frame.add(new JButton("Button 2")); 
        frame.add(new JButton("Button 3")); 
        frame.add(new JButton("Button 4")); 
        frame.add(new JButton("Button 5")); 
        frame.add(new JButton("Button 6")); 
 
        frame.setVisible(true); 
    } 
}

Expected Output

  • A window titled "Grid Layout Demo" appears with dimensions 400x300 pixels.
  • The window contains a 2x3 grid of buttons labeled "Button 1" to "Button 6", arranged as:
  • Row 1: Button 1, Button 2, Button 3
  • Row 2: Button 4, Button 5, Button 6

Program / Code

import javax.swing.*; 
import java.awt.*; 
 
public class TextFieldDemo { 
    public static void main(String[] args) { 
        JFrame frame = new JFrame("Text Field Demo"); 
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
        frame.setSize(300, 200); 
        frame.setLayout(new GridLayout(3, 2)); 
 
        frame.add(new JLabel("Name:")); 
        frame.add(new JTextField(10)); 
        frame.add(new JLabel("Password:")); 
        frame.add(new JPasswordField(10)); 
        frame.add(new JLabel("Status:")); 
        frame.add(new JLabel("Enter your details")); 
 
        frame.setVisible(true); 
    } 
}

Expected Output

  • A window titled "Text Field Demo" appears with dimensions 300x200 pixels.
  • The window contains:
  • A label "Name:" followed by a text field.
  • A label "Password:" followed by a password field (text is hidden as dots).
  • A label "Status:" followed by another label "Enter your details".

Program / Code

import javax.swing.*; 
 
public class TextAreaDemo { 
    public static void main(String[] args) { 
        JFrame frame = new JFrame("Text Area Demo"); 
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
        frame.setSize(300, 200); 
 
        JTextArea textArea = new JTextArea(5, 20); 
        JScrollPane scrollPane = new JScrollPane(textArea); 
        frame.add(scrollPane); 
 
        frame.setVisible(true); 
    } 
}

Expected Output

  • A window titled "Text Area Demo" appears with dimensions 300x200 pixels.
  • The window contains a text area inside a scroll pane, allowing the user to type and scroll if the
  • text exceeds the visible area.

Program / Code

import javax.swing.*; 
import java.awt.*; 
 
public class CheckBoxRadioDemo { 
    public static void main(String[] args) { 
        JFrame frame = new JFrame("Checkbox and Radio Button Demo"); 
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
        frame.setSize(300, 200); 
        frame.setLayout(new GridLayout(3, 1)); 
 
        JCheckBox checkBox = new JCheckBox("I agree to terms"); 
        frame.add(checkBox); 
 
        JRadioButton radio1 = new JRadioButton("Option 1"); 
        JRadioButton radio2 = new JRadioButton("Option 2"); 
        ButtonGroup group = new ButtonGroup(); 
        group.add(radio1); 
        group.add(radio2); 
        frame.add(radio1); 
        frame.add(radio2); 
 
        frame.setVisible(true); 
    } 
}

Expected Output

  • A window titled "Checkbox and Radio Button Demo" appears with dimensions 300x200 pixels.
  • The window contains:
  • A checkbox labeled "I agree to terms".
  • Two radio buttons labeled "Option 1" and "Option 2" (only one can be selected at a time).

Program / Code

import javax.swing.*; 
import java.awt.*; 
 
public class ComboSliderDemo { 
    public static void main(String[] args) { 
        JFrame frame = new JFrame("Combo Box and Slider Demo"); 
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
frame.setSize(300, 200); 
        frame.setLayout(new GridLayout(2, 1)); 
 
        String[] options = {"Option 1", "Option 2", "Option 3"}; 
        JComboBox<String> comboBox = new JComboBox<>(options); 
        frame.add(comboBox); 
 
        JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 100, 50); 
        slider.setMajorTickSpacing(20); 
        slider.setPaintTicks(true); 
        slider.setPaintLabels(true); 
        frame.add(slider); 
 
        frame.setVisible(true); 
    } 
}

Expected Output

  • A window titled "Combo Box and Slider Demo" appears with dimensions 300x200 pixels.
  • The window contains:
  • A combo box with options "Option 1", "Option 2", and "Option 3".
  • A horizontal slider ranging from 0 to 100, with the initial value set to 50, and tick
  • marks/labels at intervals of 20.

Program / Code

import javax.swing.*; 
import java.awt.*; 
 
public class MenuDemo { 
    public static void main(String[] args) { 
        JFrame frame = new JFrame("Menu Demo"); 
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
        frame.setSize(300, 200); 
 
JMenuBar menuBar = new JMenuBar(); 
        JMenu fileMenu = new JMenu("File"); 
 
        JMenuItem openItem = new JMenuItem("Open", new ImageIcon("path/to/icon.png")); // Replace with actual 
icon path 
        fileMenu.add(openItem); 
 
        JCheckBoxMenuItem checkItem = new JCheckBoxMenuItem("Check Option"); 
        fileMenu.add(checkItem); 
 
        JRadioButtonMenuItem radio1 = new JRadioButtonMenuItem("Radio Option 1"); 
        JRadioButtonMenuItem radio2 = new JRadioButtonMenuItem("Radio Option 2"); 
        ButtonGroup group = new ButtonGroup(); 
        group.add(radio1); 
        group.add(radio2); 
        fileMenu.add(radio1); 
        fileMenu.add(radio2); 
 
        menuBar.add(fileMenu); 
        frame.setJMenuBar(menuBar); 
        frame.setVisible(true); 
    } 
}

Expected Output

  • A window titled "Menu Demo" appears with dimensions 300x200 pixels.
  • The window has a menu bar with a "File" menu.
  • The "File" menu contains:
  • An "Open" menu item with an icon (if the icon path is valid).
  • A checkbox menu item labeled "Check Option".
  • Two radio button menu items labeled "Radio Option 1" and "Radio Option 2" (only one
  • can be selected at a time).

Program / Code

import javax.swing.*; 
import java.awt.*; 
import java.awt.event.*; 
 
public class AdvancedMenuDemo { 
    public static void main(String[] args) { 
        JFrame frame = new JFrame("Advanced Menu Demo"); 
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
        frame.setSize(400, 300); 
 
        // Toolbar 
        JToolBar toolBar = new JToolBar(); 
        JButton toolButton = new JButton("Tool"); 
        toolButton.setToolTipText("This is a toolbar button"); 
        toolBar.add(toolButton); 
        frame.add(toolBar, BorderLayout.NORTH); 
 
        // Pop-up Menu 
        JPopupMenu popupMenu = new JPopupMenu(); 
        JMenuItem popupItem = new JMenuItem("Popup Item"); 
        popupMenu.add(popupItem); 
 
        frame.addMouseListener(new MouseAdapter() { 
            @Override 
            public void mousePressed(MouseEvent e) { 
                if (e.isPopupTrigger()) { 
                    popupMenu.show(e.getComponent(), e.getX(), e.getY()); 
                } 
            } 
        }); 
 
        // Menu with Mnemonics and Accelerators 
        JMenuBar menuBar = new JMenuBar(); 
        JMenu fileMenu = new JMenu("File"); 
        fileMenu.setMnemonic(KeyEvent.VK_F); // Mnemonic: Alt+F 
 
        JMenuItem openItem = new JMenuItem("Open"); 
        openItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, InputEvent.CTRL_DOWN_MASK)); // 
Accelerator: Ctrl+O 
        fileMenu.add(openItem); 
 
        menuBar.add(fileMenu); 
        frame.setJMenuBar(menuBar); 
 
        frame.setVisible(true); 
    } 
}

Expected Output

  • A window titled "Advanced Menu Demo" appears with dimensions 400x300 pixels.
  • The window contains:
  • A toolbar at the top with a button labeled "Tool". Hovering over the button shows a
  • tooltip "This is a toolbar button".
  • A menu bar with a "File" menu (accessible via Alt+F).
  • The "File" menu contains an "Open" item (accessible via Ctrl+O).
  • Right-clicking anywhere in the window shows a pop-up menu with a "Popup Item".
  • Solutions and Outputs for Experiments 18 to 25

Setup / Requirements

Ensure you have MySQL installed and running. 
Create a database named testdb and a table named users with the following schema: 
sql 
 
 
 
CREATE DATABASE testdb; 
USE testdb; 
CREATE TABLE users ( 
    id INT AUTO_INCREMENT PRIMARY KEY, 
    name VARCHAR(50), 
    email VARCHAR(50) 
); 
INSERT INTO users (name, email) VALUES ('Alice', 'alice@example.com'); 
Add the MySQL JDBC driver to your project (e.g., via Maven): 
xml 
 
 
 
<dependency> 
    <groupId>mysql</groupId> 
    <artifactId>mysql-connector-java</artifactId> 
    <version>8.0.33</version> 
</dependency>

Program / Code

import java.sql.*; 
 
public class SimpleJDBCQuery { 
    public static void main(String[] args) { 
        String url = "jdbc:mysql://localhost:3306/testdb?useSSL=false"; 
        String user = "root"; // Replace with your MySQL username 
        String password = "password"; // Replace with your MySQL password 
 
        try { 
            // Load the JDBC driver 
            Class.forName("com.mysql.cj.jdbc.Driver"); 
 
            // Establish connection 
            Connection conn = DriverManager.getConnection(url, user, password); 
            System.out.println("Connected to database"); 
 
            // Create a statement 
            Statement stmt = conn.createStatement(); 
 
            // Execute a simple query 
            String sql = "SELECT * FROM users"; 
            ResultSet rs = stmt.executeQuery(sql); 
 
            // Process the result set 
            while (rs.next()) { 
                int id = rs.getInt("id"); 
                String name = rs.getString("name"); 
                String email = rs.getString("email"); 
                System.out.println("ID: " + id + ", Name: " + name + ", Email: " + email); 
            } 
 
            // Close resources 
            rs.close(); 
            stmt.close(); 
            conn.close(); 
        } catch (Exception e) { 
            e.printStackTrace(); 
        } 
    } 
}

Expected Output

  • Connected to database
  • ID: 1, Name: Alice, Email: alice@example.com

Program / Code

import java.sql.*; 
 
public class JDBCStatements { 
    public static void main(String[] args) { 
        String url = "jdbc:mysql://localhost:3306/testdb?useSSL=false"; 
        String user = "root"; // Replace with your MySQL username 
        String password = "password"; // Replace with your MySQL password 
 
        try { 
            // Load the JDBC driver 
            Class.forName("com.mysql.cj.jdbc.Driver"); 
 
            // Establish connection 
            Connection conn = DriverManager.getConnection(url, user, password); 
            System.out.println("Connected to database"); 
 
            // Create a statement 
            Statement stmt = conn.createStatement(); 
 
            // Insert a new record 
            String insertSQL = "INSERT INTO users (name, email) VALUES ('Bob', 'bob@example.com')" ; 
            int rowsAffected = stmt.executeUpdate(insertSQL); 
            System.out.println("Rows inserted: " + rowsAffected); 
 
            // Query the table 
            String selectSQL = "SELECT * FROM users WHERE name = 'Bob'"; 
            ResultSet rs = stmt.executeQuery(selectSQL); 
 
// Process the result set 
            while (rs.next()) { 
                int id = rs.getInt("id"); 
                String name = rs.getString("name"); 
                String email = rs.getString("email"); 
                System.out.println("ID: " + id + ", Name: " + name + ", Email: " + email); 
            } 
 
            // Close resources 
            rs.close(); 
            stmt.close(); 
            conn.close(); 
        } catch (Exception e) { 
            e.printStackTrace(); 
        } 
    } 
}

Expected Output

  • Connected to database
  • Rows inserted: 1
  • ID: 2, Name: Bob, Email: bob@example.com

Program / Code

import java.sql.*; 
 
public class ScrollableResultSet { 
    public static void main(String[] args) { 
        String url = "jdbc:mysql://localhost:3306/testdb?useSSL=false"; 
        String user = "root"; // Replace with your MySQL username 
        String password = "password"; // Replace with your MySQL password 
 
try { 
            // Load the JDBC driver 
            Class.forName("com.mysql.cj.jdbc.Driver"); 
 
            // Establish connection 
            Connection conn = DriverManager.getConnection(url, user, password); 
            System.out.println("Connected to database"); 
 
            // Create a scrollable and updatable statement 
            Statement stmt = conn.createStatement( 
                ResultSet.TYPE_SCROLL_INSENSITIVE, 
                ResultSet.CONCUR_UPDATABLE 
            ); 
 
            // Query the table 
            ResultSet rs = stmt.executeQuery("SELECT * FROM users"); 
 
            // Move to the last row and display 
            rs.last(); 
            System.out.println("Last row: ID: " + rs.getInt("id") + ", Name: " + rs.getString("name")); 
 
            // Move to the first row and display 
            rs.first(); 
            System.out.println("First row: ID: " + rs.getInt("id") + ", Name: " + rs.getString("name")); 
 
            // Update the first row 
            rs.updateString("email", "alice.updated@example.com"); 
            rs.updateRow(); 
            System.out.println("Updated first row email to: " + rs.getString("email")); 
 
            // Close resources 
            rs.close(); 
            stmt.close(); 
            conn.close(); 
        } catch (Exception e) { 
            e.printStackTrace(); 
        } 
    } 
}

Expected Output

  • Connected to database
  • Last row: ID: 2, Name: Bob
  • First row: ID: 1, Name: Alice
  • Updated first row email to: alice.updated@example.com

Program / Code

import javax.sql.rowset.*; 
 
public class RowSetDemo { 
    public static void main(String[] args) { 
        try { 
            // Create a JdbcRowSet 
            JdbcRowSet rowSet = RowSetProvider.newFactory().createJdbcRowSet();  
 
            // Configure the RowSet 
            rowSet.setUrl("jdbc:mysql://localhost:3306/testdb?useSSL=false"); 
            rowSet.setUsername("root"); // Replace with your MySQL username 
            rowSet.setPassword("password"); // Replace with your MySQL password 
            rowSet.setCommand("SELECT * FROM users"); 
            rowSet.execute(); 
 
            // Iterate through the RowSet 
            System.out.println("RowSet contents:"); 
            while (rowSet.next()) { 
                int id = rowSet.getInt("id"); 
                String name = rowSet.getString("name"); 
                String email = rowSet.getString("email"); 
                System.out.println("ID: " + id + ", Name: " + name + ", Email: " + email); 
            } 
 
            // Close the RowSet 
            rowSet.close(); 
        } catch (Exception e) { 
            e.printStackTrace(); 
        } 
    } 
}

Expected Output

  • RowSet contents:
  • ID: 1, Name: Alice, Email: alice.updated@example.com
  • ID: 2, Name: Bob, Email: bob@example.com

Program / Code

import java.io.Serializable; 
 
// Java Bean class 
public class UserBean implements Serializable { 
    private int id; 
    private String name; 
 
    // Default constructor 
    public UserBean() { 
    } 
 
    // Getters and setters 
    public int getId() { 
        return id; 
    } 
 
    public void setId(int id) { 
        this.id = id; 
    } 
 
    public String getName() { 
        return name; 
    } 
 
    public void setName(String name) { 
        this.name = name; 
    } 
} 
 
// Test class 
class UserBeanTest { 
    public static void main(String[] args) { 
        UserBean user = new UserBean(); 
        user.setId(1); 
        user.setName("Alice"); 
 
        System.out.println("User ID: " + user.getId()); 
        System.out.println("User Name: " + user.getName()); 
    } 
}

Expected Output

  • User ID: 1
  • User Name: Alice

Program / Code

import java.beans.*; 
import java.io.Serializable; 
 
// Java Bean with bound and constrained properties 
public class UserBeanBound implements Serializable { 
    private final PropertyChangeSupport pcs = new PropertyChangeSupport(this); 
    private final VetoableChangeSupport vcs = new VetoableChangeSupport(this); 
    private String name; 
 
    public UserBeanBound() { 
    } 
 
    public String getName() { 
return name; 
    } 
 
    public void setName(String name) throws PropertyVetoException { 
        String oldName = this.name; 
        vcs.fireVetoableChange("name", oldName, name); // Constrained property 
        this.name = name; 
        pcs.firePropertyChange("name", oldName, name); // Bound property 
    } 
 
    public void addPropertyChangeListener(PropertyChangeListener listener) { 
        pcs.addPropertyChangeListener(listener); 
    } 
 
    public void addVetoableChangeListener(VetoableChangeListener listener) { 
        vcs.addVetoableChangeListener(listener); 
    } 
} 
 
// Test class 
class BoundConstrainedTest { 
    public static void main(String[] args) { 
        UserBeanBound user = new UserBeanBound(); 
 
        // Add a listener for bound property changes 
        user.addPropertyChangeListener(evt -> { 
            System.out.println("Property changed: " + evt.getPropertyName() + 
                    " from " + evt.getOldValue() + " to " + evt.getNewValue()); 
        }); 
 
        // Add a listener for constrained property changes (vetoable) 
        user.addVetoableChangeListener(evt -> { 
            String newValue = (String) evt.getNewValue(); 
            if (newValue == null || newValue.isEmpty()) { 
                throw new PropertyVetoException("Name cannot be empty", evt); 
            } 
        }); 
 
        try { 
            user.setName("Alice"); 
            user.setName(""); // This will throw an exception 
        } catch (PropertyVetoException e) { 
            System.out.println("Vetoed: " + e.getMessage()); 
        } 
    } 
}

Expected Output

  • Property changed: name from null to Alice
  • Vetoed: Name cannot be empty

Program / Code

import java.beans.*; 
import java.io.*; 
 
// Java Bean with persistence 
public class PersistentBean implements Serializable { 
    private String data; 
 
    public PersistentBean() { 
    } 
 
    public String getData() { 
        return data; 
    } 
 
    public void setData(String data) { 
        this.data = data; 
    } 
} 
 
// Test class 
class PersistenceTest { 
    public static void main(String[] args) { 
        PersistentBean bean = new PersistentBean(); 
        bean.setData("Persistent Data"); 
 
        // Serialize the bean to a file 
        try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("bean.ser"))) { 
            out.writeObject(bean); 
System.out.println("Bean serialized"); 
        } catch (IOException e) { 
            e.printStackTrace(); 
        } 
 
        // Deserialize the bean from the file 
        try (ObjectInputStream in = new ObjectInputStream(new FileInputStream("bean.ser"))) { 
            PersistentBean restoredBean = (PersistentBean) in.readObject(); 
            System.out.println("Restored Bean Data: " + restoredBean.getData()); 
        } catch (IOException | ClassNotFoundException e) { 
            e.printStackTrace(); 
        } 
    } 
}

Expected Output

  • Bean serialized
  • Restored Bean Data: Persistent Data

Program / Code

import java.beans.*; 
import javax.swing.*; 
import java.awt.*; 
 
// Java Bean with Customizer support 
public class CustomizableBean implements Serializable { 
    private String message = "Default Message"; 
 
    public String getMessage() { 
        return message; 
    } 
 
public void setMessage(String message) { 
        this.message = message; 
    } 
} 
 
// Customizer class 
class CustomizableBeanCustomizer extends JPanel implements Customizer { 
    private CustomizableBean bean; 
    private JTextField messageField; 
 
    public CustomizableBeanCustomizer() { 
        setLayout(new GridLayout(2, 1)); 
        add(new JLabel("Message:")); 
        messageField = new JTextField(); 
        messageField.addActionListener(e -> { 
            if (bean != null) { 
                bean.setMessage(messageField.getText()); 
            } 
        }); 
        add(messageField); 
    } 
 
    @Override 
    public void setObject(Object bean) { 
        this.bean = (CustomizableBean) bean; 
        messageField.setText(this.bean.getMessage()); 
    } 
} 
 
// Test class 
class CustomizerTest { 
    public static void main(String[] args) { 
        CustomizableBean bean = new CustomizableBean(); 
        CustomizableBeanCustomizer customizer = new CustomizableBeanCustomizer(); 
        customizer.setObject(bean); 
 
        JFrame frame = new JFrame("Customizer Demo"); 
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
        frame.setSize(300, 200); 
        frame.add(customizer); 
        frame.setVisible(true); 
 
        // Print the initial message 
        System.out.println("Initial Message: " + bean.getMessage()); 
 
        // To see the updated message, you can add a button or timer to print the message after modification  
        Timer timer = new Timer(5000, e -> { 
            System.out.println("Updated Message: " + bean.getMessage()); 
        }); 
timer.setRepeats(false); 
        timer.start(); 
    } 
}

Expected Output

  • A window titled "Customizer Demo" appears with dimensions 300x200 pixels.
  • The window contains a label "Message:" and a text field with the initial value "Default Message".
  • Console output:
  • text
  • Initial Message: Default Message
  • After 5 seconds (or if you modify the text field and press Enter), the console prints the updated
  • message, e.g.:
  • text
  • Updated Message: New Message
  • (Assuming you changed the text field to "New Message").

Setup / Requirements

1. Install Tomcat: 
○ Download Apache Tomcat (e.g., version 10.x) from https://tomcat.apache.org/. 
○ Extract it to a directory (e.g., C:\Tomcat or /opt/tomcat). 
○ Start Tomcat by running bin/startup.bat (Windows) or bin/startup.sh (Linux/Mac). 
2. Create Project Structure: 
Create a directory structure for the web application: 

SimpleServletApp/ 
├── src/ 
│   └── SimpleServlet.java 
├── WEB-INF/ 
│   ├── web.xml 
│   └── classes/ 
○ └── index.html 
 
3. Compile and Deploy: 
○ Compile the Servlet using javac and place the .class file in WEB-INF/classes/. 
○ Deploy the SimpleServletApp folder to Tomcat’s webapps directory (e.g., 
C:\Tomcat\webapps\SimpleServletApp).

Program / Code

SimpleServlet.java: 

import java.io.*; 
import javax.servlet.*; 
import javax.servlet.http.*; 
 
public class SimpleServlet extends HttpServlet { 
    @Override 
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException { 
        response.setContentType("text/html"); 
        PrintWriter out = response.getWriter(); 
        out.println("<html><body>"); 
        out.println("<h1>Hello from Simple Servlet!</h1>"); 
        out.println("</body></html>"); 
    } 
} 
 
WEB-INF/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_4_0.xsd" 
         version="4.0"> 
    <servlet> 
        <servlet-name>SimpleServlet</servlet-name> 
        <servlet-class>SimpleServlet</servlet-class> 
    </servlet> 
    <servlet-mapping> 
        <servlet-name>SimpleServlet</servlet-name> 
        <url-pattern>/simple</url-pattern> 
    </servlet-mapping> 
</web-app> 
 
index.html: 

Preview 
<!DOCTYPE html> 
<html> 
<body> 
    <h1>Welcome to Simple Servlet App</h1> 
    <a href="simple">Go to Simple Servlet</a> 
</body> 
</html> 
 
Steps to Compile and Deploy: 
1. Compile the Servlet: 

javac -cp "C:\Tomcat\lib\servlet-api.jar" SimpleServlet.java 
 Move the compiled SimpleServlet.class to WEB-INF/classes/. 
2. Deploy the SimpleServletApp folder to Tomcat/webapps/. 
3. Start Tomcat and access the application at http://localhost:8080/SimpleServletApp/.

Expected Output

  • Open a browser and navigate to http://localhost:8080/SimpleServletApp/.
  • The page displays: "Welcome to Simple Servlet App" with a link "Go to Simple Servlet".
  • Clicking the link takes you to http://localhost:8080/SimpleServletApp/simple, which displays:
  • Hello from Simple Servlet!

Program / Code

ParameterServlet.java: 

import java.io.*; 
import javax.servlet.*; 
import javax.servlet.http.*; 
 
public class ParameterServlet extends HttpServlet { 
@Override 
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException { 
        response.setContentType("text/html"); 
        PrintWriter out = response.getWriter(); 
 
        // Read parameters 
        String name = request.getParameter("name"); 
        String age = request.getParameter("age"); 
 
        out.println("<html><body>"); 
        out.println("<h1>Servlet Parameters</h1>"); 
        out.println("<p>Name: " + (name != null ? name : "Not provided") + "</p>"); 
        out.println("<p>Age: " + (age != null ? age : "Not provided") + "</p>"); 
        out.println("</body></html>"); 
    } 
} 
 
WEB-INF/web.xml (update the existing web.xml): 

<servlet> 
    <servlet-name>ParameterServlet</servlet-name> 
    <servlet-class>ParameterServlet</servlet-class> 
</servlet> 
<servlet-mapping> 
    <servlet-name>ParameterServlet</servlet-name> 
    <url-pattern>/params</url-pattern> 
</servlet-mapping> 
 
index.html (update to include a link to the new Servlet): 

Preview 
<!DOCTYPE html> 
<html> 
<body> 
    <h1>Welcome to Simple Servlet App</h1> 
    <a href="simple">Go to Simple Servlet</a><br> 
    <a href="params?name=Alice&age=25">Go to Parameter Servlet</a> 
</body> 
</html>

Expected Output

  • Navigate to http://localhost:8080/SimpleServletApp/.
  • Click the link "Go to Parameter Servlet" (or directly access
  • http://localhost:8080/SimpleServletApp/params?name=Alice&age=25).
  • The page displays:
  • Servlet Parameters
  • Name: Alice
  • Age: 25

Program / Code

GetPostServlet.java: 

import java.io.*; 
import javax.servlet.*; 
import javax.servlet.http.*; 
 
public class GetPostServlet extends HttpServlet { 
    @Override 
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException { 
        response.setContentType("text/html"); 
        PrintWriter out = response.getWriter(); 
        out.println("<html><body>"); 
        out.println("<h1>Handle GET and POST Requests</h1>"); 
        out.println("<form method='post' action='getpost'>"); 
        out.println("Name: <input type='text' name='name'><br>"); 
        out.println("<input type='submit' value='Submit'>"); 
        out.println("</form>"); 
        out.println("</body></html>"); 
    } 
 
    @Override 
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException { 
        response.setContentType("text/html"); 
        PrintWriter out = response.getWriter(); 
String name = request.getParameter("name"); 
        out.println("<html><body>"); 
        out.println("<h1>POST Request Result</h1>"); 
        out.println("<p>Hello, " + (name != null ? name : "Guest") + "!</p>"); 
        out.println("<a href='getpost'>Back to Form</a>"); 
        out.println("</body></html>"); 
    } 
} 
 
WEB-INF/web.xml (add to existing web.xml): 

<servlet> 
    <servlet-name>GetPostServlet</servlet-name> 
    <servlet-class>GetPostServlet</servlet-class> 
</servlet> 
<servlet-mapping> 
    <servlet-name>GetPostServlet</servlet-name> 
    <url-pattern>/getpost</url-pattern> 
</servlet-mapping> 
 
index.html (update): 

Preview 
<!DOCTYPE html> 
<html> 
<body> 
    <h1>Welcome to Simple Servlet App</h1> 
    <a href="simple">Go to Simple Servlet</a><br> 
    <a href="params?name=Alice&age=25">Go to Parameter Servlet</a><br> 
    <a href="getpost">Go to GET/POST Servlet</a> 
</body> 
</html>

Expected Output

  • Navigate to http://localhost:8080/SimpleServletApp/getpost.
  • The page displays a form with a text field labeled "Name" and a "Submit" button.
  • Enter a name (e.g., "Bob") and click "Submit".
  • The page displays:
  • POST Request Result
  • Hello, Bob!
  • Back to Form
  • Clicking "Back to Form" returns to the form page.

Program / Code

CookieServlet.java: 

import java.io.*; 
import javax.servlet.*; 
import javax.servlet.http.*; 
 
public class CookieServlet extends HttpServlet { 
    @Override 
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException { 
        response.setContentType("text/html"); 
        PrintWriter out = response.getWriter(); 
 
        // Create a cookie 
        Cookie cookie = new Cookie("username", "Alice"); 
        cookie.setMaxAge(60 * 60); // 1 hour 
        response.addCookie(cookie); 
 
        // Read cookies 
        Cookie[] cookies = request.getCookies(); 
        String username = "Guest"; 
        if (cookies != null) { 
            for (Cookie c : cookies) { 
                if (c.getName().equals("username")) { 
                    username = c.getValue(); 
                    break; 
                } 
            } 
        } 
 
        out.println("<html><body>"); 
        out.println("<h1>Cookie Servlet</h1>"); 
        out.println("<p>Welcome, " + username + "!</p>"); 
out.println("</body></html>"); 
    } 
} 
 
WEB-INF/web.xml (add to existing web.xml): 

<servlet> 
    <servlet-name>CookieServlet</servlet-name> 
    <servlet-class>CookieServlet</servlet-class> 
</servlet> 
<servlet-mapping> 
    <servlet-name>CookieServlet</servlet-name> 
    <url-pattern>/cookie</url-pattern> 
</servlet-mapping> 
 
index.html (update): 

Preview 
<!DOCTYPE html> 
<html> 
<body> 
    <h1>Welcome to Simple Servlet App</h1> 
    <a href="simple">Go to Simple Servlet</a><br> 
    <a href="params?name=Alice&age=25">Go to Parameter Servlet</a><br> 
    <a href="getpost">Go to GET/POST Servlet</a><br> 
    <a href="cookie">Go to Cookie Servlet</a> 
</body> 
</html>

Expected Output

  • Navigate to http://localhost:8080/SimpleServletApp/cookie.
  • The page displays:
  • Cookie Servlet
  • Welcome, Alice!
  • The cookie username=Alice is stored in the browser and will persist for 1 hour.

Program / Code

SessionServlet.java: 

import java.io.*; 
import javax.servlet.*; 
import javax.servlet.http.*; 
 
public class SessionServlet extends HttpServlet { 
    @Override 
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException { 
        response.setContentType("text/html"); 
        PrintWriter out = response.getWriter(); 
 
        // Get or create a session 
        HttpSession session = request.getSession(); 
        Integer visitCount = (Integer) session.getAttribute("visitCount"); 
 
        if (visitCount == null) { 
            visitCount = 1; 
        } else { 
            visitCount++; 
        } 
        session.setAttribute("visitCount", visitCount); 
 
        out.println("<html><body>"); 
        out.println("<h1>Session Tracking Servlet</h1>"); 
        out.println("<p>You have visited this page " + visitCount + " times.</p>"); 
        out.println("</body></html>"); 
    } 
} 
 
WEB-INF/web.xml (add to existing web.xml): 

<servlet> 
    <servlet-name>SessionServlet</servlet-name> 
    <servlet-class>SessionServlet</servlet-class> 
</servlet> 
<servlet-mapping> 
<servlet-name>SessionServlet</servlet-name> 
    <url-pattern>/session</url-pattern> 
</servlet-mapping> 
 
index.html (update): 

Preview 
<!DOCTYPE html> 
<html> 
<body> 
    <h1>Welcome to Simple Servlet App</h1> 
    <a href="simple">Go to Simple Servlet</a><br> 
    <a href="params?name=Alice&age=25">Go to Parameter Servlet</a><br> 
    <a href="getpost">Go to GET/POST Servlet</a><br> 
    <a href="cookie">Go to Cookie Servlet</a><br> 
    <a href="session">Go to Session Servlet</a> 
</body> 
</html>

Expected Output

  • Navigate to http://localhost:8080/SimpleServletApp/session.
  • First visit:
  • Session Tracking Servlet
  • You have visited this page 1 times.
  • Refresh the page (second visit):
  • Session Tracking Servlet
  • You have visited this page 2 times.
  • The visit count persists as long as the session is active (default timeout is 30 minutes).

Program / Code

SimpleJSP.jsp (place in SimpleServletApp/): 

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> 
<!DOCTYPE html> 
<html> 
<body> 
    <h1>Hello from Simple JSP!</h1> 
    <p>This is a JSP page, which is simpler to write than a Servlet for generating HTML.</p> 
</body> 
</html> 
 
CompareServlet.java (for comparison): 

import java.io.*; 
import javax.servlet.*; 
import javax.servlet.http.*; 
 
public class CompareServlet extends HttpServlet { 
    @Override 
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException { 
        response.setContentType("text/html"); 
        PrintWriter out = response.getWriter(); 
        out.println("<html><body>"); 
        out.println("<h1>Hello from Compare Servlet!</h1>"); 
        out.println("<p>This is a Servlet, which requires more code to generate HTML compared to JSP.</p>" ); 
        out.println("</body></html>"); 
    } 
} 
 
WEB-INF/web.xml (add to existing web.xml): 

<servlet> 
    <servlet-name>CompareServlet</servlet-name> 
    <servlet-class>CompareServlet</servlet-class> 
</servlet> 
<servlet-mapping> 
    <servlet-name>CompareServlet</servlet-name> 
    <url-pattern>/compare</url-pattern> 
</servlet-mapping> 
 
index.html (update): 

Preview 
<!DOCTYPE html> 
<html> 
<body> 
    <h1>Welcome to Simple Servlet App</h1> 
    <a href="simple">Go to Simple Servlet</a><br> 
    <a href="params?name=Alice&age=25">Go to Parameter Servlet</a><br> 
    <a href="getpost">Go to GET/POST Servlet</a><br> 
    <a href="cookie">Go to Cookie Servlet</a><br> 
    <a href="session">Go to Session Servlet</a><br> 
    <a href="SimpleJSP.jsp">Go to Simple JSP</a><br> 
    <a href="compare">Go to Compare Servlet</a> 
</body> 
</html>

Expected Output

  • Navigate to http://localhost:8080/SimpleServletApp/SimpleJSP.jsp:
  • Hello from Simple JSP!
  • This is a JSP page, which is simpler to write than a Servlet for generating HTML.
  • Navigate to http://localhost:8080/SimpleServletApp/compare:
  • Hello from Compare Servlet!
  • This is a Servlet, which requires more code to generate HTML compared to JSP.
  • Comparison:
  • ○ JSP is simpler for generating HTML as it allows direct embedding of HTML code.
  • ○ Servlets require manual HTML generation using PrintWriter, which is more verbose.

Program / Code

Remote Interface (Calculator.java): 

import java.rmi.Remote; 
import java.rmi.RemoteException; 
 
public interface Calculator extends Remote { 
    int add(int a, int b) throws RemoteException; 
}
Server Implementation (CalculatorImpl.java): 

import java.rmi.*; 
import java.rmi.server.*; 
import java.rmi.registry.*; 
 
public class CalculatorImpl extends UnicastRemoteObject implements Calculator { 
    public CalculatorImpl() throws RemoteException { 
        super(); 
    } 
 
    @Override 
    public int add(int a, int b) throws RemoteException { 
        return a + b; 
    } 
 
    public static void main(String[] args) { 
        try { 
            // Create and bind the remote object 
            CalculatorImpl calc = new CalculatorImpl(); 
            Registry registry = LocateRegistry.createRegistry(1099); 
            registry.rebind("CalculatorService", calc); 
            System.out.println("Server is running..."); 
        } catch (Exception e) { 
            e.printStackTrace(); 
        } 
    } 
}
Client (CalculatorClient.java): 

import java.rmi.registry.*; 
 
public class CalculatorClient { 
    public static void main(String[] args) { 
        try { 
            // Locate the remote object 
            Registry registry = LocateRegistry.getRegistry("localhost", 1099); 
            Calculator calc = (Calculator) registry.lookup("CalculatorService"); 
 
            // Call the remote method 
            int result = calc.add(5, 3); 
            System.out.println("Result of 5 + 3 = " + result); 
        } catch (Exception e) { 
            e.printStackTrace(); 
        } 
    } 
}
Steps to Run: 
1. Compile all files: 

javac Calculator.java CalculatorImpl.java CalculatorClient.java 
 
2. Start the RMI registry (if not started by the server): 

rmiregistry 
 
3. Run the server: 

java CalculatorImpl 
 
4. Run the client in a separate terminal: 

java CalculatorClient

Expected Output

  • Server console:
  • Server is running...
  • Client console:
  • Result of 5 + 3 = 8
  • Notes:
  • Tomcat Setup: Ensure Tomcat is properly installed and running for Experiments 26-31. The
  • servlet-api.jar is required for compiling Servlets (found in Tomcat/lib/).
  • RMI Setup: For Experiment 32, ensure the RMI registry is running (port 1099 by default). Run
  • the server first, then the client.
  • Dependencies: Servlets require the Servlet API (provided by Tomcat). RMI is part of the Java
  • standard library.
  • File Structure: For Servlets, maintain the correct web application structure (WEB-INF/web.xml,
  • etc.). For RMI, ensure all files are in the same directory or adjust the classpath accordingly.

No matching lab found

Try a different keyword or select “All”.