Important Questions

BIT401 · Exam intelligence

Advanced Java Programming important questions

From 4 past TU papers: which questions keep coming back, how much they carry, and what is most likely to show up next. Every question links to a model answer.

Most likely in the next examStatistical

Ranked by how often a topic is asked, its marks weight, and whether it is due after skipping the 2082 paper. No guarantees; study the whole syllabus.

1asked 2xavg 5 marks · due (skipped 2082) · Event handling and action commands
Answer

Write a program to design a form with a button and label, such that the number of times the button is clicked will be displayed in label. [5]

Key Components: 1. Window Creation: tk.Tk() creates the main application window with title and size. 2. Global Counter: clickcount variable stores the number of button clicks. 3. Click Handler Function: onbuttonclick() function: - Increm...

2asked 2xavg 5 marks · due (skipped 2082) · RMI architecture and components
Answer

Explain the architecture of RMI. [5]

RMI is a Java mechanism that allows a program running on one JVM to invoke methods on objects residing in another JVM. The architecture consists of the following layers: - Contains the client and server applications - Client invokes remo...

3asked 3xavg 8 marks · Text boxes and text fields
Answer

Design a form that contains two text fields and two buttons with caption 'OK' and 'CANCEL' using AWT. [5]

Model Answer: AWT Form with Text Fields and Buttons

Program Code:

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

public class SimpleForm extends Frame {
    
    // Declare components
    TextField textField1, textField2;
    Button okButton, cancelButton;
    
    // Constructor
    public SimpleForm() {
        // Set frame properties
        setTitle("Simple Form");
        setSize(300, 200);
        setLayout(new FlowLayout());
        
        // Create and add labels
        add(new Label("Field 1:"));
        
        // Create first text field
        textField1 = new TextField(20);
        add(textField1);
        
        add(new Label("Field 2:"));
        
        // Create second text field
        textField2 = new TextField(20);
        add(textField2);
        
        // Create OK button
        okButton = new Button("OK");
        add(okButton);
        
        // Create CANCEL button
        cancelButton = new Button("CANCEL");
        add(cancelButton);
        
        // Add event listeners
        okButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.out.println("Field 1: " + textField1.getText());
                System.out.println("Field 2: " + textField2.getText());
            }
        });
        
        cancelButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });
        
        // Handle window close
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
        
        setVisible(true);
    }
    
    // Main method
    public static void main(String[] args) {
        new SimpleForm();
    }
}

Key Components Explained:

ComponentPurpose
FrameContainer window for the form
TextFieldInput fields for user data (2 fields)
ButtonClickable buttons with captions 'OK' and 'CANCEL'
FlowLayoutArranges components in a row
ActionListenerHandles button click events

Output:

  • Form displays with two text input fields
  • Two buttons labeled "OK" and "CANCEL"
  • OK button prints field values to console
  • CANCEL button closes the application
4asked 3xavg 7 marks · Layout managers
Answer

Distinguish between component and containers. What do you mean by keyboard mnemonics and accelerators? Illustrate the concept of Grid layout with an example.[10]

Model Answer: Components, Containers, Mnemonics, Accelerators, and Grid Layout

1. Components vs Containers

Components:

  • Basic building blocks of GUI applications
  • Lightweight objects that represent visual elements
  • Examples: JButton, JLabel, JTextField, JCheckBox, JRadioButton
  • Cannot contain other components
  • Directly display information or accept user input
  • Have their own appearance and behavior

Containers:

  • Special components that can hold other components
  • Used to organize and manage groups of components
  • Examples: JFrame, JPanel, JDialog, JWindow
  • Provide layout management for contained components
  • Inherit from Component class but add containment capability
  • Manage the positioning and sizing of child components

Key Distinction: Containers are components that can contain other components, whereas components are atomic UI elements that cannot contain other components.


2. Keyboard Mnemonics and Accelerators

Keyboard Mnemonics:

  • Single character shortcuts that activate a button or menu item
  • Accessed by pressing Alt + the mnemonic key
  • Underlined character in the button/menu label
  • Example: In a button labeled "Save", 'S' is the mnemonic
  • User presses Alt+S to activate the button
  • Provides keyboard navigation for accessibility

Accelerators:

  • Keyboard shortcuts that directly invoke an action without focus requirement
  • Typically use Ctrl key combined with another key
  • Example: Ctrl+S for Save, Ctrl+C for Copy
  • Work globally regardless of which component has focus
  • Faster than mnemonics for experienced users
  • Commonly used in menu items

Difference: Mnemonics require Alt key and component focus; accelerators work globally with Ctrl (or other modifier) combinations.


3. Grid Layout with Example

Grid Layout Concept:

  • Arranges components in a rectangular grid of rows and columns
  • All components are given equal size
  • Components fill the grid cells uniformly
  • Useful for creating uniform button arrays or form layouts

Constructor:

GridLayout(int rows, int columns)
GridLayout(int rows, int columns, int hgap, int vgap)

Where hgap and vgap are horizontal and vertical gaps between components.

Example Code:

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

public class GridLayoutExample extends JFrame {
    public GridLayoutExample() {
        setTitle("Grid Layout Demo");
        setSize(300, 300);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        // Create panel with GridLayout (3 rows, 3 columns)
        JPanel panel = new JPanel(new GridLayout(3, 3, 5, 5));
        
        // Add 9 buttons
        for (int i = 1; i <= 9; i++) {
            JButton btn = new JButton("Button " + i);
            panel.add(btn);
        }
        
        add(panel);
        setVisible(true);
    }
    
    public static void main(String[] args) {
        new GridLayoutExample();
    }
}

Output: Creates a 3x3 grid of 9 equal-sized buttons with 5-pixel gaps between them.


Total Answer Length: Appropriate for 10 marks with clear distinctions, definitions, and practical example.

5asked 2xavg 8 marks · due (skipped 2082) · Method overloading and overriding
Answer

Discuss the concept of method overriding. Write a program to create Person class with variables id, and name. Include methods getPerson() and showPerson() in the class. Again, create another class named Employee, which is child of person class. Include member variable salary, and methods getEmployee(), and showEmployee() in the class. Again, create a third class named Typist, which is child of Employee. Include variable typespeed, and methods getTypist(), and showTypist() in the class. Finally, create two objects of Typist class and read and display their details.[10]

Method Overriding and Multilevel Inheritance - Model Answer

Concept of Method Overriding

Method Overriding is a feature of Object-Oriented Programming that allows a child class to provide a specific implementation of a method that is already defined in its parent class. When a method in a child class has the same name, return type, and parameters as a method in the parent class, the child class method overrides (replaces) the parent class method.

Key Points:

  • Enables runtime polymorphism
  • Child class method must have the same signature as parent class method
  • Allows customized behavior in child classes while maintaining the parent interface
  • Improves code reusability and flexibility

Program Implementation

import java.util.Scanner;

// Parent Class: Person
class Person {
    protected int id;
    protected String name;
    
    public void getPerson() {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter ID: ");
        id = sc.nextInt();
        sc.nextLine();  // consume newline
        System.out.print("Enter Name: ");
        name = sc.nextLine();
    }
    
    public void showPerson() {
        System.out.println("ID: " + id);
        System.out.println("Name: " + name);
    }
}

// Child Class: Employee (inherits from Person)
class Employee extends Person {
    protected double salary;
    
    public void getEmployee() {
        getPerson();  // call parent method
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter Salary: ");
        salary = sc.nextDouble();
    }
    
    public void showEmployee() {
        showPerson();  // call parent method
        System.out.println("Salary: " + salary);
    }
}

// Child Class: Typist (inherits from Employee)
class Typist extends Employee {
    private int typespeed;
    
    public void getTypist() {
        getEmployee();  // call parent method
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter Typing Speed (words/min): ");
        typespeed = sc.nextInt();
    }
    
    public void showTypist() {
        showEmployee();  // call parent method
        System.out.println("Typing Speed: " + typespeed + " words/min");
    }
}

// Main Class
public class TypistDemo {
    public static void main(String[] args) {
        System.out.println("=== Typist Information System ===\n");
        
        // Create array of Typist objects
        Typist[] typists = new Typist[2];
        
        // Read details for two Typist objects
        for (int i = 0; i < 2; i++) {
            typists[i] = new Typist();
            System.out.println("\n--- Enter Details for Typist " + (i + 1) + " ---");
            typists[i].getTypist();
        }
        
        // Display details for two Typist objects
        System.out.println("\n\n=== Typist Details ===");
        for (int i = 0; i < 2; i++) {
            System.out.println("\n--- Typist " + (i + 1) + " ---");
            typists[i].showTypist();
        }
    }
}

Sample Output

=== Typist Information System ===

--- Enter Details for Typist 1 ---
Enter ID: 101
Enter Name: Ram Kumar
Enter Salary: 25000
Enter Typing Speed (words/min): 60

--- Enter Details for Typist 2 ---
Enter ID: 102
Enter Name: Sita Sharma
Enter Salary: 28000
Enter Typing Speed (words/min): 75


=== Typist Details ===

--- Typist 1 ---
ID: 101
Name: Ram Kumar
Salary: 25000.0
Typing Speed: 60 words/min

--- Typist 2 ---
ID: 102
Name: Sita Sharma
Salary: 28000.0
Typing Speed: 75 words/min

Explanation of Inheritance Hierarchy

Person (Base Class)
  ↓
Employee (Child of Person)
  ↓
Typist (Child of Employee - Multilevel Inheritance)
  • Person: Contains basic attributes (id, name) and methods
  • Employee: Extends Person, adds salary attribute and overrides display methods
  • Typist: Extends Employee, adds typespeed attribute and overrides display methods

Each child class calls parent methods using method names, demonstrating method overriding where showEmployee() overrides showPerson(), and showTypist() overrides showEmployee().

Most repeated questions

Topics asked at least twice, most-asked first.

asked 3xavg 8 marks · 2082, 2080, 0
Answer

Design a form that contains two text fields and two buttons with caption 'OK' and 'CANCEL' using AWT. [5]

Model Answer: AWT Form with Text Fields and Buttons

Program Code:

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

public class SimpleForm extends Frame {
    
    // Declare components
    TextField textField1, textField2;
    Button okButton, cancelButton;
    
    // Constructor
    public SimpleForm() {
        // Set frame properties
        setTitle("Simple Form");
        setSize(300, 200);
        setLayout(new FlowLayout());
        
        // Create and add labels
        add(new Label("Field 1:"));
        
        // Create first text field
        textField1 = new TextField(20);
        add(textField1);
        
        add(new Label("Field 2:"));
        
        // Create second text field
        textField2 = new TextField(20);
        add(textField2);
        
        // Create OK button
        okButton = new Button("OK");
        add(okButton);
        
        // Create CANCEL button
        cancelButton = new Button("CANCEL");
        add(cancelButton);
        
        // Add event listeners
        okButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.out.println("Field 1: " + textField1.getText());
                System.out.println("Field 2: " + textField2.getText());
            }
        });
        
        cancelButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });
        
        // Handle window close
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
        
        setVisible(true);
    }
    
    // Main method
    public static void main(String[] args) {
        new SimpleForm();
    }
}

Key Components Explained:

ComponentPurpose
FrameContainer window for the form
TextFieldInput fields for user data (2 fields)
ButtonClickable buttons with captions 'OK' and 'CANCEL'
FlowLayoutArranges components in a row
ActionListenerHandles button click events

Output:

  • Form displays with two text input fields
  • Two buttons labeled "OK" and "CANCEL"
  • OK button prints field values to console
  • CANCEL button closes the application
asked 3xavg 7 marks · 2082, 2080, 0
Answer

Distinguish between component and containers. What do you mean by keyboard mnemonics and accelerators? Illustrate the concept of Grid layout with an example.[10]

Model Answer: Components, Containers, Mnemonics, Accelerators, and Grid Layout

1. Components vs Containers

Components:

  • Basic building blocks of GUI applications
  • Lightweight objects that represent visual elements
  • Examples: JButton, JLabel, JTextField, JCheckBox, JRadioButton
  • Cannot contain other components
  • Directly display information or accept user input
  • Have their own appearance and behavior

Containers:

  • Special components that can hold other components
  • Used to organize and manage groups of components
  • Examples: JFrame, JPanel, JDialog, JWindow
  • Provide layout management for contained components
  • Inherit from Component class but add containment capability
  • Manage the positioning and sizing of child components

Key Distinction: Containers are components that can contain other components, whereas components are atomic UI elements that cannot contain other components.


2. Keyboard Mnemonics and Accelerators

Keyboard Mnemonics:

  • Single character shortcuts that activate a button or menu item
  • Accessed by pressing Alt + the mnemonic key
  • Underlined character in the button/menu label
  • Example: In a button labeled "Save", 'S' is the mnemonic
  • User presses Alt+S to activate the button
  • Provides keyboard navigation for accessibility

Accelerators:

  • Keyboard shortcuts that directly invoke an action without focus requirement
  • Typically use Ctrl key combined with another key
  • Example: Ctrl+S for Save, Ctrl+C for Copy
  • Work globally regardless of which component has focus
  • Faster than mnemonics for experienced users
  • Commonly used in menu items

Difference: Mnemonics require Alt key and component focus; accelerators work globally with Ctrl (or other modifier) combinations.


3. Grid Layout with Example

Grid Layout Concept:

  • Arranges components in a rectangular grid of rows and columns
  • All components are given equal size
  • Components fill the grid cells uniformly
  • Useful for creating uniform button arrays or form layouts

Constructor:

GridLayout(int rows, int columns)
GridLayout(int rows, int columns, int hgap, int vgap)

Where hgap and vgap are horizontal and vertical gaps between components.

Example Code:

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

public class GridLayoutExample extends JFrame {
    public GridLayoutExample() {
        setTitle("Grid Layout Demo");
        setSize(300, 300);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        // Create panel with GridLayout (3 rows, 3 columns)
        JPanel panel = new JPanel(new GridLayout(3, 3, 5, 5));
        
        // Add 9 buttons
        for (int i = 1; i <= 9; i++) {
            JButton btn = new JButton("Button " + i);
            panel.add(btn);
        }
        
        add(panel);
        setVisible(true);
    }
    
    public static void main(String[] args) {
        new GridLayoutExample();
    }
}

Output: Creates a 3x3 grid of 9 equal-sized buttons with 5-pixel gaps between them.


Total Answer Length: Appropriate for 10 marks with clear distinctions, definitions, and practical example.

asked 3xavg 5 marks · 2082, 2080, 0
Answer

Mention the steps to write the socket program using TCP. [5]

Model Answer: Steps to Write a Socket Program Using TCP

Since reference notes are not provided, this answer follows standard TCP socket programming methodology taught in BSc CSIT curricula:

Server-Side Steps:

  1. Create a Socket

    • Use socket() system call to create a socket with domain (AF_INET), type (SOCK_STREAM), and protocol (0 or IPPROTO_TCP)
  2. Bind the Socket

    • Use bind() to associate the socket with a specific port number and IP address
    • Define server address structure with port and address family
  3. Listen for Connections

    • Use listen() to mark the socket as passive and specify the backlog queue size for pending connections
  4. Accept Client Connection

    • Use accept() to accept incoming client connections
    • Creates a new socket for communication with the connected client
  5. Send/Receive Data

    • Use send() or write() to transmit data to the client
    • Use recv() or read() to receive data from the client
  6. Close the Socket

    • Use close() to terminate the connection and release resources

Client-Side Steps:

  1. Create a Socket

    • Use socket() with same parameters as server
  2. Connect to Server

    • Use connect() to establish connection to server's IP address and port
  3. Send/Receive Data

    • Use send() or write() to send data to server
    • Use recv() or read() to receive data from server
  4. Close the Socket

    • Use close() to terminate connection

Key Point: TCP ensures reliable, ordered, connection-oriented communication between client and server.

asked 2xavg 5 marks · 2081, 0
Answer

Write a program to design a form with a button and label, such that the number of times the button is clicked will be displayed in label. [5]

Key Components: 1. Window Creation: tk.Tk() creates the main application window with title and size. 2. Global Counter: clickcount variable stores the number of button clicks. 3. Click Handler Function: onbuttonclick() function: - Increm...

asked 2xavg 5 marks · 2081, 2080
Answer

Explain the architecture of RMI. [5]

RMI is a Java mechanism that allows a program running on one JVM to invoke methods on objects residing in another JVM. The architecture consists of the following layers: - Contains the client and server applications - Client invokes remo...

asked 2xavg 8 marks · 0
Answer

Discuss the concept of method overriding. Write a program to create Person class with variables id, and name. Include methods getPerson() and showPerson() in the class. Again, create another class named Employee, which is child of person class. Include member variable salary, and methods getEmployee(), and showEmployee() in the class. Again, create a third class named Typist, which is child of Employee. Include variable typespeed, and methods getTypist(), and showTypist() in the class. Finally, create two objects of Typist class and read and display their details.[10]

Method Overriding and Multilevel Inheritance - Model Answer

Concept of Method Overriding

Method Overriding is a feature of Object-Oriented Programming that allows a child class to provide a specific implementation of a method that is already defined in its parent class. When a method in a child class has the same name, return type, and parameters as a method in the parent class, the child class method overrides (replaces) the parent class method.

Key Points:

  • Enables runtime polymorphism
  • Child class method must have the same signature as parent class method
  • Allows customized behavior in child classes while maintaining the parent interface
  • Improves code reusability and flexibility

Program Implementation

import java.util.Scanner;

// Parent Class: Person
class Person {
    protected int id;
    protected String name;
    
    public void getPerson() {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter ID: ");
        id = sc.nextInt();
        sc.nextLine();  // consume newline
        System.out.print("Enter Name: ");
        name = sc.nextLine();
    }
    
    public void showPerson() {
        System.out.println("ID: " + id);
        System.out.println("Name: " + name);
    }
}

// Child Class: Employee (inherits from Person)
class Employee extends Person {
    protected double salary;
    
    public void getEmployee() {
        getPerson();  // call parent method
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter Salary: ");
        salary = sc.nextDouble();
    }
    
    public void showEmployee() {
        showPerson();  // call parent method
        System.out.println("Salary: " + salary);
    }
}

// Child Class: Typist (inherits from Employee)
class Typist extends Employee {
    private int typespeed;
    
    public void getTypist() {
        getEmployee();  // call parent method
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter Typing Speed (words/min): ");
        typespeed = sc.nextInt();
    }
    
    public void showTypist() {
        showEmployee();  // call parent method
        System.out.println("Typing Speed: " + typespeed + " words/min");
    }
}

// Main Class
public class TypistDemo {
    public static void main(String[] args) {
        System.out.println("=== Typist Information System ===\n");
        
        // Create array of Typist objects
        Typist[] typists = new Typist[2];
        
        // Read details for two Typist objects
        for (int i = 0; i < 2; i++) {
            typists[i] = new Typist();
            System.out.println("\n--- Enter Details for Typist " + (i + 1) + " ---");
            typists[i].getTypist();
        }
        
        // Display details for two Typist objects
        System.out.println("\n\n=== Typist Details ===");
        for (int i = 0; i < 2; i++) {
            System.out.println("\n--- Typist " + (i + 1) + " ---");
            typists[i].showTypist();
        }
    }
}

Sample Output

=== Typist Information System ===

--- Enter Details for Typist 1 ---
Enter ID: 101
Enter Name: Ram Kumar
Enter Salary: 25000
Enter Typing Speed (words/min): 60

--- Enter Details for Typist 2 ---
Enter ID: 102
Enter Name: Sita Sharma
Enter Salary: 28000
Enter Typing Speed (words/min): 75


=== Typist Details ===

--- Typist 1 ---
ID: 101
Name: Ram Kumar
Salary: 25000.0
Typing Speed: 60 words/min

--- Typist 2 ---
ID: 102
Name: Sita Sharma
Salary: 28000.0
Typing Speed: 75 words/min

Explanation of Inheritance Hierarchy

Person (Base Class)
  ↓
Employee (Child of Person)
  ↓
Typist (Child of Employee - Multilevel Inheritance)
  • Person: Contains basic attributes (id, name) and methods
  • Employee: Extends Person, adds salary attribute and overrides display methods
  • Typist: Extends Employee, adds typespeed attribute and overrides display methods

Each child class calls parent methods using method names, demonstrating method overriding where showEmployee() overrides showPerson(), and showTypist() overrides showEmployee().

asked 2xavg 5 marks · 2082, 2081
Answer

Write a program to illustrate the concept of Mouse Events. [5]

Event Type Method Description -------------------------------- Mouse Click mouseClicked() Triggered when mouse button is clicked Mouse Press mousePressed() Triggered when mouse button is pressed down Mouse Release mouseReleased() Trigger...

asked 2xavg 5 marks · 2082, 2081
Answer

Describe any two JavaFX layouts. [5]

Model Answer: Two JavaFX Layouts

1. BorderPane Layout

BorderPane is a layout container that arranges child nodes in five regions: top, bottom, left, right, and center.

  • Structure: The center region occupies the maximum available space, while the other four regions size themselves based on their content
  • Use case: Ideal for creating application layouts with a menu bar at the top, toolbars on sides, and main content in the center
  • Properties: Each region can hold a single node; if multiple nodes are needed, wrap them in another container (e.g., VBox, HBox)
  • Example structure:
    ┌─────────────────────┐
    │       TOP           │
    ├──────┬───────┬──────┤
    │      │       │      │
    │ LEFT │CENTER │RIGHT │
    │      │       │      │
    ├──────┴───────┴──────┤
    │      BOTTOM         │
    └─────────────────────┘
    

2. GridPane Layout

GridPane is a layout container that arranges child nodes in a flexible grid of rows and columns.

  • Structure: Nodes are positioned using row and column indices; cells can span multiple rows/columns
  • Flexibility: Rows and columns automatically adjust their size based on content; can set preferred widths/heights
  • Properties: Supports gap spacing between rows and columns, alignment, and padding
  • Use case: Suitable for form layouts, data tables, and any grid-based arrangement of controls
  • Example: A login form with labels in column 0 and text fields in column 1, arranged across multiple rows

Key Difference: BorderPane provides a fixed five-region layout, while GridPane offers flexible row-column positioning for more complex arrangements.

Study every one of these with model answers, flashcards, and MCQs.

Open BIT401 study modes