Q1. Develop a program that has only one button in the frame, clicking on the button cycles through the colours.

Problem Explanation

This program demonstrates color cycling in a Swing button. Each click changes the button background through a sequence of colors. The current color is obtained with getBackground().

Step-By-Step Instructions

  • Create JFrame with a single button
  • Maintain a color array (red, green, blue, yellow, etc.)
  • Keep track of current color index
  • On button click, increment index and set new color
  • Use setBackground() to change button color

Code

Java
import javax.swing.*;
import java.awt.*;

public class ColorCyclingButton extends JFrame {
    JButton btn;
    Color[] colors = {Color.RED, Color.GREEN, Color.BLUE, Color.YELLOW};
    int colorIndex = 0;
    
    ColorCyclingButton() {
        setTitle("Color Cycling Button");
        setSize(400, 200);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new FlowLayout());
        
        btn = new JButton("Click Me");
        btn.setBackground(colors[0]);
        btn.setOpaque(true);
        btn.addActionListener(e -> changeColor());
        add(btn);
        
        setVisible(true);
    }
    
    void changeColor() {
        colorIndex = (colorIndex + 1) % colors.length;
        btn.setBackground(colors[colorIndex]);
    }
    
    public static void main(String[] args) {
        new ColorCyclingButton();
    }
}

Output

Expected Output:
Button with Red background Click → Green background Click → Blue background Click → Yellow background Click → Red background (Cycles)

Key Concept

Color cycling uses modulo operator to loop through array. setOpaque(true) allows background color display. setBackground() changes component color. This demonstrates simple state management with button clicks.

Q2. Develop an program that contains three check boxes and 30x30 pixel canvas. The three checkboxes should be labelled "Red", "Green", "Blue".

Problem Explanation

This program creates a 30x30 pixel canvas whose color depends on checkbox selections. When Red and Blue are selected, the canvas turns Purple. Multiple combinations are possible.

Step-By-Step Instructions

  • Create three checkboxes for RGB colors
  • Create a custom JPanel (30x30 pixels)
  • Add ItemListener to each checkbox
  • In listener, check which boxes are selected
  • Calculate resulting color and repaint canvas

Code

Java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class RGBCanvas extends JFrame {
    JCheckBox cbRed, cbGreen, cbBlue;
    ColorCanvas canvas;
    
    RGBCanvas() {
        setTitle("RGB Checkbox Canvas");
        setSize(400, 300);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new FlowLayout());
        
        canvas = new ColorCanvas();
        add(canvas);
        
        cbRed = new JCheckBox("Red");
        cbRed.addItemListener(e -> updateCanvas());
        add(cbRed);
        
        cbGreen = new JCheckBox("Green");
        cbGreen.addItemListener(e -> updateCanvas());
        add(cbGreen);
        
        cbBlue = new JCheckBox("Blue");
        cbBlue.addItemListener(e -> updateCanvas());
        add(cbBlue);
        
        setVisible(true);
    }
    
    void updateCanvas() {
        int r = cbRed.isSelected() ? 255 : 0;
        int g = cbGreen.isSelected() ? 255 : 0;
        int b = cbBlue.isSelected() ? 255 : 0;
        canvas.setColor(new Color(r, g, b));
    }
}

class ColorCanvas extends JPanel {
    Color color = Color.WHITE;
    
    ColorCanvas() {
        setPreferredSize(new Dimension(30, 30));
    }
    
    void setColor(Color c) {
        color = c;
        repaint();
    }
    
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(color);
        g.fillRect(0, 0, 30, 30);
    }
}

class Demo {
    public static void main(String[] args) {
        new RGBCanvas();
    }
}

Output

Expected Output:
Initial: White canvas Select Red: Red canvas Select Red+Blue: Purple canvas Select All Three: White canvas

Key Concept

ItemListener detects checkbox state changes. RGB color mixing creates different colors. Custom JPanel with paintComponent() renders graphics. repaint() refreshes display.

Q3. Create an application that displays a frame with a menu bar. When a user selects any menu or menu item, display that selection on a text area in the center of the frame.

Problem Explanation

This program demonstrates menu creation using JMenuBar, JMenu, and JMenuItem. When user selects any menu item, the selection is displayed in a TextArea.

Step-By-Step Instructions

  • Create JMenuBar and JMenu objects
  • Add JMenuItems to menus
  • Add ActionListener to each menu item
  • Create JTextArea for displaying selections
  • Add text to TextArea when items are clicked

Code

Java
import javax.swing.*;
import java.awt.*;

public class MenuDemo extends JFrame {
    JTextArea textArea;
    
    MenuDemo() {
        setTitle("Menu Application");
        setSize(500, 400);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        // Create Menu Bar
        JMenuBar menuBar = new JMenuBar();
        
        // File Menu
        JMenu fileMenu = new JMenu("File");
        JMenuItem newItem = new JMenuItem("New");
        newItem.addActionListener(e -> textArea.append("Selected: File > New\n"));
        fileMenu.add(newItem);
        
        JMenuItem openItem = new JMenuItem("Open");
        openItem.addActionListener(e -> textArea.append("Selected: File > Open\n"));
        fileMenu.add(openItem);
        
        JMenuItem exitItem = new JMenuItem("Exit");
        exitItem.addActionListener(e -> System.exit(0));
        fileMenu.add(exitItem);
        
        menuBar.add(fileMenu);
        
        // Edit Menu
        JMenu editMenu = new JMenu("Edit");
        JMenuItem copyItem = new JMenuItem("Copy");
        copyItem.addActionListener(e -> textArea.append("Selected: Edit > Copy\n"));
        editMenu.add(copyItem);
        
        JMenuItem pasteItem = new JMenuItem("Paste");
        pasteItem.addActionListener(e -> textArea.append("Selected: Edit > Paste\n"));
        editMenu.add(pasteItem);
        
        menuBar.add(editMenu);
        setJMenuBar(menuBar);
        
        // Text Area
        textArea = new JTextArea();
        add(new JScrollPane(textArea), BorderLayout.CENTER);
        
        setVisible(true);
    }
    
    public static void main(String[] args) {
        new MenuDemo();
    }
}

Output

Expected Output:
Menu Bar with File and Edit menus Click File > New: "Selected: File > New" Click Edit > Copy: "Selected: Edit > Copy" (Text accumulates in TextArea)

Key Concept

JMenuBar holds menus. JMenu groups items. JMenuItem represents individual actions. ActionListener handles menu selections. setJMenuBar() adds menu bar to frame.

Q4. Develop a Graphical User Interface that performs the following SQL operations: Insert, Delete, Update.

Problem Explanation

This is a complete database management application with a GUI for performing CRUD operations (Create, Read, Update, Delete) on a database table using Swing components and JDBC.

Key Components

  • JTextFields for entering data
  • Buttons for Insert, Update, Delete operations
  • JTable to display records
  • JDBC connection for database operations
  • ActionListeners for button operations

Key Concept

JDBC enables Java applications to interact with databases. GUI components allow user interaction. PreparedStatement prevents SQL injection. This demonstrates integration of database with Java GUI applications.

Q5. Develop a simple servlet program which maintains a counter for the number of times it has been accessed since its loading.

Problem Explanation

Servlets are Java programs that run on server. This program maintains a hit counter that increments with each servlet access. The counter persists for the servlet lifetime.

Code Example

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

public class HitCounterServlet extends HttpServlet {
    static int hitCount = 0;
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        hitCount++;
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        
        out.println("<html><body>");
        out.println("<h2>This page has been accessed " + hitCount + " times</h2>");
        out.println("</body></html>");
    }
}

Key Concept

Static variables in servlets persist across requests. doGet() handles HTTP GET requests. PrintWriter sends response to client. This is a basic servlet demonstrating HTTP communication.

Q6. Develop a simple JSP program for user registration and then control will be transfer it into second page.

Problem Explanation

JSP (Java Server Pages) allows embedding Java code in HTML. This program demonstrates form submission and page redirection. After registration form submission, user is redirected to a success page.

Key Concept

JSP mixes HTML and Java code. Form data is accessed using request.getParameter(). Redirection is done using response.sendRedirect(). This demonstrates web form processing in Java.

Q7. Develop an EMI calculator using Servlet.

Problem Explanation

EMI (Equated Monthly Installment) calculator computes monthly loan payment. This servlet accepts principal, rate, and months, then calculates EMI using the financial formula.

Formula

EMI = P × r × (1 + r)^n / ((1 + r)^n - 1)
where P = Principal, r = Monthly Rate, n = Number of Months

Key Concept

Servlet handles mathematical calculations on server side. Form data is processed and results sent as HTML response. This demonstrates practical web application development.

Q8. Create a web form which processes servlet and demonstrates use of cookies and sessions.

Problem Explanation

Cookies and sessions store user information. Cookies store data on client, sessions on server. This program demonstrates both mechanisms for user tracking across requests.

Key Components

  • Create cookies using new Cookie()
  • Set cookie expiration time
  • Create sessions using request.getSession()
  • Store attributes in session
  • Retrieve values across requests

Key Concept

Cookies are persistent on client side. Sessions are server-side storage. Both enable stateful communication in HTTP. Sessions are more secure for sensitive data.

Q9. Assume that the information regarding the salary and age for all employees of an organization are available in a database. Develop a Servlet application which takes the employee id of an employee as a request parameter and displays the salary for the employee.

Problem Explanation

This servlet demonstrates database querying with request parameters. It retrieves employee information from database based on ID passed as URL parameter.

Key Concept

Request parameters are accessed via request.getParameter(). SQL queries fetch data based on ID. JDBC ResultSet stores query results. This demonstrates practical employee management system.

Q11. Develop a JSP program to display the grade of a student by accepting the marks of five subjects.

Problem Explanation

This JSP program accepts marks for five subjects, calculates average, and assigns grade accordingly. Grades may be A (90+), B (80+), C (70+), D (60+), or F (below 60).

Key Concept

JSP processes form data to perform calculations. Conditional logic assigns grades based on computed average. This demonstrates academic grading system implementation.

Q12. Create a Login application using servlet and JSP, where the user will provide his login details in a servlet page and if the login is successful then, a JSP page with "Welcome" message and "Log Out" button should be shown.

Problem Explanation

Complete login system with authentication, session management, and logout functionality. This demonstrates real-world security practices and web application flow.

Key Features

  • Login form in servlet or JSP
  • Validate credentials against database
  • Create session on successful login
  • Store user information in session
  • Implement logout to destroy session
  • Handle failed login with error message
  • Implement login attempt counter

Key Concept

Sessions prevent unauthorized access. Session IDs are unique identifiers. Logout destroys session data. Login failure counter prevents brute-force attacks. This is fundamental to web security.