0% found this document useful (0 votes)
2 views

Oops Answer Key

The document is an answer key for Object-Oriented Programming (OOP) concepts and Java programming. It covers topics such as features of OOP, constructors, data types, method overloading, interfaces, built-in exceptions, autoboxing, generic methods, file operations, mouse events, menus in JavaFX, thread control, and user-defined exceptions. Each section includes definitions, examples, and explanations to clarify the concepts.

Uploaded by

kalaikumaran
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Oops Answer Key

The document is an answer key for Object-Oriented Programming (OOP) concepts and Java programming. It covers topics such as features of OOP, constructors, data types, method overloading, interfaces, built-in exceptions, autoboxing, generic methods, file operations, mouse events, menus in JavaFX, thread control, and user-defined exceptions. Each section includes definitions, examples, and explanations to clarify the concepts.

Uploaded by

kalaikumaran
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

ANSWER KEY FOR OOPS

PART A

1. List any two features of Object-Oriented Programming.(2)


o Encapsulation: Bundling data (attributes) and methods (functions) that operate
on the data within a single unit (class).
o Inheritance: Creating new classes (subclasses) from existing ones (superclasses),
inheriting properties and behaviors.
2. What is the purpose of a constructor in Java? (2)
o A constructor is a special method in a class that is used to initialize objects of that
class. It has the same name as the class and is called when an object is created
using the new keyword.
3. Define abstract classes in Java.(2)
o Abstract classes are classes that cannot be instantiated (objects cannot be created
directly). They can contain abstract methods (methods without implementation).
Subclasses of abstract classes must provide implementations for the inherited
abstract methods.
4. What is the difference between static and instance methods in Java?(2)
o Static methods: Belong to the class itself, not a specific object. They are
accessed using the class name (e.g., ClassName.methodName()).
o Instance methods: Belong to individual objects of a class. They are accessed
using an object reference (e.g., objectName.methodName()).
5. What are Java's built-in exceptions?(2)
o Checked exceptions: Exceptions that must be handled explicitly using try-catch
blocks or declared in the method signature using throws. Examples include
IOException, SQLException.
o Unchecked exceptions: Exceptions that don't need to be explicitly handled.
Examples include NullPointerException, ArithmeticException.
6. How do you create a thread in Java?(2)
o Extend the Thread class: Create a new class that extends the Thread class and
override the run() method.
o Implement the Runnable interface: Implement the Runnable interface and
override the run() method. Create a Thread object and pass the Runnable object to
its constructor.
7. How can you read input from the user via the console in Java?(2)
o Use the Scanner class:

Java

Scanner scanner = new Scanner(System.in);


int input = scanner.nextInt(); // Read an integer
String inputString = scanner.nextLine(); // Read a line of text

8. What is the basic String class in Java used for?(2)


o The String class is used to represent and manipulate sequences of characters (text)
in Java. It provides methods for string concatenation, comparison, searching, and
more.
9. What is the difference between a Checkbox and a Toggle Button in JavaFX?(2)
o Checkbox: Represents a single checkable option.
o ToggleButton: Represents a button that can be toggled between two states
(on/off, selected/unselected).
10. How a StackPane layout works in JavaFX?(2)

 The StackPane layout places its children nodes on top of each other in the order they are
added. The last node added will be on top.

PART B

11. a) Write a Java program to demonstrate the use of constructors. Explain the concept of
default and parameterized constructors with examples.(13)

Java
class Employee {
String name;
int id;

// Default constructor
Employee() {
name = "Default";
id = 0;
}

// Parameterized constructor
Employee(String name, int id) {
this.name = name;
this.id = id;
}

void display() {
System.out.println("Name: " + name + ", ID: " + id);
}
}
public class ConstructorDemo {
public static void main(String[] args) {
Employee emp1 = new Employee(); // Using default constructor
emp1.display();

Employee emp2 = new Employee("John Doe", 123); // Using parameterized constructor


emp2.display();
}
}

11. b) Explain the different types of data types available in Java. Give examples of
primitive data types and reference data types.(13)

 Primitive data types: Represent basic data values. Examples: int, double, char, boolean.
 Reference data types: Represent objects (instances of classes). Examples: String,
Employee, ArrayList.

Note: The answer key for Part B is based on the prompt provided and the image of the question
paper. The actual answer key may vary depending on the specific requirements and expectations
of the instructor or examination board.

12a) Method Overloading(13)

 Definition: Method overloading is the ability to define multiple methods with the same
name but different parameters in a class. This allows you to create methods that perform
similar tasks but with varying input arguments.
 Example:

Java
public class Calculator {
public int add(int a, int b) {
return a + b;
}

public double add(double a, double b) {


return a + b;
}

public int add(int a, int b, int c) {


return a + b + c;
}
}

 Difference from Method Overriding:


o Method overloading occurs within the same class, while method overriding
happens between a parent class and its child class.
o Method overloading is about different parameters, while method overriding is
about the same method signature but different implementations.

12 b) Interfaces(13)

 Definition: Interfaces in Java are blueprints for classes. They define a set of methods that
a class must implement to adhere to the interface contract.
 Difference from Abstract Classes:
o Interfaces can only have abstract methods (no method bodies), while abstract
classes can have both abstract and concrete methods.
o Interfaces cannot have instance variables, while abstract classes can.
o A class can implement multiple interfaces but can only extend one abstract class.
 Role in Multiple Inheritance: Interfaces enable multiple inheritance in Java, as a class
can implement multiple interfaces, effectively inheriting behavior from multiple sources.
 Example:

Java
interface Drawable {
void draw();
}

class Circle implements Drawable {


public void draw() {
System.out.println("Drawing a circle");
}
}

13 a) Built-in Exceptions(13)

 Definition: Built-in exceptions are predefined classes in Java that represent exceptional
conditions that can occur during program execution.
 Examples:
o NullPointerException: Thrown when trying to access a member of an object that
is null.
o ArithmeticException: Thrown when an arithmetic operation fails, such as division
by zero.
o IOException: Thrown when an input/output operation fails, such as reading from
or writing to a file.

13 b) Autoboxing and Unboxing (13)

 Definition: Autoboxing is the automatic conversion of primitive types (like int, double,
etc.) to their corresponding wrapper class objects (like Integer, Double, etc.). Unboxing is
the reverse process.
 Example:

Java
int num = 10; // Primitive type
Integer numObject = num; // Autoboxing
int num2 = numObject; // Unboxing

14 a) Generic Methods(13)

 Definition: Generic methods are methods that can work with different data types. They
are defined using type parameters (like <T>) to represent the type of data they can
handle.
 Example:

Java
public class GenericExample {
public static <T> T findMax(T[] array) {
T max = array[0];
for (T element : array) {
// Assuming a Comparable interface is implemented for T
if (element.compareTo(max) > 0) {
max = element;
}
}
return max;
}
}

14 b) File Reading and Writing (13)

 Process:
1. Create a File object representing the file to be read or written.
2. Create a FileReader or FileWriter object to read or write data to the file.
3. Use a BufferedReader or BufferedWriter to efficiently read or write data in
chunks.
4. Close the streams after finishing the operations.
 Example:

Java
import java.io.*;

public class FileReadWrite {


public static void main(String[] args) {
// Write to file
try (BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"))) {
writer.write("Hello, world!");
} catch (IOException e) {
e.printStackTrace();
}

// Read from file


try (BufferedReader reader = new BufferedReader(new FileReader("output.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

15 a) Mouse Events in JavaFX(13)

 Definition: Mouse events represent user interactions with the mouse, such as clicking,
dragging, and hovering.
 Handling: You can handle mouse events using event listeners attached to nodes in a
JavaFX scene.
 Examples:
o MouseEvent.MOUSE_CLICKED: Occurs when the mouse button is pressed and
released.
o MouseEvent.MOUSE_PRESSED: Occurs when the mouse button is pressed.
o MouseEvent.MOUSE_DRAGGED: Occurs when the mouse is dragged while a
button is pressed.
15 b) Menus in JavaFX(13)

 Creating Menus:
1. Create a MenuBar object.
2. Create Menu objects for each main menu item.
3. Create MenuItem objects for each sub-item within a menu.
4. Add MenuItem objects to their respective Menu objects.
5. Add Menu objects to the MenuBar.
 Example:

Java
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.stage.Stage;

public class MenuExample extends Application {


@Override
public void start(Stage primaryStage) {
// Create a MenuBar
MenuBar menuBar = new MenuBar();

// Create File Menu


Menu fileMenu = new Menu("File");
MenuItem openItem = new MenuItem("Open");
MenuItem saveItem = new MenuItem("Save");
fileMenu.getItems().addAll(openItem, saveItem);

// Create Edit Menu


Menu editMenu = new Menu("Edit");
MenuItem copyItem = new MenuItem("Copy");
MenuItem pasteItem = new MenuItem("Paste");
editMenu.getItems().addAll(copyItem, pasteItem);

// Add menus to MenuBar


menuBar.getMenus().addAll(fileMenu, editMenu);

// Create a Scene and set the MenuBar


Scene scene = new Scene(menuBar, 300, 200);
primaryStage.setScene(scene);
primaryStage.show();
}

public static void main(String[] args) {


launch(args);
}
}
PART - C

16 a) Thread Control(15)

 Suspending: Temporarily pausing the execution of a thread without terminating it. This
can be achieved using methods like Thread.suspend(). However, Thread.suspend() is
discouraged in modern Java due to potential deadlocks.
 Resuming: Restarting the execution of a suspended thread. This is done using
Thread.resume().
 Stopping: Terminating the execution of a thread completely. This can be achieved using
Thread.stop(), but it is also discouraged as it can lead to unpredictable behavior.
 Example:

Java
public class ThreadControlExample {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();

// Suspend the thread


thread.suspend();

// Resume the thread


thread.resume();

// Stop the thread


thread.stop(); // Discouraged
}
}

class MyThread extends Thread {


public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("Thread running: " + i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

public void suspend() {


// Implement thread suspension using proper synchronization
}

public void resume() {


// Implement thread resumption using proper synchronization
}
}

16 b) User-Defined Exceptions (15)

 Creating User-Defined Exceptions:


1. Create a new class that extends the Exception class or one of its subclasses (like
RuntimeException).
2. Provide a constructor for the exception class to optionally pass a message or
cause.
 Example:

Java
class InvalidStringException extends Exception {
public InvalidStringException(String message) {
super(message);
}
}

 Using Custom Exceptions:


1. Throw the custom exception in the appropriate code block using the throw
keyword.
2. Catch the custom exception using a try-catch block and handle the error
accordingly.
 Example:

Java
public class CustomExceptionExample {
public static void main(String[] args) {
String input = "Hello, world!";
try {
validateString(input);
System.out.println("String is valid.");
} catch (InvalidStringException e) {
System.out.println("Error: " + e.getMessage());
}
}

public static void validateString(String str) throws InvalidStringException {


for (char c : str.toCharArray()) {
if (!Character.isLetterOrDigit(c)) {
throw new InvalidStringException("String contains invalid characters.");
}
}
}
}

You might also like