Kyūkei Master Hub
SCS2108 | Phase Study Card
👁️ -- opens | 0%

Phase 17: Wednesday Test Sprint (Part 2 - Questions 5 to 8)

Master the final 4 high-yield exam questions: Publishing Company Class Hierarchy, Multi-Catch Exception Handling, AWT Registration Form GUI, and SQLite Database Table Creation.

Question 5: Publishing Hierarchy (Publication ➔ Book & DVD)

For a publishing company that markets both books and audio DVDs create a class publication that stores the price (type float) of a publication. From this class derive two classes: book, which adds a page count (type int) and dvd, which adds a playing time in minutes (type float). Each of these three classes should have a getdata() function to get its data from the user at the keyboard, and a putdata() function to display its data. Write a main() program to test the book and dvd classes by creating instances of them, asking the user to fill in data with getdata(), and then displaying the data with putdata().

Compilable Model Code:

import java.util.Scanner; // Base Superclass (PascalCase Convention) class Publication { protected float price; public void getdata(Scanner sc) { System.out.print("Enter publication price ($): "); this.price = sc.nextFloat(); } public void putdata() { System.out.println("Price: $" + price); } } // Derived Subclass 1: Book class Book extends Publication { private int pageCount; @Override public void getdata(Scanner sc) { super.getdata(sc); // Prompt for price in superclass first! System.out.print("Enter book page count: "); this.pageCount = sc.nextInt(); } @Override public void putdata() { super.putdata(); // Print price first! System.out.println("Page Count: " + pageCount + " pages"); } } // Derived Subclass 2: Dvd class Dvd extends Publication { private float playingTime; @Override public void getdata(Scanner sc) { super.getdata(sc); // Prompt for price in superclass first! System.out.print("Enter DVD playing time (minutes): "); this.playingTime = sc.nextFloat(); } @Override public void putdata() { super.putdata(); // Print price first! System.out.println("Playing Time: " + playingTime + " mins"); } } // Test Program public class PublishingCompanyTest { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("=== ENTER BOOK DATA ==="); Book b = new Book(); b.getdata(sc); System.out.println("\n=== ENTER AUDIO DVD DATA ==="); Dvd d = new Dvd(); d.getdata(sc); System.out.println("\n=========================================="); System.out.println("=== DISPLAYING BOOK PUBLICATION ==="); b.putdata(); System.out.println("\n=== DISPLAYING AUDIO DVD PUBLICATION ==="); d.putdata(); System.out.println("=========================================="); sc.close(); } }
💡 Distinction Tip #1: Reusing super.getdata() and super.putdata()
Always call super.getdata(sc) and super.putdata() inside the subclass methods! This eliminates code duplication, ensuring that the base class field (`price`) is queried and displayed cleanly before subclass-specific attributes are handled.
🌟 Distinction Tip #2: Standard Java Naming Conventions (PascalCase)

Always follow standard Java naming conventions in exams:

  • Class Names: Always use PascalCase starting with a Capital letter (e.g. Publication, Book, Dvd).
  • Method & Variable Names: Always use camelCase starting with a lowercase letter (e.g. getdata(), putdata(), pageCount, playingTime).

Question 6: Multiple Exception Handling

Write a Java program demonstrating multiple exception handling.
Requirements:
• Prompt the user to:
    ◦ Enter two integers.
    ◦ Enter an array index.
• Perform division and access an array element.
• Handle:
    ◦ ArithmeticException
    ◦ ArrayIndexOutOfBoundsException
    ◦ InputMismatchException

Compilable Model Code:

import java.util.Scanner; import java.util.InputMismatchException; public class MultiExceptionDemo { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int[] numbers = {10, 20, 30, 40, 50}; // Fixed size array of 5 elements (indices 0 to 4) try { // Step 1: Prompt for two integers for division System.out.print("Enter numerator (integer): "); int num = sc.nextInt(); System.out.print("Enter denominator (integer): "); int den = sc.nextInt(); int result = num / den; // May throw ArithmeticException (if den == 0) System.out.println("Division Result: " + num + " / " + den + " = " + result); // Step 2: Prompt for array index System.out.print("Enter an array index to access (0 to 4): "); int index = sc.nextInt(); // May throw InputMismatchException (if non-int) System.out.println("Element at index " + index + " is: " + numbers[index]); // May throw ArrayIndexOutOfBoundsException } catch (ArithmeticException e) { System.err.println("❌ Exception Caught: Cannot divide by zero! Details: " + e.getMessage()); } catch (ArrayIndexOutOfBoundsException e) { System.err.println("❌ Exception Caught: Invalid array index! Array size is " + numbers.length + " (valid indices 0-4)."); } catch (InputMismatchException e) { System.err.println("❌ Exception Caught: Input mismatch! You must enter valid integer numbers only."); } finally { System.out.println("\n[Finally Block]: Resource cleanup completed."); sc.close(); } } }
💡 Distinction Tip: Order of Catch Blocks
When catching multiple exceptions, catch blocks are evaluated sequentially from top to bottom. Specific subclass exception types (`ArithmeticException`, `ArrayIndexOutOfBoundsException`, `InputMismatchException`) MUST be listed before general `Exception`.

Question 7: Java AWT Student Registration Form GUI

Write a Java AWT program to create a simple student registration form.
Requirements:
• Create a Frame.
• Add the following AWT components:
    ◦ Labels
    ◦ TextFields (Student ID, Name, Age)
    ◦ Choice (Gender)
    ◦ Button (Register)
• Display a confirmation message when the Register button is clicked.

Compilable Model Code:

import java.awt.*; import java.awt.event.*; public class StudentRegistrationForm extends Frame implements ActionListener { // Component declarations private TextField txtID, txtName, txtAge; private Choice choiceGender; private Button btnRegister; private Label lblConfirmation; public StudentRegistrationForm() { // 1. Frame setup setTitle("Student Registration Form (AWT)"); setLayout(new GridLayout(6, 2, 10, 10)); // 6 rows, 2 columns layout setSize(450, 320); // 2. Add Labels, TextFields, Choice, Button add(new Label(" Student ID:")); txtID = new TextField(15); add(txtID); add(new Label(" Full Name:")); txtName = new TextField(20); add(txtName); add(new Label(" Age:")); txtAge = new TextField(5); add(txtAge); add(new Label(" Gender:")); choiceGender = new Choice(); choiceGender.add("Male"); choiceGender.add("Female"); choiceGender.add("Other"); add(choiceGender); // Register Button btnRegister = new Button("Register"); btnRegister.setBackground(new Color(16, 185, 129)); // Green button btnRegister.setForeground(Color.WHITE); btnRegister.addActionListener(this); // Register Event Listener! add(btnRegister); // Confirmation Message Label lblConfirmation = new Label("", Label.CENTER); add(lblConfirmation); // Handle Window Closing (X button click) addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { dispose(); System.exit(0); } }); setVisible(true); // Make frame visible } // 3. Event Handler Implementation @Override public void actionPerformed(ActionEvent e) { String id = txtID.getText().trim(); String name = txtName.getText().trim(); String age = txtAge.getText().trim(); String gender = choiceGender.getSelectedItem(); if (id.isEmpty() || name.isEmpty() || age.isEmpty()) { lblConfirmation.setForeground(Color.RED); lblConfirmation.setText("Error: Please fill in all fields!"); } else { lblConfirmation.setForeground(new Color(0, 128, 0)); lblConfirmation.setText("Registered: " + name + " (" + id + ", " + gender + ")"); } } public static void main(String[] args) { new StudentRegistrationForm(); } }
💡 Distinction Tip: AWT Event Delegation Model
Notice that `StudentRegistrationForm implements ActionListener`. Calling `btnRegister.addActionListener(this)` registers the frame as the listener for action events generated by the button. When clicked, the JVM automatically invokes `actionPerformed(ActionEvent e)`.

Question 8: SQLite Database Table Creation (JDBC)

Write a Java program that creates a table in a SQLite database.
Requirements:
• Connect to library.db.
• Create a table named Books with the following fields:
    ◦ BookID
    ◦ Title
    ◦ Author
    ◦ Price
• Display a message indicating whether the table was created successfully.

Compilable Model Code:

import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; import java.sql.SQLException; public class SQLiteCreateTable { public static void main(String[] args) { // SQLite Connection String URL String dbUrl = "jdbc:sqlite:library.db"; // SQL DDL query for creating Books table String createTableSQL = "CREATE TABLE IF NOT EXISTS Books (" + "BookID INTEGER PRIMARY KEY AUTOINCREMENT, " + "Title TEXT NOT NULL, " + "Author TEXT NOT NULL, " + "Price REAL NOT NULL" + ");"; System.out.println("Connecting to database 'library.db'..."); // Try-with-resources automatically manages Connection and Statement cleanup! try (Connection conn = DriverManager.getConnection(dbUrl); Statement stmt = conn.createStatement()) { if (conn != null) { // Execute table creation DDL stmt.execute(createTableSQL); System.out.println("================================================="); System.out.println("✅ SUCCESS: Table 'Books' created successfully!"); System.out.println("Database File: library.db"); System.out.println("Columns: [BookID, Title, Author, Price]"); System.out.println("================================================="); } } catch (SQLException e) { System.err.println("================================================="); System.err.println("❌ ERROR: Failed to create table 'Books'."); System.err.println("SQL State: " + e.getSQLState()); System.err.println("Message: " + e.getMessage()); System.err.println("================================================="); } } }
💡 Distinction Tip: The 5 JDBC Steps
When examiners grade JDBC questions, they award marks for:
  1. Connection URL (`jdbc:sqlite:library.db`)
  2. Establishing connection via `DriverManager.getConnection(...)`
  3. Creating `Statement` or `PreparedStatement`
  4. Executing SQL via `stmt.execute(...)` or `stmt.executeUpdate(...)`
  5. Closing resources / `SQLException` handling.