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

CS3391-oops-Answer Key

The document provides an overview of various Java programming concepts, including inheritance using the 'extends' keyword, runtime exceptions, thread creation methods, character streams, and the purpose of event handling in JavaFX. It also covers object-oriented programming principles, data types, control statements, and the use of packages and access modifiers. Additionally, it discusses inter-thread communication methods such as wait, notify, and synchronization.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

CS3391-oops-Answer Key

The document provides an overview of various Java programming concepts, including inheritance using the 'extends' keyword, runtime exceptions, thread creation methods, character streams, and the purpose of event handling in JavaFX. It also covers object-oriented programming principles, data types, control statements, and the use of packages and access modifiers. Additionally, it discusses inter-thread communication methods such as wait, notify, and synchronization.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 10

• The extend keyword is used in inheritance.

• When the child class is derived from its parent class then the keyword extends is
used.

5. What is a runtime exception?


Runtime Exception is the super class of those exceptions that can be thrown during the normal
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY operation of the Java Virtual Machine. Runtime Exception is the parent class in all exceptions
(AN AUTONOMUS INSTITUTION) of the Java.
Affiliation to Anna University, Chennai | NAAC Accredited 6. How to create a thread in java
Opp : Salem airport, Kamalapuram, Sikkanampatty, Omalur, Salem (Dt.) – 636 In Java, creating a thread can be done in two primary ways:
309 1. By implementing the Runnable interface.
Department of Computer Science and Engineering 2. By extending the Thread class.
Answer Key for End Semester Examination 7. How character streams are defined in java
 Character streams are defined in the java.io package, and they differ from byte
5070
Subject Code : CS3391 Qp. Code : streams, which handle raw binary data (like image or audio files).
Object Oriented There are two main categories of classes for character streams:
14.12.24
Subject Name : Programming Date of exam : 1. Reader Class (for reading character data)
2. Writer Class (for writing character data)
FN
Faculty Name : Mr.R.Makendran Session : 8. How to create a generic class in java
CSE Generic class or a method with a type parameter, which allows the code to be reused with
Designation : Assistant professor Department : different types.
Date of Submission :03.01.25 Use angle brackets <> to specify the type parameter (e.g., <T>).
PART – A(10*2=20 Marks)  T is a placeholder for the type that will be specified when creating an instance of the
1. Distinguish between Procedural oriented Programming and Object Oriented class.
Programming  You can use multiple type parameters (e.g., <T, U>).
9. What is the purpose of event handling in javaFx
Procedural Oriented Programming Object-Oriented Programming User Interaction: Event handling enables the application to respond to user actions such
In procedural programming, the program is In object-oriented programming, the program as:
divided into small parts called functions. is divided into small parts called objects.  Mouse clicks
Procedural programming follows a top-down Object-oriented programming follows  Key presses
approach. a bottom-up approach.  Drag-and-drop operations
 Hovering over elements
There is no access specifier in procedural Object-oriented programming has access
 Resizing windows
programming. specifiers like private, public, protected, etc.
Dynamic Behavior: Event handlers make the application dynamic by allowing components
Adding new data and functions is not easy. Adding new data and function is easy. to change in
2. Define class and object: Response to events. For example:
Class:  Highlighting a button when the mouse hovers over it.
A class is a collection of similar objects and it contains data and methods that operate  Validating input when a user types in a text field.
on that data. 10. What is the difference between combo box and choice box in javaFx
Object:
Feature ComboBox ChoiceBox
Object is an instance of a class.
For example: chair, pen, table, keyboard, bike etc. Editability Can be editable (custom input) Not editable
3. Interface in java Complexity More complex (supports typing) Simpler (fixed options)
 Java doesn't support multiple inheritance of classes, it does support it for interfaces, When only predefined options are
Use Case When custom input is needed
 An interface is similar to classes which consist of group of method declaration. sufficient
4. Explain the use of extend keyword with suitable example. Default Displays selected item, with drop- Displays selected item, with drop-
1
Feature ComboBox ChoiceBox month_days=new int[5];
Behavior down for more options down for more options month_days[0]=31;
month_days[1]=28;
AutoComplete Can implement autocomplete Not supported
month_days[2]=31;
month_days[3]=30;
month_days[4]=31;
System.out.println(“April has ”+month_days[3]+ “ days.”);
PART – B(5*16=80 Marks) }}
11. a (i) Describe java data type, variable, and array. ( 4marks) Output:
Java is a strongly typed programming language because every variable must be April has 30 days.
declared with a data type, once it is declared, the data type of the variable cannot change.
Data types in Java are of two types: 11. a (ii) Java Control statements (4marks)
1. Primitive data types (Intrinsic or built-in types ) :The primitive data Java Control statements control the order of execution in a java program, based on
types include boolean, char, byte, short, int, long, float and double. data values and conditional logic.
· Selection statements: if, if-else and switch.
2. Non-primitive data types (Derived or Reference Types): The non-
· Loop statements: while, do-while and for.
primitive data types include Classes, Interfaces, Strings and Arrays.
Java - Variables Transfer statements: break, continue, return, try-catch-finally and assert.
A Variable is a named piece of memory that is used for storing data in java Program.
 A variable is an identifier used for storing a data value. Selection statements (Decision Making Statement)
Syntax to declare variables:  if statements
datatype identifier [=value][,identifier [ =value] …];  if-else statements
Example  nested if statements
int average=0.0, height, total height;
 if-else if-else statements
Initializing Variables:
 After the declaration of a variable, it must be initialized by means of assignment  switch statements
statement. Example:
 It is not possible to use the values of uninitialized variables. public class Test {
Syntax: public static void main(String args[]){
Data type variablename=value; int x = 30;
int months=12; if( x == 10 ){
Array Definition: (4 marks) System.out.print("Value of X is 10");
An array is a collection of similar type of elements which has contiguous memory }else if( x == 20 ){
location. System.out.print("Value of X is 20");
Declaration of the array: }else if( x == 30 ){
Declaration of array means the specification of array variable, data_type and System.out.print("Value of X is 30");
array_name. }else{
Syntax to Declare an Array in java: System.out.print("This is else statement");
Example: }}}
int[] floppy; (or) int []floppy (or) int floppy[]; Looking Statements (Iteration Statements) (4marks)
While Statement
Example:  The while statement is a looping control statement that executes a block of
class Array code while a condition is true. It is entry controlled loop.
{ Do-while Loop Statement
public static void main(String[] args)  Do while loop checks the condition after executing the statements
{ atleast once.
int month_days[];  Therefore it is called as Exit Controlled Loop.
2
For Loops Statement
 The for loop is a looping construct which can execute a set of
instructions a specified number of times. It‘s a counter controlled loop.
A for statement consumes the initialization, condition and
increment/decrement in one line. It is the entry controlled loop.

OR

11. b Object-Oriented Programming (8 marks)


Object-Oriented Programming (OOP) is a programming language model
organized around objects rather than actions and data. An object-oriented program can be
characterized as data 12. a (i) Explain types of inheritance supported in java. (4 marks)
Controlling access to code. Concepts of OOPS Inheritance means creating new classes based on existing ones.
 Object 1. Single Inheritance
 Class  A class inherits from one parent class.
 Inheritance Multilevel Inheritance
 Polymorphism  : A class inherits from a class that itself inherits from another class, forming a chain
 Abstraction of inheritance.
 Encapsulation Hierarchical Inheritance
 Multiple child classes inherit from the same parent class.
Multiple Inheritance (via Interfaces) (4 marks)
Class:  Java does not support multiple inheritance with classes to avoid ambiguity (known as
A class is a collection of similar objects and it contains data and methods that operate the diamond problem). However, it supports multiple inheritance using interfaces.
on that data. Hybrid Inheritance (via Interfaces)
In other words ― Class is a blueprint or template for a set of objects that share a  A combination of two or more types of inheritance. Java supports hybrid inheritance
common structure and a common behavior. only through interfaces.
Object: Key Notes:
Object is an instance of a class.  Final Classes and Methods: A final class cannot be extended, and a final method
For example: chair, pen, table, keyboard, bike etc. cannot be overridden.
Inheritance (8 marks)  Object Class: All classes in Java implicitly inherit from the Object class, making it
Inheritance can be defined as the procedure or mechanism of acquiring all the the root of the inheritance hierarchy.
properties and behavior of one class to another,  Interface vs Class Inheritance: While a class can inherit from only one class (single
inheritance), it can implement multiple interfaces.
Polymorphism
When one task is performed by different ways i.e. known as polymorphism. For 12 a.(ii) what is the purpose of static class nested class and inner class in java
example: to convince the customer differently, to draw something e.g. shape or rectangle etc. Static Classes
Abstraction A static class is a nested class declared with the static modifier. Static classes belong
Abstraction is a process of hiding the implementation details and showing only to their enclosing class and do not require an instance of the enclosing class to be instantiated.
functionality to the  Improves Code Organization (4 marks)
user. For example: phone call, class Outer {
Encapsulation static class StaticNested {
Encapsulation in java is a process of wrapping code and data together into a single void display() {
unit, System.out.println("Static Nested Class");
} }}

3
OR
public class Test { 12.b java package and access modifier work together to control member visibility
public static void main(String[] args) { Java packages and access modifiers work together to define the visibility and
Outer.StaticNested obj = new Outer.StaticNested(); accessibility of classes, methods, variables, and other members within a program.
obj.display(); Packages: (8 marks)
}
Nested Classes
A nested class is any class defined within another class. There are two primary types:
Definition: Packages are namespaces that organize classes and interfaces into
 Static Nested Classes (as described above)
manageable units.
 Non-static Nested Classes (Inner Classes)
Purpose: Helps prevent naming conflicts and provides controlled access to classes
class Outer {
and their members.
private int num = 10;
Access Modifiers:
class Inner { Java provides four access modifiers to control the visibility of class members:
void display() { 1. Private: Accessible only within the class where it is defined.
System.out.println("Inner Class, num = " + 2. Default (Package-Private): Accessible within the same package
num);
3. Protected: Accessible within the same package and also in subclasses, even if they
} }}
are in different packages.
public class Test { 4. Public: Accessible from any other class in any package.
public static void main(String[] args) {
Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();
inner.display(); How Packages and Access Modifiers Work Together: (8 marks)
}}
Inner Classes (4 marks) 1. within the Same Package:
An inner class is a non-static nested class.  Classes in the same package can access members with public, protected, and default
Purpose: (package-private) access.
 Logical Grouping: Inner classes can logically group code that will be used only in  private members are not accessible outside the defining class, even within the same
association with the outer class. package.
 Encapsulation: Inner classes help hide implementation details from the outside 2. Across Different Packages:
world,  Public Members: Accessible to all classes, regardless of the package.
class Outer  Protected Members: Accessible in subclasses, even if they are in different
{ packages.
private String message = "Hello from Outer";  Default Members: Not accessible outside their own package.

class Inner {  Private Members: Not accessible outside their defining class, regardless of the
void printMessage() { package.
System.out.println(message); Key Points:
} }}  Default Access: Restricts visibility to the same package.
public class Test {  Protected Access: Extends visibility to subclasses in other packages.
public static void main(String[] args) {  Private Access: Restricts visibility to within the defining class.
Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();  Public Access: Grants visibility to all classes in all packages.
inner.printMessage();
}} 13.a Explain inter thread communication in java method
4
5. Avoid Deadlocks: Mismanagement of locks can lead to deadlocks, where threads are
stuck waiting indefinitely. (8 marks)
Methods for Inter-Thread Communication (8 marks) class SharedResource {
private boolean flag = false;

1. wait(): public synchronized void produce() {


o Causes the current thread to wait until another thread invokes the notify() or try {
if (flag) {
notifyAll() method for the same object.
wait(); // Wait if the resource is already produced
o Must be called within a synchronized block or method. }
System.out.println("Producing resource...");
2. notify(): } catch (InterruptedException e) {
e.printStackTrace();
} }
o Wakes up a single thread that is waiting on the object's monitor.
public synchronized void consume() {
o The awakened thread does not immediately proceed; it needs to regain the try {
if (!flag) {
object's lock.
wait(); // Wait if the resource is not yet produced
3. notifyAll(): }
System.out.println("Consuming resource...");
flag = false;
o Wakes up all threads that are waiting on the object's monitor.
notify(); // Notify the producer thread
o Like notify(), these threads will resume execution only after they }
public class InterThreadCommunicationDemo {
successfully reacquire the lock.
public static void main(String[] args) {
1. Synchronization Block:
SharedResource resource = new SharedResource();
o Threads must enter a synchronized block or method to ensure exclusive
Thread producer = new Thread(() -> {
access to the shared object.
while (true) {
2. Wait-Notify Mechanism: resource.produce();
} });
Thread consumer = new Thread(() -> {
o A thread calls wait() on an object, causing it to pause and release the lock while (true) {
on that object. resource.consume();
} });
o Another thread signals the waiting thread by calling notify() or notifyAll()
producer.start();
on the same object. consumer.start();
}}
3. Resumption of Execution:
Output
Producing resource...
o The waiting thread(s) wake up and attempt to reacquire the lock. Once a Consuming resource...
thread reacquires the lock, it resumes execution from the point where it Producing resource...
called wait(). Consuming resource...
4. Thread Safety: The use of synchronized ensures thread safety while accessing
shared resources. OR

5
Output

13.b (i)Describe how exception handling in java program (4 marks)


Exception handling in Java is a robust mechanism for managing runtime errors,
Array index is out of bounds: Index 5 out of bounds for length 3 Finally
ensuring the normal flow of a program.
block always executes.
Try Block:
o Code that might throw an exception is enclosed in a try block.
o This isolates error-prone code for monitoring
Catch Block:
 Used to handle specific exceptions.
 Multiple catch blocks can handle different exception types. 13. b(ii) Describe user defined exception in java program
Finally Block: Steps to Create and Use a User-Defined Exception: (4 marks)
 Executes code regardless of whether an exception was thrown or not.
 Typically used for cleanup operations like closing files or releasing
resources.
Throw Statement: 1. Define a Custom Exception Class:
 Explicitly throws an exception, either built-in or user-defined. o Extend either Exception (checked exception) or RuntimeException
 Commonly used to signal a method’s failure. (unchecked exception).
Throws Keyword:
 Used in method declarations to specify exceptions that might be thrown o Provide constructors for the exception class.
by the method.
Example (4 marks) o Optionally, add custom fields and methods to store and retrieve additional
import java.io.*; error details.
public class ExceptionHandlingExample {
2. Throw the Custom Exception:
public static void main(String[] args) {
try {
int[] numbers = {1, 2, 3}; o Use the throw keyword to raise the exception when the specific error
System.out.println(numbers[5]); condition occurs.
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index is out of bounds: " + 3. Handle the Custom Exception:
e.getMessage());
} finally { o Use try-catch blocks to catch and handle the custom exception.
System.out.println("Finally block always executes.");
}
try {
throwException(); Example: (4 marks)
} catch (IOException e) {
System.out.println("Caught IOException: " + e.getMessage());
} }
public static void throwException() throws IOException {
throw new IOException("Custom IO Exception thrown.");
}} class InvalidAgeException extends Exception {

6
 push(T data): Adds an element to the stack.
 pop(): Removes and returns the top element.
 peek(): Returns the top element without removing it.
public InvalidAgeException(String message) {
super(message);  isEmpty(): Checks if the stack is empty.
}}
public class UserDefinedExceptionDemo {  size(): Returns the number of elements.
public static void validateAge(int age) throws
InvalidAgeException {  clear(): Clears the stack.
if (age < 18) {
throw new InvalidAgeException("Age must be 18 or above
to register.");
} System.out.println("Registration successful!"); Testing: The main method demonstrates how to use the stack with integer data. (4 marks)
}
public static void main(String[] args) {
try {
validateAge(15);
} catch (InvalidAgeException e) {
System.out.println("Exception occurred: " +
e.getMessage()); import java.util.EmptyStackException;
} }} public class GenericStack<T> {
private Node<T> top; // Top of the stack
private int size; // Size of the stack
private static class Node<T> {
private T data;
private Node<T> next;

Output: public Node(T data) {


this.data = data;
} }
public void push(T data) {
Node<T> newNode = new Node<>(data);
newNode.next = top;
top = newNode;
Exception occurred: Age must be 18 or above to register. size++;
}
public T pop() {
if (isEmpty()) {
throw new EmptyStackException();
}
14. a (i)Design a generic class that implements a stack T data = top.data;
Generic Class: The class uses a type parameter T to allow any data type to be used. top = top.next;
Node Class: Each node holds data and a reference to the next node. size--;
return data;

Core Methods: (4 marks)

7
Key Methods of Scanner: (4 marks)
 nextLine(): Reads a whole line (including spaces).
 next(): Reads a single token (word).
}
 nextInt(), nextDouble(), etc.: Reads specific data types.

 hasNextInt(), hasNextDouble(), etc.: Checks if the input is of a specific


14.a(ii)write a java program read a string from the user and perform the operation such
as reversing and converting to uppercase (8 marks) type.
import java.util.Scanner;
public class StringOperations { Method Input Handling Use Case
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in); Scanner Simple input parsing. General-purpose console input.
// Prompt the user to enter a string
System.out.print("Enter a string: "); Efficient for large
String input = scanner.nextLine(); BufferedReader When performance is critical.
inputs.
String reversed = new
StringBuilder(input).reverse().toString();
String uppercased = input.toUpperCase(); Advanced console Secure input like passwords,
Console
System.out.println("Original String: " + input); features. interactive CLIs.
System.out.println("Reversed String: " + reversed);
System.out.println("Uppercased String: " + uppercased);
// Close the scanner
scanner.close();
}}
Using Console Class (8 marks)
The Console class provides methods specifically designed for console I/O. Note that it may
Output: not work in some IDEs (e.g., Eclipse). (5 marks)

Enter a string: HelloWorld


Original String: HelloWorld
Reversed String: dlroWolleH
Uppercased String: HELLOWORLD
import java.io.Console;
OR public class ConsoleInputConsole {
public static void main(String[] args) {
Console console = System.console();
if (console != null) {
14.b Java handles console I/O operations. String name = console.readLine("Enter your name: ");
1. Output to Console (4 marks) char[] password = console.readPassword("Enter your
To display output on the console, Java provides: password: ");
System.out.print() System.out.println("Hello, " + name + "!");
-Prints the text without moving to the next line. System.out.println("Your password is " +
2. Input from Console String.valueOf(password));
For reading user input, Java provides several approaches:
Using Scanner Class
-the Scanner class from java.util package is commonly used for reading input.
8
 fillWidth: When set to false, it prevents children from stretching horizontally. By
default, children grow in width to fill the entire space.
Comparison Between HBox and VBox:
} else {
 HBox arranges nodes horizontally (in a row), while VBox arranges nodes vertically
System.out.println("Console is not available.");
(in a column).
} }}
 Both layouts offer similar functionality but in different orientations.
 You can use HBox to organize buttons or labels horizontally across the top of a
window, and VBox for vertically stacking elements like text fields and buttons in a
Features: form.
 readLine(): Reads a line of text.
 readPassword(): Reads a password without echoing characters to the console.
15.a (i)Explain usages of layout in javaFX ,Focusing on Hbox and Vbox (8 marks)
Layout Managers are used to organize and arrange the UI components (controls) 15.a (ii)what is borderpane layout in javaFx (8 marks)
within a container (a Pane). the BorderPane layout is a type of layout container that arranges its child nodes in
1. HBox Layout five distinct regions: top, bottom, left, right, and center.
Key Features of BorderPane:

 : HBox is a layout that arranges its children horizontally in a single row.


Key Properties of HBox:  Top Bottom Left Right Centre
import javafx.application.Application;
 spacing: Sets the horizontal gap between child elements.
import javafx.scene.Scene;
 alignment: Specifies how child elements are aligned within the HBox. The default is
import javafx.scene.control.Button;
Pos.TOP_LEFT, but you can change it to align items at the top, bottom, center, etc.
import javafx.scene.layout.BorderPane;
 padding: Adds padding around the edges of the HBox.
import javafx.stage.Stage;
 fillHeight: When set to false, it prevents children from stretching vertically. By public class BorderPaneExample extends Application {
default, children can grow in height to fill the entire space. public void start(Stage primaryStage) {
BorderPane borderPane = new BorderPane();
borderPane.setTop(new Button("Top Button"));
borderPane.setBottom(new Button("Bottom Button"));
2. VBox Layout borderPane.setLeft(new Button("Left Button"));
borderPane.setRight(new Button("Right Button"));
borderPane.setCenter(new Button("Center Button"));
Scene scene = new Scene(borderPane, 400, 300);
primaryStage.setTitle("BorderPane Example");
primaryStage.setScene(scene);
 VBox is a layout that arranges its children vertically in a single column. primaryStage.show();
 Usage: It is ideal when you need to stack items vertically, such as in a vertical }
toolbar, form fields, or menu items. public static void main(String[] args) {
Key Properties of VBox: launch(args);
}}
 spacing: Sets the vertical gap between child elements.
OR
 alignment: Specifies how child elements are aligned within the VBox. Similar to
15.b Explain event handling in javaFX wit key and mouse event
HBox, you can set the alignment to top, bottom, center, etc.
1. Event Handling in JavaFX (8 marks)
 padding: Adds padding around the edges of the VBox. 2. Key Events in JavaFX
 KeyEvent.KEY_PRESSED: Fired when a key is pressed down.
import javafx.application.Application;
9
import javafx.scene.Scene; text.setOnMouseMoved(event -> {
public class KeyEventExample extends Application { text.setText("Mouse Moved to (" + event.getX() + ", " +
public static void main(String[] args) { event.getY() + ")");
launch(args); } });
public void start(Stage primaryStage) { Scene scene = new Scene(root, 300, 200);
Text text = new Text("Press a key"); primaryStage.setTitle("Mouse Event Handling Example");
text.setText("You pressed the 'A' key!"); primaryStage.setScene(scene);
} }); primaryStage.show();
text.setOnKeyReleased(event -> { }}
text.setText("Key Released: " +
event.getCode().toString());
});
primaryStage.setTitle("Key Event Handling Example");
primaryStage.setScene(scene);
primaryStage.show();
3. Mouse Events in JavaFX (8 marks)
Mouse events are triggered by user actions like clicking, dragging, and moving the mouse
over an element.
Common MouseEvent types include: (4 marks) FACULTY SIGNATURE HOD PRINCIPAL

 MouseEvent.MOUSE_CLICKED: Fired when the mouse is clicked.


 MouseEvent.MOUSE_PRESSED: Fired when a mouse button is pressed.

 MouseEvent.MOUSE_RELEASED: Fired when a mouse button is released.

Example of Mouse Event Handling (4 marks)

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.input.MouseEvent;
public class MouseEventExample extends Application {
public static void main(String[] args) {
launch(args);
}
public void start(Stage primaryStage) {
Text text = new Text("Click or Move the Mouse");
text.setOnMouseClicked(event -> {
text.setText("Mouse Clicked at (" + event.getX() + ", " +
event.getY() + ")");
});

10

You might also like