Java Final Exam
Practice Questions
125 Questions — Part 1: Multiple Choice (95, with answers shown) | Part 2: Comprehension (32 marks, with
model answers)
Chapter 4 Chapter 5 Chapter 6 Chapter 8
PART 1 — Multiple Choice Questions (95 Questions, Answers Included)
Chapter 4 – Inheritance and Polymorphism
Q1. What does inheritance allow a class to do?
A) Acquire the properties and methods of another class
B) Hide all its methods
C) Create multiple objects automatically
D) Become an interface
✓ Correct Answer: A) Acquire the properties and methods of another class
Q2. The class being inherited from is called the:
A) Subclass
B) Superclass
C) Interface
D) Abstract class
✓ Correct Answer: B) Superclass
Q3. Which is the correct syntax to create an inheritance relationship?
A) class Child extends Parent
B) class Child implements Parent
C) class Child extends(Parent)
D) class Parent extends Child
✓ Correct Answer: A) class Child extends Parent
Q4. Which keyword refers to the immediate superclass of a class?
A) this
B) super
C) extends
D) implements
✓ Correct Answer: B) super
Q5. When the statement “Circle c = new Circle();” is executed, what is the correct constructor execution
order?
A) Circle → GeometricObject → Object
B) Object → GeometricObject → Circle
C) GeometricObject → Object → Circle
D) Circle → Object → GeometricObject
✓ Correct Answer: B) Object → GeometricObject → Circle
Q6. For a method in a subclass to correctly override a method in the superclass, it must have:
A) The same name but different parameters
B) The same name, same parameter list, and a compatible return type
C) A different name and different parameters
D) Only a different return type
✓ Correct Answer: B) The same name, same parameter list, and a compatible return type
Q7. Method overloading is based on having the same method name but:
A) Different parameter lists
B) Different return types only
C) Identical parameter lists
D) Different access modifiers only
✓ Correct Answer: A) Different parameter lists
Q8. The word “Polymorphism” literally means:
A) One Form
B) Many Forms
C) No Forms
D) Final Form
✓ Correct Answer: B) Many Forms
Q9. A type defined by a superclass is called the:
A) Subtype
B) Supertype
C) Interface type
D) Generic type
✓ Correct Answer: B) Supertype
Q10. Given “Person p = new Student();”, this statement is an example of:
A) Downcasting
B) Upcasting (Polymorphism)
C) A compile error
D) Method overloading
✓ Correct Answer: B) Upcasting (Polymorphism)
Q11. The process by which the JVM decides, at runtime, which overridden method implementation to
execute is called:
A) Static binding
B) Dynamic binding
C) Early binding
D) Compile-time binding
✓ Correct Answer: B) Dynamic binding
Q12. “Student s = new Student(); Person p = s;” This is an example of:
A) Explicit downcasting
B) Upcasting
C) A runtime error
D) Operator overloading
✓ Correct Answer: B) Upcasting
Q13. “Student s = (Student) p;” This statement is an example of:
A) Upcasting
B) Explicit downcasting
C) Implicit casting
D) Method overriding
✓ Correct Answer: B) Explicit downcasting
Q14. If “p” is a Person reference actually pointing to a Person object (not a Student), what happens when
you write “Student s = (Student) p;”?
A) It compiles and runs normally
B) It throws a ClassCastException at runtime
C) It throws a NullPointerException
D) It throws an ArithmeticException
✓ Correct Answer: B) It throws a ClassCastException at runtime
Q15. The instanceof operator is used to:
A) Compare two object values
B) Test whether an object belongs to a specific class
C) Create a new object
D) Cast an object automatically
✓ Correct Answer: B) Test whether an object belongs to a specific class
Q16. The == operator compares ______, while the equals() method compares ______.
A) contents, references
B) references (memory addresses), contents
C) class names, hash codes
D) data types, values
✓ Correct Answer: B) references (memory addresses), contents
Q17. Which access modifier allows access from the same class, the same package, AND subclasses (even in a
different package), but NOT from non-subclasses in a different package?
A) private
B) public
C) protected
D) (default/no modifier)
✓ Correct Answer: C) protected
Q18. A method declared as final:
A) Can still be overridden by a subclass
B) Cannot be overridden by any subclass
C) Must be abstract
D) Cannot be called at all
✓ Correct Answer: B) Cannot be overridden by any subclass
Q19. A class declared as final:
A) Can be extended by other classes
B) Cannot be extended by any other class
C) Must contain abstract methods
D) Cannot have any constructors
✓ Correct Answer: B) Cannot be extended by any other class
Q20. Which of the following is an example of a final class in the Java API (as mentioned in the slides)?
A) Object
B) String
C) ArrayList
D) Scanner
✓ Correct Answer: B) String
Q21. A subclass does NOT inherit which of the following from its superclass?
A) Public methods
B) Protected fields
C) Constructors
D) Instance methods
✓ Correct Answer: C) Constructors
Q22. Which keyword refers to the current object (the calling object) itself?
A) super
B) this
C) new
D) static
✓ Correct Answer: B) this
Q23. By default, every class in Java implicitly extends which class?
A) String
B) Object
C) Number
D) Class
✓ Correct Answer: B) Object
Q24. The default equals() method inherited from Object compares:
A) Field values
B) Memory references (same as ==)
C) Hash codes only
D) Class names only
✓ Correct Answer: B) Memory references (same as ==)
Q25. Overriding the toString() method is useful because it allows:
A) Changing how an object is converted to a String for display
B) Preventing object creation
C) Hiding all fields
D) Disabling inheritance
✓ Correct Answer: A) Changing how an object is converted to a String for display
Chapter 5 – Exception Handling
Q26. An exception is best defined as:
A) A compile-time syntax error
B) An unexpected event that occurs during program execution and disrupts normal flow
C) A logic error that is always automatically fixed
D) A warning message only
✓ Correct Answer: B) An unexpected event that occurs during program execution and disrupts normal flow
Q27. Which type of error is detected by the compiler before the program runs?
A) Runtime error
B) Logic error
C) Syntax error
D) Exception
✓ Correct Answer: C) Syntax error
Q28. In the exception class hierarchy, both Error and Exception are subclasses of:
A) Object directly
B) Throwable
C) RuntimeException
D) IOException
✓ Correct Answer: B) Throwable
Q29. Which of the following is an example of an unchecked exception?
A) IOException
B) FileNotFoundException
C) ArithmeticException
D) ClassNotFoundException
✓ Correct Answer: C) ArithmeticException
Q30. A checked exception is checked:
A) At runtime only
B) At compile time, and the compiler forces the programmer to handle it
C) Never — it is ignored by Java
D) Only inside JavaFX applications
✓ Correct Answer: B) At compile time, and the compiler forces the programmer to handle it
Q31. Which keyword is used in a method header to declare that the method might throw an exception?
A) throw
B) throws
C) catch
D) try
✓ Correct Answer: B) throws
Q32. Which keyword is used to explicitly create and throw an exception object inside a method body?
A) throw
B) throws
C) catch
D) finally
✓ Correct Answer: A) throw
Q33. Which block of code is guaranteed to execute whether or not an exception occurs?
A) try
B) catch
C) finally
D) throw
✓ Correct Answer: C) finally
Q34. When using multiple catch blocks for the same try block, the correct order is:
A) General exceptions first, then specific exceptions
B) Specific exceptions first, then general exceptions
C) Order does not matter at all
D) Alphabetical order of exception names
✓ Correct Answer: B) Specific exceptions first, then general exceptions
Q35. Which method of an exception object returns the error message associated with it?
A) toString()
B) getMessage()
C) printStackTrace()
D) getClass()
✓ Correct Answer: B) getMessage()
Q36. The process of passing an exception from the method where it occurred to the calling method (and so
on) until a handler is found is called:
A) Exception chaining
B) Exception propagation
C) Rethrowing
D) Exception declaration
✓ Correct Answer: B) Exception propagation
Q37. Throwing an exception again from inside a catch block is called:
A) Exception propagation
B) Rethrowing an exception
C) Exception chaining
D) Declaring an exception
✓ Correct Answer: B) Rethrowing an exception
Q38. A NullPointerException typically occurs when:
A) Dividing an integer by zero
B) Calling a method or accessing a field on a null reference
C) Accessing an array index that is out of bounds
D) Converting a non-numeric string to a number
✓ Correct Answer: B) Calling a method or accessing a field on a null reference
Q39. Which of the following will cause an ArrayIndexOutOfBoundsException?
A) int[] x = new int[5]; x[10] = 1;
B) String s = null; [Link]();
C) int result = 10 / 0;
D) [Link]("ABC");
✓ Correct Answer: A) int[] x = new int[5]; x[10] = 1;
Q40. The statement [Link]("ABC") will throw a:
A) ArithmeticException
B) NumberFormatException
C) NullPointerException
D) ClassCastException
✓ Correct Answer: B) NumberFormatException
Q41. The finally block is primarily used for:
A) Declaring new exceptions
B) Cleanup operations such as closing files or releasing resources
C) Re-declaring the try block
D) Catching only checked exceptions
✓ Correct Answer: B) Cleanup operations such as closing files or releasing resources
Q42. Which of the following correctly demonstrates the basic try-catch structure?
A) catch(Exception ex){} try{}
B) try { } catch(Exception ex) { }
C) try catch(Exception ex) { }
D) exception try { } end;
✓ Correct Answer: B) try { } catch(Exception ex) { }
Q43. According to the slides, which of the following is NOT listed as a common reason for exceptions?
A) Invalid user input
B) Accessing an index out of bounds
C) Successfully compiling a program with no errors
D) Loss of a network connection
✓ Correct Answer: C) Successfully compiling a program with no errors
Q44. To create a custom (user-defined) exception class, it should extend:
A) Throwable directly only
B) Exception (or RuntimeException)
C) Object
D) Error
✓ Correct Answer: B) Exception (or RuntimeException)
Q45. Which syntax (introduced in Java 7) allows catching multiple exception types in a single catch block?
A) catch (IOException, SQLException e)
B) catch (IOException | SQLException e)
C) catch (IOException && SQLException e)
D) catch (IOException or SQLException e)
✓ Correct Answer: B) catch (IOException | SQLException e)
Q46. The try-with-resources statement automatically:
A) Declares variables
B) Closes resources (like files) when the try block finishes
C) Catches all exceptions
D) Throws a NullPointerException
✓ Correct Answer: B) Closes resources (like files) when the try block finishes
Q47. The printStackTrace() method is used to:
A) Print the exception message and the call stack where the exception occurred
B) Stop the program
C) Catch the exception
D) Declare the exception
✓ Correct Answer: A) Print the exception message and the call stack where the exception occurred
Q48. To create and throw a custom exception object, which is correct?
A) throw new MyException("message");
B) throws new MyException("message");
C) catch new MyException("message");
D) new throw MyException("message");
✓ Correct Answer: A) throw new MyException("message");
Chapter 6 – Abstract Classes, Interfaces & File I/O
Q49. Abstraction in object-oriented programming means:
A) Hiding implementation details and showing only functionality to the user
B) Writing all the code in one single class
C) Removing all methods from a class
D) Making every variable public
✓ Correct Answer: A) Hiding implementation details and showing only functionality to the user
Q50. An abstract method:
A) Has a complete body/implementation
B) Has no body and must be implemented (overridden) by a subclass
C) Cannot exist inside an abstract class
D) Is always declared as final
✓ Correct Answer: B) Has no body and must be implemented (overridden) by a subclass
Q51. Which keyword is used to declare an abstract class?
A) interface
B) abstract
C) final
D) static
✓ Correct Answer: B) abstract
Q52. Can an object be created directly from an abstract class using new?
A) Yes, always
B) No, it is not allowed
C) Only if the class has no fields
D) Only if it has a constructor
✓ Correct Answer: B) No, it is not allowed
Q53. Given “GeometricObject obj = new Circle(4);” where Circle extends GeometricObject and
GeometricObject is abstract, this statement is:
A) Invalid, because GeometricObject is abstract
B) Valid, because Circle is a subclass of GeometricObject
C) Valid only after an explicit cast
D) Will throw a ClassCastException at runtime
✓ Correct Answer: B) Valid, because Circle is a subclass of GeometricObject
Q54. The Number class in Java is:
A) A concrete, instantiable class
B) An abstract superclass for numeric wrapper classes such as Integer and Double
C) An interface implemented by String
D) A final class that cannot be extended
✓ Correct Answer: B) An abstract superclass for numeric wrapper classes such as Integer and Double
Q55. An interface defines:
A) How a class should implement its behavior internally
B) What a class should do (its behavior), not how it does it
C) The private implementation details of a class
D) Only constructors for a class
✓ Correct Answer: B) What a class should do (its behavior), not how it does it
Q56. Fields declared inside an interface are implicitly:
A) private final
B) public static final
C) protected static
D) public and non-static
✓ Correct Answer: B) public static final
Q57. A class uses which keyword to implement an interface?
A) extends
B) implements
C) interface
D) abstract
✓ Correct Answer: B) implements
Q58. If a class implements an interface but does NOT provide implementations for all of the interface's
methods, the class must be declared as:
A) final
B) abstract
C) static
D) private
✓ Correct Answer: B) abstract
Q59. Regarding inheritance and interfaces in Java, a class can extend ______ class(es) and implement
______ interface(s).
A) multiple ... only one
B) only one ... multiple
C) only one ... only one
D) multiple ... multiple
✓ Correct Answer: B) only one ... multiple
Q60. The method defined by the Comparable interface is:
A) equals(Object o)
B) compareTo(Object o)
C) toString()
D) hashCode()
✓ Correct Answer: B) compareTo(Object o)
Q61. If [Link](y) returns a negative number, this means:
A) x is greater than y
B) x is equal to y
C) x is less than y
D) An error occurred
✓ Correct Answer: C) x is less than y
Q62. Which of the following CANNOT have constructors?
A) A concrete class
B) An abstract class
C) An interface
D) A subclass
✓ Correct Answer: C) An interface
Q63. Which method of the File class is used to create a new directory?
A) createDirectory()
B) mkdir()
C) newDir()
D) makeFolder()
✓ Correct Answer: B) mkdir()
Q64. Which method is used to rename a file or directory?
A) rename()
B) renameTo(File newFile)
C) move()
D) changeName()
✓ Correct Answer: B) renameTo(File newFile)
Q65. Which class is used in Java to write data to a text file?
A) Scanner
B) PrintWriter
C) FileReader
D) BufferedReader
✓ Correct Answer: B) PrintWriter
Q66. If a file already exists when a new PrintWriter object is created for it, the existing contents of the file
are:
A) Appended to
B) Discarded (overwritten)
C) Locked and protected
D) Left completely unchanged
✓ Correct Answer: B) Discarded (overwritten)
Q67. Which PrintWriter method writes data AND moves to a new line afterward?
A) print()
B) println()
C) write()
D) append()
✓ Correct Answer: B) println()
Q68. Which class is used in Java to read data from a text file?
A) PrintWriter
B) Scanner
C) FileWriter
D) System
✓ Correct Answer: B) Scanner
Q69. Which Scanner method checks whether more data exists in the file before attempting to read it?
A) hasNext()
B) next()
C) close()
D) exists()
✓ Correct Answer: A) hasNext()
Q70. Before a file can be read using a Scanner object, the file must:
A) Be empty
B) Already exist (otherwise a FileNotFoundException may occur)
C) Be writable only, never readable
D) Be deleted and recreated first
✓ Correct Answer: B) Already exist (otherwise a FileNotFoundException may occur)
Q71. Starting from Java 8, an interface can contain a method with a body if it is declared as:
A) abstract
B) default or static
C) private only
D) final
✓ Correct Answer: B) default or static
Q72. Which File method checks whether a file or directory actually exists?
A) isFile()
B) exists()
C) canRead()
D) length()
✓ Correct Answer: B) exists()
Q73. Compared to PrintWriter, FileWriter:
A) Has convenient print()/println() methods built in
B) Writes raw characters and lacks the convenient print()/println() methods of PrintWriter
C) Cannot write to files at all
D) Is used only for reading files
✓ Correct Answer: B) Writes raw characters and lacks the convenient print()/println() methods of PrintWriter
Q74. BufferedReader is mainly used to:
A) Write data to files
B) Read text efficiently by buffering input, often combined with readLine()
C) Delete files
D) Create directories
✓ Correct Answer: B) Read text efficiently by buffering input, often combined with readLine()
Q75. Which of the following best describes the relationship between an interface and the classes that
implement it?
A) The interface provides full implementation for all classes
B) The interface specifies a contract that implementing classes must fulfill
C) Implementing classes cannot override interface methods
D) Interfaces can only be implemented by abstract classes
✓ Correct Answer: B) The interface specifies a contract that implementing classes must fulfill
Chapter 8 – JavaFX UI Controls & Event-Driven Programming
Q76. JavaFX was introduced as part of which Java version?
A) Java 5
B) Java 6
C) Java 7
D) Java 8
✓ Correct Answer: D) Java 8
Q77. Which GUI framework is described as the oldest, platform-dependent, and made up of “heavyweight”
components?
A) Swing
B) JavaFX
C) AWT
D) None of the above
✓ Correct Answer: C) AWT
Q78. In JavaFX, the top-level window/container is represented by a:
A) Scene
B) Node
C) Stage
D) Pane
✓ Correct Answer: C) Stage
Q79. A JavaFX Scene object contains:
A) Stages
B) Nodes
C) Applications
D) Threads
✓ Correct Answer: B) Nodes
Q80. Which layout pane places nodes on top of each other, centered by default?
A) FlowPane
B) StackPane
C) GridPane
D) BorderPane
✓ Correct Answer: B) StackPane
Q81. Which layout pane arranges nodes in rows and columns, similar to a table?
A) GridPane
B) HBox
C) VBox
D) FlowPane
✓ Correct Answer: A) GridPane
Q82. A BorderPane divides its layout into how many regions?
A) 3
B) 4
C) 5
D) 6
✓ Correct Answer: C) 5
Q83. An HBox arranges its child nodes:
A) Vertically (top to bottom)
B) Horizontally (left to right)
C) In a stack, on top of each other
D) Randomly
✓ Correct Answer: B) Horizontally (left to right)
Q84. Which UI control allows the user to enter multiple lines of text?
A) TextField
B) TextArea
C) Label
D) Button
✓ Correct Answer: B) TextArea
Q85. Which UI control allows the user to select only ONE option from a group of options?
A) CheckBox
B) RadioButton
C) TextField
D) Label
✓ Correct Answer: B) RadioButton
Q86. In the statement “Button bt = new Button("OK");”, the bt object is considered the:
A) Event Handler
B) Event Source
C) Event Class
D) Event Listener
✓ Correct Answer: B) Event Source
Q87. ActionEvent and MouseEvent are examples of:
A) Event Sources
B) Event Classes
C) Event Handlers
D) Layout Panes
✓ Correct Answer: B) Event Classes
Q88. Which method is used to register a handler that responds when a Button is clicked?
A) setOnKeyTyped()
B) setOnAction()
C) setOnMouseMoved()
D) setOnClick()
✓ Correct Answer: B) setOnAction()
Q89. Lambda expressions, used in JavaFX to simplify event handling, were introduced in:
A) Java 6
B) Java 7
C) Java 8
D) Java 9
✓ Correct Answer: C) Java 8
Q90. Which of the following is the correct lambda expression syntax for an event handler?
A) (e) => { }
B) e -> { }
C) e :: { }
D) function(e) { }
✓ Correct Answer: B) e -> { }
Q91. Which JavaFX control displays a non-editable piece of text or an image?
A) Label
B) TextField
C) Button
D) Slider
✓ Correct Answer: A) Label
Q92. Which JavaFX control lets the user choose one item from a drop-down list?
A) CheckBox
B) ComboBox
C) TextArea
D) Slider
✓ Correct Answer: B) ComboBox
Q93. In JavaFX, all layout containers (HBox, VBox, BorderPane, etc.) are subclasses of:
A) Stage
B) Scene
C) Pane
D) Application
✓ Correct Answer: C) Pane
Q94. Which method handles a mouse click event on a node?
A) setOnAction()
B) setOnMouseClicked()
C) setOnKeyPressed()
D) setOnScroll()
✓ Correct Answer: B) setOnMouseClicked()
Q95. Which method is automatically called by the JVM to launch the user interface of a JavaFX Application?
A) main()
B) init()
C) start(Stage primaryStage)
D) run()
✓ Correct Answer: C) start(Stage primaryStage)
Quick Reference Answer Key — Part 1 (MCQs)
Q# Answer Q# Answer Q# Answer Q# Answer Q# Answer
1 A 2 B 3 A 4 B 5 B
6 B 7 A 8 B 9 B 10 B
11 B 12 B 13 B 14 B 15 B
16 B 17 C 18 B 19 B 20 B
21 C 22 B 23 B 24 B 25 A
26 B 27 C 28 B 29 C 30 B
31 B 32 A 33 C 34 B 35 B
36 B 37 B 38 B 39 A 40 B
41 B 42 B 43 C 44 B 45 B
46 B 47 A 48 A 49 A 50 B
51 B 52 B 53 B 54 B 55 B
56 B 57 B 58 B 59 B 60 B
61 C 62 C 63 B 64 B 65 B
66 B 67 B 68 B 69 A 70 B
71 B 72 B 73 B 74 B 75 B
76 D 77 C 78 C 79 B 80 B
81 A 82 C 83 B 84 B 85 B
86 B 87 B 88 B 89 C 90 B
91 A 92 B 93 C 94 B 95 C
PART 2 — Comprehension Questions (32 Marks)
Short answer questions, code snippets, fill-in-the-blanks, and UML class diagrams. Each question shows its type and
mark value. Model answers are shown in green/italic directly below each question.
Q96 [Short Answer — 1 mark]
Explain the difference between method overriding and method overloading. Give one short example of each.
Answer: Overriding: a subclass redefines an inherited method using the SAME signature (e.g., Dog overrides sound()
from Animal).
Overloading: methods in the SAME class share a name but have DIFFERENT parameter lists (e.g., sum(int a, int b) and
sum(int a, int b, int c)).
Q97 [Short Answer — 1 mark]
What is the difference between a checked exception and an unchecked exception? Give one example of
each.
Answer: Checked: checked by the compiler at compile time; must be declared or handled (e.g., IOException).
Unchecked: not checked by the compiler; occurs at runtime (e.g., ArithmeticException, NullPointerException).
Q98 [Short Answer — 2 marks]
List at least three differences between an abstract class and an interface.
Answer: 1. Abstract classes can have constructors; interfaces cannot.
2. Abstract classes can have fields and complete (concrete) methods; interface fields are implicitly public static final.
3. A class can extend only ONE abstract class but implement MULTIPLE interfaces.
4. Abstract classes represent an IS-A relationship; interfaces represent shared behavior/capability.
Q99 [Fill in the Blank — 1 mark]
The ______ keyword is used to call or refer to the constructor, methods, or variables of the immediate
superclass from within a subclass.
Answer: super
Q100 [Fill in the Blank — 1 mark]
A method declared with the ______ keyword cannot be overridden by any subclass.
Answer: final
Q101 [Fill in the Blank — 1 mark]
The ______ block in a try-catch structure always executes, whether or not an exception was thrown.
Answer: finally
Q102 [Fill in the Blank — 1 mark]
______ is the automatic process of treating a subclass object as an object of its superclass type (e.g., Person p
= new Student();).
Answer: Upcasting
Q103 [Fill in the Blank — 1 mark]
In JavaFX, a ______ represents the main application window, while a ______ is the container that holds all
the visual nodes displayed inside that window.
Answer: Stage ... Scene
Q104 [Code Writing — 2 marks]
Write a Java class Animal containing a method sound() that prints "Animal Sound". Then write a subclass Dog
that overrides sound() to print "Bark". Finally, write a main method that creates an Animal reference pointing
to a Dog object and calls sound(), demonstrating dynamic binding. State the expected output.
class Animal {
public void sound() {
[Link]("Animal Sound");
}
}
class Dog extends Animal {
@Override
public void sound() {
[Link]("Bark");
}
}
public class Test {
public static void main(String[] args) {
Animal a = new Dog();
[Link](); // Output: Bark
}
}
Answer: Expected output: "Bark" (dynamic binding executes the Dog version even though the reference type is
Animal).
Q105 [Code Writing — 2 marks]
Write the setRadius(double newRadius) method for a Circle class. The method should throw an
IllegalArgumentException with the message "Radius cannot be negative" if the given radius is negative;
otherwise, it should set the radius field.
public void setRadius(double newRadius) throws IllegalArgumentException {
if (newRadius >= 0)
radius = newRadius;
else
throw new IllegalArgumentException("Radius cannot be negative");
}
Q106 [Code Writing — 2 marks]
Write a Java code segment that reads two integers, divides the first by the second inside a try block, catches
an ArithmeticException if the divisor is zero (printing "Arithmetic Error"), and prints "Done" inside a finally
block.
try {
int result = x / y;
[Link](result);
} catch (ArithmeticException ex) {
[Link]("Arithmetic Error");
} finally {
[Link]("Done");
}
Q107 [Code Writing — 2 marks]
Write an abstract class GeometricObject with two abstract methods: getArea() and getPerimeter() (both
returning double). Then write a concrete subclass Rectangle (with width and height fields) that extends
GeometricObject and provides implementations for both methods.
abstract class GeometricObject {
abstract double getArea();
abstract double getPerimeter();
}
class Rectangle extends GeometricObject {
private double width;
private double height;
public Rectangle(double width, double height) {
[Link] = width;
[Link] = height;
}
public double getArea() {
return width * height;
}
public double getPerimeter() {
return 2 * (width + height);
}
}
Q108 [Code Writing — 1 mark]
Write an interface Edible containing one abstract method howToEat() that returns a String. Then write a class
Apple that implements Edible, where howToEat() returns "Eat raw".
public interface Edible {
String howToEat();
}
class Apple implements Edible {
public String howToEat() {
return "Eat raw";
}
}
Q109 [Code Writing — 2 marks]
Write Java code that: (1) creates a PrintWriter object for a file named "[Link]"; (2) writes two lines of data
using println(); (3) closes the file; (4) includes the necessary exception handling for IOException.
import [Link];
import [Link];
public class WriteScores {
public static void main(String[] args) throws IOException {
PrintWriter output = new PrintWriter("[Link]");
[Link]("John T Smith 90");
[Link]("Mary A Brown 85");
[Link]();
}
}
Q110 [Code Writing — 2 marks]
Write Java code that uses a Scanner object to open a file named "[Link]", then reads and prints every token
in the file one by one until EOF is reached. Close the Scanner when finished.
import [Link];
import [Link];
import [Link];
public class ReadData {
public static void main(String[] args) throws FileNotFoundException {
File file = new File("[Link]");
Scanner input = new Scanner(file);
while ([Link]()) {
String token = [Link]();
[Link](token);
}
[Link]();
}
}
Q111 [Code Writing — 1 mark]
Write a JavaFX code snippet that creates a Button labeled "Greet Me" and uses a lambda expression to
register an event handler that prints "Hello!" to the console when the button is clicked.
Button bt = new Button("Greet Me");
[Link](e -> {
[Link]("Hello!");
});
Q112 [Short Answer / Tracing — 1 mark]
Given the statement "Person p = new Student();" (where Student extends Person): (a) What is the compile-
time type of p? (b) What is the runtime type of p?
Answer: a) Compile-time type: Person
b) Runtime type: Student
Q113 [Short Answer / Tracing — 1 mark]
Given: String s1 = new String("Java"); String s2 = new String("Java"); What is the result of s1 == s2? What is
the result of [Link](s2)? Explain why these results differ.
Answer: s1 == s2 is false (two different objects in memory, so the references differ).
[Link](s2) is true (equals() compares the actual contents/characters of the strings, which are the same).
Q114 [Short Answer — 1 mark]
List, in order, the steps of the file output process when writing data to a file using PrintWriter.
Answer: 1. Create a PrintWriter object for the target file.
2. Write data using print(), println(), or printf().
3. Close the file using close().
(Optionally handle IOException.)
Q115 [Short Answer — 1 mark]
Explain, step by step, what happens during exception propagation when an exception is not handled in the
method where it occurs.
Answer: 1. The exception occurs in the current method.
2. The JVM searches for a matching catch block in that method.
3. If none is found, the exception is passed (propagated) to the calling method.
4. This continues up the call chain until a matching handler is found.
5. If no handler is ever found, the program terminates abnormally.
Q116 [UML Class Diagram — 2 marks]
Draw a UML class diagram showing the inheritance relationship between an abstract class GeometricObject
and its two subclasses Circle and Rectangle. GeometricObject should include the fields color and filled, and
the abstract methods getArea() and getPerimeter() (write abstract class/method names in italics, as per UML
convention). Circle should include the field radius and implementations of getArea() and getPerimeter().
Rectangle should include the fields width and height and implementations of getArea() and getPerimeter().
Use a hollow triangle arrow pointing from Circle and Rectangle to GeometricObject to represent inheritance.
GeometricObject <<abstract>>
----------------------------------
- color
- filled
----------------------------------
+ getArea(): double {abstract}
+ getPerimeter(): double {abstract}
/_\
|
-----------------------------
| |
Circle Rectangle
---------------- ----------------
- radius - width
- height
---------------- ----------------
+ getArea(): double + getArea(): double
+ getPerimeter(): double + getPerimeter(): double
/_\ = hollow triangle arrowhead (inheritance, points to GeometricObject)
Q117 [UML Class Diagram — 2 marks]
Draw a UML class diagram representing a class Student that implements the Comparable interface. Show
Comparable as an interface (use the <<interface>> label) containing the method compareTo(Object o). Show
Student with at least one field (e.g., gpa) and its own compareTo(Object o) implementation. Use a dashed
line with a hollow triangle arrow from Student to Comparable to represent interface realization.
<<interface>>
Comparable
----------------------
+ compareTo(o: Object): int
/_\
:
: (dashed line = interface realization)
:
Student
----------------------
- gpa: double
----------------------
+ compareTo(o: Object): int
/_\ with dashed line = interface realization (Student realizes Comparable)
Q118 [Short Answer — 1 mark]
Compare the JavaFX HBox and VBox layout panes. How do they differ, and give one example scenario where
you would use each.
Answer: HBox arranges its child nodes horizontally (left to right) — useful for a row of buttons, e.g., "OK" and
"Cancel" side by side.
VBox arranges its child nodes vertically (top to bottom) — useful for a form with stacked labels and text fields.
Q119 [Short Answer — 1 mark]
Why is the protected access modifier useful in inheritance? Give a short example showing a protected field
being accessed from a subclass.
class Employee {
protected double salary;
}
class Manager extends Employee {
void giveRaise() {
salary = salary + 500; // direct access allowed (protected)
}
}
Answer: protected allows a field/method to be accessed within the same class, the same package, and by subclasses
(even in a different package) — useful when a superclass wants subclasses to directly access an inherited member
without making it fully public.
Q120 [Fill in the Blank — 1 mark]
The ______ operator is used to test whether an object is an instance of a particular class before performing a
downcast, in order to avoid a ______ exception at runtime.
Answer: instanceof ... ClassCastException
Q121 [Short Answer — 1 mark]
What is the difference between a default method and a static method in an interface (Java 8)?
Answer: Default method: has a body, is inherited by implementing classes, CAN be overridden, and is called on an
instance ([Link]()).
Static method: has a body, belongs to the interface itself, CANNOT be overridden, and is called using the interface
name ([Link]()).
Q122 [Fill in the Blank — 1 mark]
The try-with-resources statement automatically calls the ______ method on each resource when the try
block finishes, even if an exception occurs.
Answer: close()
Q123 [Code Writing — 2 marks]
Write a custom checked exception class called InsufficientFundsException that extends Exception, with a
constructor that accepts a String message and passes it to the superclass constructor.
class InsufficientFundsException extends Exception {
public InsufficientFundsException(String message) {
super(message);
}
}
Q124 [Code Writing — 2 marks]
Write a try-catch statement using the Java 7 multi-catch syntax that catches both IOException and
SQLException in a single catch block, printing "Error occurred: " followed by the exception message.
try {
// code that may throw IOException or SQLException
} catch (IOException | SQLException ex) {
[Link]("Error occurred: " + [Link]());
}
Q125 [Short Answer — 1 mark]
Compare ComboBox and RadioButton in JavaFX. When would you use each?
Answer: ComboBox shows a drop-down list of options and is best when there are many choices and limited screen
space.
RadioButton (in a group/ToggleGroup) shows all options visibly at once and is best for a small number of mutually
exclusive choices.