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

WINTER 2023 _ OOP in Java

The document outlines the exam structure for the Object Oriented Programming - I course at Gujarat Technological University, including instructions and a variety of programming questions. It covers topics such as Java's platform independence, object-class relationships, error analysis in code, and multithreading. Additionally, it includes practical programming tasks related to arrays, exception handling, and JavaFX applications.

Uploaded by

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

WINTER 2023 _ OOP in Java

The document outlines the exam structure for the Object Oriented Programming - I course at Gujarat Technological University, including instructions and a variety of programming questions. It covers topics such as Java's platform independence, object-class relationships, error analysis in code, and multithreading. Additionally, it includes practical programming tasks related to arrays, exception handling, and JavaFX applications.

Uploaded by

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

Seat No.: Enrolment No.

GUJARAT TECHNOLOGICAL UNIVERSITY


BE - SEMESTER–IV (NEW) EXAMINATION – WINTER 2023
Subject Code:3140705 Date:31-01-2024
Subject Name: Object Oriented Programming -I
Time: 10:30 AM TO 01:00 PM Total Marks:70
Instructions:
1. Attempt all questions.
2. Make suitable assumptions wherever necessary.
3. Figures to the right indicate full marks.
4. Simple and non-programmable scientific calculators are allowed.
MARKS

Q.1 (a) How java supports platform independency? What is the role of JVM in it? 03
(b) Write a program which displays first n prime number? Where is n provided 04
by user as command line argument?
(c) Write a program which declare integer array of 10 elements? Initialize array 07
and define following methods with the specified header:
(i) public static int add(int [] array) print addition of all element of array.
(ii) public static int max(int [] array) print maximum element of array.
(ii) public static int search(int [] array, int key) search element key in array
and return index of it. If element is not found method will return -1.

Q.2 (a) Describe the relationship between an object and its defining class? 03
(b) Analyze following code. Validate and explain output of code. If any error 04
exists, indicate portion. Suggest code to eliminate error:
public class Circle {
private double radius;
public static void main(String args[]){
Circle c1=new Circle(2);
System.out.println("Area "+c1.getArea());
B b1=new B(2, 2);
System.out.println("Area "+b1.getArea());
}
public Circle(double radius) {
radius = radius;
}
public double getRadius() {
return radius;
}
public double getArea() {
return radius * radius * Math.PI;
}
}

class B extends Circle {


private double length;
B(){}
B(double radius, double length) {
length = length;
}
public double getArea() {
return (super.getArea() * length);
}
}
(c) Design a java class Rectangle which contains following field and methods: 07
(i) Field: length, width: int
(ii) Default Constructor: initialize all fields with 0 value
(iii) Method: int getArea() will return area of rectangle.

Click :Youtube Channel | Free Material | Download App


OR
(c) Answer in brief(within two lines): 07
(i) If a method defined in a subclass has the same signature as a method in its
superclass with the
same return type, is the method overridden or overloaded?
(ii) How do you invoke an overridden superclass method from a subclass?
(iii) What is the purpose of "this" keyword?
(iv) Differentiate between following statements:
int a=3;
Integer b=new Integer(3);
(v) Which java keyword is used to prevent inheritance (prevent class to be
extended)?
(vi) Can we create reference of interface. If we can create, then what is the
use of it?
(vii) What is the difference between a String in Java and String in C/C++?

Q.3 (a) Discuss benefits of multithreading? 03


(b) Develop a program which stores name of districts in Gujrat in array of String. 04
The array specified capacity to store 5 districts. The user will be able to print
name of district based on array index e.g. (0 will print Ahemdabad). If the
specified index is out of bounds, program will display the message Out of
Bounds.
(c) Characterize the two ways of implementing thread in Java? Illustrate each 07
method by example?
OR
Q.3 (a) Explain the use of finally. Show the type of code usually kept in finally? 03
(b) Distinguish unchecked exception and checked exception? Give example of 04
each type of exception?
(c) Implement java code to take some (say 10) Strings from users. Put all the 07
input Strings in an array (String name[]). Provide implementation of
following methods:
(i) search(String s) will return index of String passed in method if String S is
found in name, otherwise return -1.
(ii) sort() will print sorted String array to user

Q.4 (a) Write a program to find out whether the given number is palindrome or not? 03
(b) Outline the use of throw in exception handling with example. 04
(c) Give Definitions: static, finalize, final 07
OR
Q.4 (a) Elaborate the role of java garbage collector. 03
(b) State four similarities between Interfaces and Classes. 04
(c) Differentiate between ArrayList and LinkedList? Which list should you use 07
to insert and delete elements at the beginning of a list? What methods are in
LinkedList but not in ArrayList?

Q.5 (a) List various classes for Binary Input Output? 03


(b) Characterize the role of Iterator interface? 04
(c) Explain DataInputStream and DataOutputStream Classes? Implement a java 07
program to demonstrate any one of them?
OR
Q.5 (a) What do you understand by JavaFX? How it is different from AWT? 03
(b) Explain ArrayList Class with its methods? 04
(c) Design and develop EMI Calculator using JavaFX? The user will enter a loan 07
amount, annual interest
2

Click :Youtube Channel | Free Material | Download App


rate, and number of years and click the Calculate button to get EMI and total
payment ? formula is
EMI= P*r*(1+r)n/((1+r)n-1)
P is Principal Loan Amount
r is rate of interest calculated on monthly basis. (i.e., r = Rate of Annual
interest/12/100. If rate of interest is 10.5% per annum, then r =
10.5/12/100=0.00875)
n is loan term / tenure / duration in number of months?

***********

Click :Youtube Channel | Free Material | Download App


OOP WINTER 2023 SOLUTION
Q1(A) How java supports platform independency? What is the role of
JVM in it? (3M)
ANS

Java achieves platform independence through its "Write Once, Run


Anywhere" (WORA) principle. This is possible due to the Java Virtual
Machine (JVM) and the compilation process in Java.
Java Compilation Process
1. Source Code (.java file) → Written by the programmer.
2. Compilation → The Java compiler (javac) converts the source
code into bytecode (.class file), which is not specific to any
operating system.
3. Execution → The JVM interprets the bytecode and executes it on
any machine that has a JVM.
Since bytecode is not directly executed by the OS but by the JVM, Java
can run on any platform (Windows, Linux, macOS, etc.) that has a
JVM installed.

Role of JVM in Platform Independence


The Java Virtual Machine (JVM) is the key component that enables
platform independence.
1. Interprets Bytecode – JVM reads the bytecode and translates it
into machine-specific instructions.
2. Just-In-Time (JIT) Compilation – Converts frequently used
bytecode into native machine code to improve performance.
3. Handles Memory Management – JVM manages memory using
features like Garbage Collection.
4. Provides Security – JVM runs bytecode in a sandboxed
environment, preventing malicious code execution.
Each OS has its own JVM implementation, but they all understand the
same bytecode. This allows Java programs to run on any system
without modification

Click :Youtube Channel | Free Material | Download App


Q1(B) Write a program which displays first n prime number?
Where is n provided by user as command line argument? (4M)

public class PrimeNumbers {


public static void main(String[] args) {
if (args.length != 1) {
System.out.println("Usage: java PrimeNumbers <n>");
return;
}
int n;
try {
n = Integer.parseInt(args[0]);
if (n <= 0) {
System.out.println("Please enter a positive integer.");
return;
}
} catch (NumberFormatException e) {
System.out.println("Invalid input. Please enter a valid
integer.");
return;
}
int count = 0, num = 2;
System.out.println("First " + n + " prime numbers:");
while (count < n) {
if (isPrime(num)) {
System.out.print(num + " ");
count++;
}
num++;
}
}
// Method to check if a number is prime
public static boolean isPrime(int num) {
if (num < 2) return false;
for (int i = 2; i * i <= num; i++) {
if (num % i == 0) return false;
}
return true;
}
}

Click :Youtube Channel | Free Material | Download App


Q1(C) Write a program which declare integer array of 10 elements?
Initialize array and define following methods with the specified header:
(i) public static int add(int [] array) print addition of all element of array.
(ii) public static int max(int [] array) print maximum element of array.
(iii) public static int search(int [] array, int key) search element key in
array and return index of it. If element is not found method will return -1.
(7M)

ANS

Ans.
public class ArrayOperations {
public static void main(String[] args) {
int[] array = {10, 25, 30, 5, 45, 60, 75, 80, 95, 100}; // Initializing
array

System.out.println("Sum of array elements: " + add(array));


System.out.println("Maximum element in array: " + max(array));

int key = 45; // Key to search


int index = search(array, key);
if (index != -1) {
System.out.println("Element " + key + " found at index: " +
index);
} else {
System.out.println("Element " + key + " not found in array.");
}
}

// (i) Method to find sum of all elements in the array


public static int add(int[] array) {
int sum = 0;
for (int num : array) {
sum += num;
}
return sum;
}

Click :Youtube Channel | Free Material | Download App


// (ii) Method to find the maximum element in the array
public static int max(int[] array) {
int max = array[0];
for (int num : array) {
if (num > max) {
max = num;
}
}
return max;
}

// (iii) Method to search for a key in the array and return its index
public static int search(int[] array, int key) {
for (int i = 0; i < array.length; i++) {
if (array[i] == key) {
return i; // Return index if found
}
}
return -1; // Return -1 if not found
}
}

Click :Youtube Channel | Free Material | Download App


Q2(A) Describe the relationship between an object and its defining
class? (3M)

ANS
In Object-Oriented Programming (OOP), a class serves as a blueprint
for creating objects. An object is an instance of a class, meaning it holds
specific values and can perform actions (methods) defined by the class.

1. Definition of Class and Object


 Class: A template that defines properties (attributes/fields) and
behaviors (methods) of objects.
 Object: A real-world entity that has a state (values of attributes)
and behavior (methods).
// Defining a Class
class Car {
String brand;
int speed;

// Method to display car details


void display() {
System.out.println("Brand: " + brand + ", Speed: " + speed
+ " km/h");
}
}

// Creating Objects
public class CarDemo {
public static void main(String[] args) {
Car car1 = new Car(); // Object creation
car1.brand = "Toyota";
car1.speed = 120;

Car car2 = new Car(); // Another object


car2.brand = "Honda";

Click :Youtube Channel | Free Material | Download App


car2.speed = 150;

car1.display();
car2.display();
}
}
2. Key Relationships
1. Instance of a Class:
o Objects are instances of a class.

o A class can have multiple objects, but each object belongs to

a single class.
2. Memory Allocation:
o A class does not occupy memory until an object is created.

o Each object gets its own copy of instance variables.

3. Encapsulation:
o Objects hide data using private attributes and provide access

via methods.
4. Methods and Behavior:
o Objects call methods defined in the class to perform actions.

3. Real-World Analogy
Think of a class as a blueprint for a house.
 The blueprint defines rooms, doors, and windows.

 An actual house (object) is built using this blueprint, with specific

dimensions and colors.


Similarly:
 The class defines attributes (brand, speed) and behaviors

(display()).
 The object (e.g., car1, car2) has actual values for these attributes.

Click :Youtube Channel | Free Material | Download App


Q2(B) Analyze following code. Validate and explain output of code. If
any error exists, indicate portion. Suggest code to eliminate error: (4M)

ANS
Analysis of Given Code & Errors

Errors in the Code


1. Incorrect Instance Variable Assignment in Constructor
Issue:
java
public Circle(double radius) {
radius = radius; // Incorrect assignment
}
 Problem: radius = radius; is a wrong assignment because it refers to
the local variable radius instead of the instance variable.
 Fix: Use this.radius = radius; to correctly assign the constructor
argument to the instance variable.
2. Missing Call to Superclass Constructor in Subclass
Issue:
java
class B extends Circle {

Click :Youtube Channel | Free Material | Download App


private double length;
B(){}
}
 Problem: Since Circle has a parameterized constructor, Java does
not provide a default constructor.
 Fix: The default constructor (B()) must call a constructor in Circle
explicitly using super().
3. Incorrect Assignment in Subclass Constructor
Issue:
java
B(double radius, double length) {
length = length; // Incorrect assignment
}
 Problem: Similar to the first issue, length = length; only modifies the
local variable and does not set the instance variable.
 Fix: Use this.length = length; to assign the value correctly.

Fixed Code
public class Circle {
private double radius;

public static void main(String args[]) {


Circle c1 = new Circle(2);
System.out.println("Area: " + c1.getArea());

B b1 = new B(2, 2);


System.out.println("Area: " + b1.getArea());
}

// Corrected constructor
public Circle(double radius) {
this.radius = radius; // Fixed assignment
}

public double getRadius() {


return radius;
}

Click :Youtube Channel | Free Material | Download App


public double getArea() {
return radius * radius * Math.PI;
}
}

class B extends Circle {


private double length;

// Corrected default constructor


B() {
super(1); // Default radius to 1
}

// Corrected parameterized constructor


B(double radius, double length) {
super(radius); // Call superclass constructor
this.length = length; // Fixed assignment
}

public double getArea() {


return super.getArea() * length; // Correct area calculation
}
}

Expected Output
Area: 12.566370614359172
Area: 25.132741228718345
Explanation
1. Circle c1 = new Circle(2);
o Calls Circle constructor (radius = 2).
o getArea() → 22×π=12.562^2 \times \pi = 12.5622×π=12.56
2. B b1 = new B(2, 2);
o Calls Circle constructor (radius = 2).
o Calls B constructor (length = 2).
o getArea() → 12.56×2=25.1312.56 \times 2 =
25.1312.56×2=25.13.

Click :Youtube Channel | Free Material | Download App


Q2(C) Design a java class Rectangle which contains following field
and methods:
(i) Field: length, width: int
(ii) Default Constructor: initialize all fields with 0 value
(iii) Method: int getArea() will return area of rectangle.

ANS

// Rectangle class
public class Rectangle {
// Fields
private int length;
private int width;

// Default Constructor (initializes fields to 0)


public Rectangle() {
this.length = 0;
this.width = 0;
}

// Method to calculate and return the area of the rectangle


public int getArea() {
return length * width;
}

// Setter methods to update length and width


public void setLength(int length) {
this.length = length;
}

public void setWidth(int width) {


this.width = width;
}

// Getter methods to retrieve length and width


public int getLength() {

Click :Youtube Channel | Free Material | Download App


return length;
}

public int getWidth() {


return width;
}

// Main method to test the class


public static void main(String[] args) {
Rectangle rect = new Rectangle(); // Using default constructor
rect.setLength(5); // Set length
rect.setWidth(4); // Set width

System.out.println("Rectangle Length: " + rect.getLength());


System.out.println("Rectangle Width: " + rect.getWidth());
System.out.println("Rectangle Area: " + rect.getArea());
}
}

Click :Youtube Channel | Free Material | Download App


OR Q2(C) Answer in brief(within two lines): (7M)
(i) If method defined in a subclass has same signature as a method in its
superclass with same return type, is method overridden or overloaded?
(ii) How do you invoke an overridden superclass method from a
subclass?
(iii) What is the purpose of "this" keyword?
(iv) Differentiate between following statements: int a=3; Integer b=new
Integer(3);
(v) Which java keyword is used to prevent inheritance (prevent class to
be extended)?
(vi) Can we create reference of interface. If we can create, then what is
the use of it?
(vii) What is difference between a String in Java and String in C/C++?

(i) If a method defined in a subclass has the same signature and return
type as a method in its superclass, it is overridden (not overloaded).

(ii) An overridden superclass method can be invoked using


super.methodName(); inside the subclass.

(iii) The this keyword refers to the current object and is used to
differentiate instance variables from local variables, call constructors,
or invoke instance methods

(iv) int a = 3; → Stores primitive int value in stack memory.


Integer b = new Integer(3); → Creates an Integer object in heap
memory (deprecated, prefer Integer b = 3;).

(v) The final keyword is used to prevent a class from being extended.

(vi) Yes, we can create a reference of an interface, but it must be


assigned an object of a class that implements the interface. It is used for
achieving polymorphism and loose coupling.

(vii) Java String: Immutable and part of the java.lang package.


C/C++ String: A character array (char[]), mutable, and does not
support built-in string manipulation methods like Java.

Click :Youtube Channel | Free Material | Download App


Q3(A) Discuss benefits of multithreading? (3M)

Benefits of Multithreading in Java


1. Improved Performance
o Multiple threads execute concurrently, utilizing multi-core
processors efficiently.
2. Better CPU Utilization
o Threads keep the CPU busy by executing tasks in parallel,
reducing idle time.
3. Faster Execution
o Tasks like file processing, network operations, or database
queries can run simultaneously.
4. Enhanced Responsiveness
o GUI applications remain responsive by running heavy
computations in separate threads.
5. Efficient Resource Sharing
o Threads share memory space within the same process,
reducing overhead.
6. Simplifies Complex Applications
o Helps in handling tasks like background processing, gaming,
and real-time simulations.
7. Better Scalability
 Makes applications scalable by efficiently distributing
workloads across multiple threads

Click :Youtube Channel | Free Material | Download App


Q3(B) Develop a program which stores name of districts in Gujrat in
array of String. The array specified capacity to store 5 districts. The user
will be able to print name of district based on array index e.g. (0 will
print Ahemdabad). If the specified index is out of bounds, program will
display the message Out of Bounds. (4M)

ANS
import java.util.Scanner;
public class DistrictsOfGujarat {
public static void main(String[] args) {
// Array to store 5 district names
String[] districts = {"Ahmedabad", "Surat", "Vadodara",
"Rajkot", "Bhavnagar"};
// Scanner to take user input
Scanner scanner = new Scanner(System.in);
// Asking user for index input
System.out.print("Enter the index (0-4) to get the district name: ");
try {
int index = scanner.nextInt(); // Taking index input
// Validating index range
if (index >= 0 && index < districts.length) {
System.out.println("District: " + districts[index]);
} else {
System.out.println("Out of Bounds");
}
} catch (Exception e) {
System.out.println("Invalid input! Please enter an integer.");
} finally {
scanner.close(); // Closing the scanner
}
}
}
OUTPUT
Valid Input
Enter the index (0-4) to get the district name: 2
District: Vadodara
Out of Bounds Input
Enter the index (0-4) to get the district name: 7
Out of Bounds

Click :Youtube Channel | Free Material | Download App


Q3(C) Characterize the two ways of implementing thread in Java?
Illustrate each method by example (7M)

ANS
Two Ways to Implement Threads in Java
Java provides two main ways to create and implement threads:
1. By Extending the Thread Class
2. By Implementing the Runnable Interface

1⃣ Extending the Thread Class


 In this approach, a class extends the Thread class and overrides
the run() method.
 The start() method is called to begin execution.
 Limitation: Since Java does not support multiple inheritance,
extending Thread prevents extending another class.
Example
class MyThread extends Thread {
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println("Thread running: " + i);
try {
Thread.sleep(500); // Pause execution for 500ms
} catch (InterruptedException e) {
System.out.println(e);
}
}
}

public static void main(String[] args) {


MyThread t1 = new MyThread(); // Creating thread object
t1.start(); // Starting the thread
}
}
Output
Thread running: 1
Thread running: 2

Click :Youtube Channel | Free Material | Download App


Thread running: 3
Thread running: 4
Thread running: 5

2⃣ Implementing the Runnable Interface


 The Runnable interface has a single method: run().
 A class implements Runnable and defines the run() method.
 The Thread class is then used to create and start a thread.
 Advantage: Allows multiple inheritance since it does not extend
Thread.
Example
class MyRunnable implements Runnable {
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println("Runnable Thread running: " + i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
System.out.println(e);
}
}
}

public static void main(String[] args) {


MyRunnable myRunnable = new MyRunnable(); // Creating
Runnable object
Thread t1 = new Thread(myRunnable); // Passing Runnable object
to Thread
t1.start(); // Starting the thread
}
}
Output
Runnable Thread running: 1
Runnable Thread running: 2
Runnable Thread running: 3
Runnable Thread running: 4
Runnable Thread running: 5

Click :Youtube Channel | Free Material | Download App


OR Q3(A) Explain the use of finally. Show the type of code usually kept
in finally? (3M)

ANS

The finally block in Java is used to execute code regardless of


whether an exception occurs or not. It is typically used for
resource cleanup (e.g., closing files, database connections,
releasing locks).
Key Features of finally
1. Always Executes: The code inside the finally block
executes whether an exception occurs or not.
2. Used for Cleanup: Commonly used to close resources like
files, database connections, and sockets.
3. Works with try and catch: It is optional but often used
alongside try and catch.
4. Executes Even with return: Even if a return statement is
present in try or catch, the finally block still executes
before returning.

Example 1: finally Executes Even If No Exception Occurs


java
public class FinallyExample {
public static void main(String[] args) {
try {
System.out.println("Inside try block");
} catch (Exception e) {
System.out.println("Inside catch block");
} finally {
System.out.println("Inside finally block");
}
}
}
Output
Inside try block
Inside finally block
Since there is no exception, catch is skipped, but finally still
executes.

Click :Youtube Channel | Free Material | Download App


OR Q3(B) Distinguish unchecked exception and checked
exception? Give example of each type of exception (4M)

ANS

Feature Checked Exception Unchecked Exception


Behaviour Checked exceptions are Unchecked exceptions are
checked at compile time. checked at run time.
Base class Derived from Exception Derived
from RuntimeException
Cause External factors like file I/O Programming bugs like
and database connection logical Errors cause the
cause checked Exception. unchecked Exception.
Handling checked exception must be No handling is required
Requirement handled using try-catch
block or must be declared
using throw keyword
Examples IOException, SQLException NullPointerException, ArrayI
, FileNotFoundException. ndexOutOfBoundsException.

Click :Youtube Channel | Free Material | Download App


OR Q3(C) Implement java code to take some (say 10) Strings from
users. Put all the input Strings in an array (String name[]). Provide
implementation of following methods:
a) search(String s) will return index of String passed in method if
String S is found in name, otherwise return -1.
b) sort() will print sorted String array to user

ANS
import java.util.Arrays;
import java.util.Scanner;

public class StringArrayOperations {


private String[] name = new String[10];

// Method to search for a string in the array


public int search(String s) {
for (int i = 0; i < name.length; i++) {
if (name[i].equals(s)) {
return i; // Return index if found
}
}
return -1; // Return -1 if not found
}

// Method to sort and print the string array


public void sort() {
Arrays.sort(name);
System.out.println("Sorted Strings: " + Arrays.toString(name));
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
StringArrayOperations obj = new StringArrayOperations();

Click :Youtube Channel | Free Material | Download App


// Taking 10 string inputs from the user
System.out.println("Enter 10 Strings:");
for (int i = 0; i < 10; i++) {
obj.name[i] = scanner.nextLine();
}

// Sorting the array and displaying sorted strings


obj.sort();

// Searching for a string


System.out.print("Enter a string to search: ");
String searchString = scanner.nextLine();
int index = obj.search(searchString);

// Displaying search result


if (index != -1) {
System.out.println("String found at index: " + index);
} else {
System.out.println("String not found in the array.");
}

scanner.close();
}
}

Click :Youtube Channel | Free Material | Download App


Q4(A) Write a program to find out whether given number is
palindrome or not? (3M)

import java.util.Scanner;

public class PalindromeNumber {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Taking input from user


System.out.print("Enter a number: ");
int num = scanner.nextInt();

// Check if the number is palindrome


if (isPalindrome(num)) {
System.out.println(num + " is a Palindrome.");
} else {
System.out.println(num + " is not a Palindrome.");
}

scanner.close();
}
// Method to check if a number is palindrome
public static boolean isPalindrome(int num) {
int originalNum = num;
int reversedNum = 0;

while (num > 0) {


int digit = num % 10; // Extract last digit
reversedNum = reversedNum * 10 + digit; // Build reversed
number
num /= 10; // Remove last digit
}
return originalNum == reversedNum; // Check if original and
reversed are same
}
}

Click :Youtube Channel | Free Material | Download App


Q4(B) Outline use of throw in exception handling with example. (4M)

ANS

The throw keyword in Java is used to explicitly throw an exception


from a method or block of code. It is useful when we want to create
custom exceptions or force an exception under certain conditions.
Key Points about throw:
 Used to throw an exception explicitly.
 Can be used for both built-in exceptions and custom exceptions.
 The thrown exception must be an instance of a subclass of
Throwable (i.e., Exception or Error).
 Once an exception is thrown, it must be handled using try-catch
or declared using throws.

Example 1: Throwing a Built-in Exception


public class ThrowExample {
// Method to check if a number is negative
public static void checkNumber(int num) {
if (num < 0) {
throw new IllegalArgumentException("Negative numbers are
not allowed!");
} else {
System.out.println("Valid number: " + num);
}
}

public static void main(String[] args) {


try {
checkNumber(-5); // This will throw an exception
} catch (IllegalArgumentException e) {
System.out.println("Exception caught: " + e.getMessage());
}
}
}

Click :Youtube Channel | Free Material | Download App


Q4(C) Give Definitions: static, finalize, final (7M)

ANS

1. static (Keyword & Modifier)


 The static keyword is used to indicate that a variable, method, or
block belongs to class rather than a specific instance of the class.
 Usage: Shared among all instances of the class.
 Example:
class Example {
static int count = 0; // Static variable

static void display() { // Static method


System.out.println("Count: " + count);
}
}

public class Test {


public static void main(String[] args) {
Example.count = 10;
Example.display(); // No need to create an object
}
}
Output:
Count: 10

2. final (Modifier for Variables, Methods, and Classes)


 The final keyword is used to prevent modification.
 For Variables: Prevents the value from changing (constant).
 For Methods: Prevents method overriding.
 For Classes: Prevents class inheritance.
 Example:
class Parent {
final void show() { // Method cannot be overridden
System.out.println("Final method");

Click :Youtube Channel | Free Material | Download App


}
}

final class Child extends Parent { // Cannot be extended


// public void show() {} // Error: Cannot override final method
}

public class Test {


public static void main(String[] args) {
final int x = 10;
// x = 20; // Error: Cannot change final variable value
System.out.println(x);
}
}
Output: 10

3. finalize() (Method)
 The finalize() method is called by the Garbage Collector (GC)
before an object is removed from memory.
 Used for cleanup operations (e.g., closing files, releasing
resources).
 Example:
class Example {
protected void finalize() {
System.out.println("Object is being garbage collected.");
}
}

public class Test {


public static void main(String[] args) {
Example obj = new Example();
obj = null; // Mark object for garbage collection
System.gc(); // Request GC
}
}
Output (may vary):
Object is being garbage collected.

Click :Youtube Channel | Free Material | Download App


OR Q4(A) Elaborate the role of java garbage collector (3M)

1. Introduction to Garbage Collection (GC)


 In Java, memory management is handled automatically using
Garbage Collection (GC).
 The Garbage Collector (GC) is responsible for reclaiming memory
occupied by unused objects to prevent memory leaks

2. Why is Garbage Collection Needed?


 In languages like C/C++, developers must manually allocate
(malloc()) and deallocate (free()) memory.
 Java automates this process, ensuring efficient memory
management and avoiding memory leaks.

3. How Does Java's Garbage Collector Work?


 Unused objects (no longer referenced) are identified and removed
from memory.
 Java’s GC works in the heap memory, where objects are
dynamically allocated.
 When an object no longer has active references, GC removes it.

4. Java Garbage Collection Process


Java uses different algorithms for garbage collection:
 Mark and Sweep Algorithm:
o Mark Phase: Identifies reachable objects.
o Sweep Phase: Removes unreferenced objects.

 Generational Garbage Collection:


o Java divides memory into Young Generation, Old
Generation, and Permanent Generation (or Metaspace in
Java 8+).
o Young Generation: Newly created objects.
o Old Generation: Long-lived objects.

Click :Youtube Channel | Free Material | Download App


OR Q4(B) State four similarities between Interfaces and Classes. (4M)

1) Both Define a Type


 Interfaces and classes can be used as types in Java.
 Objects can be created based on their type (class or interface
reference).
 Example:
interface Animal {
void makeSound();
}
class Dog implements Animal
{
public void makeSound()
{
System.out.println("Bark!"); } }
Animal a = new Dog(); // Animal type reference

2) Both Can Contain Methods


 Both interfaces and classes define methods.
 Interfaces (from Java 8+) can have default and static methods
similar to classes.
 Example:
interface Vehicle {
default void start()
{
System.out.println("Vehicle is starting");
}
}
class Car implements Vehicle
{
}

3) Both Support Inheritance


 Classes support inheritance (using extends).
 Interfaces support multiple inheritance (using extends).
 Example:

Click :Youtube Channel | Free Material | Download App


interface A {
void methodA();
}
interface B extends A {
void methodB();
} // Interface can extend another interface

4) Both Need to Be Implemented/Instantiated for Use


 Classes must be instantiated using new.
 Interfaces must be implemented by a class or used with
anonymous classes/lambdas.
 Example:
interface Playable {
void play();
}
class Music implements Playable {
public void play()
{
System.out.println("Playing music");
}
}
Playable p = new Music(); // Implemented and instantiated

Click :Youtube Channel | Free Material | Download App


OR Q4(C) Differentiate between ArrayList and LinkedList? Which list
should you use to insert and delete elements at the beginning of a list?
What methods are in LinkedList but not in ArrayList? (7M)

ArrayList LinkedList
1) ArrayList internally uses LinkedList internally uses
a dynamic array to store the a doubly linked list to store the
elements. elements.
2) Manipulation with ArrayList Manipulation with LinkedList
is slow because it internally uses is faster than ArrayList because it
an array. If any element is uses a doubly linked list, so no bit
removed from the array, all the shifting is required in memory.
other elements are shifted in
memory.
3) An ArrayList class can act as a LinkedList class can act as a list
list only because it implements and queue both because it
List only. implements List and Deque
interfaces.
4) ArrayList is better for storing LinkedList is better for
and accessing data. manipulating data.
5) The memory location for the The location for the elements of a
elements of an ArrayList is linked list is not contagious.
contiguous.

Which List to Use for Insertions and Deletions at the Beginning?


 LinkedList should be used because:
✅ Insertion at the beginning is O(1) (only pointer updates).
❌ In ArrayList, inserting at the beginning requires shifting all
elements (O(n)).

Click :Youtube Channel | Free Material | Download App


Methods in LinkedList but Not in ArrayList
LinkedList has additional methods since it implements both List and
Deque interfaces:
1. addFirst(E e) – Adds element at the beginning.
2. addLast(E e) – Adds element at the end.
3. removeFirst() – Removes the first element.
4. removeLast() – Removes the last element.
5. getFirst() – Retrieves the first element without removal.
6. getLast() – Retrieves the last element without removal.

Q5(A) List various classes for Binary Input Output? (3M)

ANS

Java provides several binary input and output stream classes under the
java.io package for handling binary data. These classes are divided into
input streams (for reading binary data) and output streams (for writing
binary data).

1⃣ Binary Input Stream Classes (Reading Binary Data)


Class Description
InputStream Abstract superclass for all byte input
streams.
FileInputStream Reads bytes from a file.
ByteArrayInputStream Reads bytes from an in-memory byte array.
DataInputStream Reads primitive data types (int, float,
double, etc.) in a machine-independent way.
BufferedInputStream Improves performance by buffering input
data.
ObjectInputStream Reads objects (deserialization) from a
stream.
Example: Reading from a File Using FileInputStream
import java.io.*;
public class BinaryReadExample {
public static void main(String[] args) {
try (FileInputStream fis = new FileInputStream("data.bin")) {

Click :Youtube Channel | Free Material | Download App


int byteData;
while ((byteData = fis.read()) != -1) {
System.out.print(byteData + " "); // Prints byte values
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

2⃣ Binary Output Stream Classes (Writing Binary Data)


Class Description
OutputStream Abstract superclass for all byte output
streams.
FileOutputStream Writes bytes to a file.
ByteArrayOutputStream Writes bytes to an in-memory byte array.
DataOutputStream Writes primitive data types in a portable
format.
BufferedOutputStream Improves performance by buffering
output data.
ObjectOutputStream Writes objects (serialization) to a stream.
Example: Writing to a File Using FileOutputStream
import java.io.*;

public class BinaryWriteExample {


public static void main(String[] args) {
try (FileOutputStream fos = new FileOutputStream("data.bin")) {
fos.write(65); // Writing ASCII value of 'A'
fos.write(66); // Writing ASCII value of 'B'
fos.write(67); // Writing ASCII value of 'C'
System.out.println("Data written successfully.");
} catch (IOException e) {
e.printStackTrace();
}
}
}

Click :Youtube Channel | Free Material | Download App


Q5(B) Characterize the role of Iterator interface? (4M)

ANS
The Iterator interface in Java, located in the java.util package, is used
to traverse elements of a collection one by one without exposing its
underlying structure. It provides a universal way to iterate over
different collection types (like ArrayList, LinkedList, HashSet, etc.).

Key Features of Iterator Interface


1. Traverses Elements Sequentially – Allows accessing elements one
at a time.
2. Works with Different Collection Types – Can be used with any
Collection (List, Set, Queue, etc.).
3. Prevents Concurrent Modification Issues – Detects modifications
made during iteration.
4. Does Not Support Backward Traversal – Moves only forward (use
ListIterator for bidirectional traversal).

Methods of Iterator Interface


Method Description
boolean hasNext() Returns true if there are more elements to iterate.
E next() Returns the next element in the collection.
void remove() Removes the last element returned by next().

Example: Using Iterator to Traverse an ArrayList


import java.util.*;

public class IteratorExample {


public static void main(String[] args) {
// Creating a list of names
ArrayList<String> names = new ArrayList<>();
names.add("Yash");
names.add("Amit");
names.add("Neha");
names.add("Priya");

Click :Youtube Channel | Free Material | Download App


// Getting an iterator for the list
Iterator<String> iterator = names.iterator();

// Traversing the list using iterator


while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}
Output:
Yash
Amit
Neha
Priya

Removing an Element While Iterating


import java.util.*;

public class RemoveUsingIterator {


public static void main(String[] args) {
ArrayList<Integer> numbers = new
ArrayList<>(Arrays.asList(10, 20, 30, 40, 50));

Iterator<Integer> iterator = numbers.iterator();

while (iterator.hasNext()) {
int num = iterator.next();
if (num == 30) {
iterator.remove(); // Removing 30 from the list
}
}

System.out.println(numbers); // Output: [10, 20, 40, 50]


}
}

Click :Youtube Channel | Free Material | Download App


Q5(C) Explain DataInputStream and DataOutputStream Classes?
Implement a java program to demonstrate any one of them? (7M)

ANS
The DataInputStream and DataOutputStream classes are used for
reading and writing primitive data types (int, double, float, char, etc.) in
binary format rather than text format. These classes are part of the
java.io package.

1. DataOutputStream Class
 Used to write primitive data (int, double, float, boolean, char, etc.)
to a file in a machine-readable binary format.
 Provides methods like writeInt(), writeDouble(), writeUTF(), etc.
 Ensures efficient data storage and retrieval.
Example Methods:
writeInt(int val); // Writes an integer
writeDouble(double val); // Writes a double value
writeUTF(String str); // Writes a String in UTF format

2. DataInputStream Class
 Used to read primitive data from a binary file created using
DataOutputStream.
 Reads data in the same sequence it was written.
 Provides methods like readInt(), readDouble(), readUTF(), etc.

Example Methods:
readInt(); // Reads an integer
readDouble(); // Reads a double value
readUTF(); // Reads a String in UTF format

Java Program to Demonstrate DataOutputStream and


DataInputStream
This program writes integer, double, and string values to a file using
DataOutputStream and then reads them back using DataInputStream.
import java.io.*;

public class DataStreamExample {

Click :Youtube Channel | Free Material | Download App


public static void main(String[] args) {
String fileName = "data.bin"; // File to store binary data

// Writing data to file using DataOutputStream


try (DataOutputStream dos = new DataOutputStream(new
FileOutputStream(fileName))) {
dos.writeInt(100);
dos.writeDouble(99.99);
dos.writeUTF("Hello, Java!");
System.out.println("Data written successfully.");
} catch (IOException e) {
System.out.println("Error writing data: " + e.getMessage());
}

// Reading data from file using DataInputStream


try (DataInputStream dis = new DataInputStream(new
FileInputStream(fileName))) {
int num = dis.readInt();
double price = dis.readDouble();
String text = dis.readUTF();

System.out.println("Data read from file:");


System.out.println("Integer: " + num);
System.out.println("Double: " + price);
System.out.println("String: " + text);
} catch (IOException e) {
System.out.println("Error reading data: " + e.getMessage());
}
}
}

Output
Data written successfully.
Data read from file:
Integer: 100
Double: 99.99
String: Hello, Java

Click :Youtube Channel | Free Material | Download App


OR Q5(A) What do you understand by JavaFX? How it is different
from AWT? (3M)

ANS
JavaFX is a modern GUI framework for building rich internet
applications (RIA) in Java. It is part of the Java Standard Library
since Java 8 and is meant to replace Swing and AWT for developing
desktop applications.
 Uses FXML (XML-based UI design) for separating UI from
business logic.
 Supports CSS for styling, like web technologies.
 Provides built-in support for 2D and 3D graphics, animations,
and media playback.
 Uses a scene graph-based rendering system for high-performance
UI.
 Supports hardware acceleration for smooth graphics.
 Works on Windows, macOS, Linux, and even mobile devices (via
frameworks like Gluon).

Difference Between JavaFX and AWT


Feature JavaFX AWT (Abstract
Window Toolkit)
Introduced In Java 8 Java 1.0 (1995)
UI Rendering Uses Scene Graph Uses native OS
components
(heavyweight)
Graphics & Supports 2D & 3D Basic UI, no built-in
Animation graphics, built-in animations
animation
Styling Uses CSS for styling Limited styling using
Java Code
Multimedia Supports audio, video, No built-in multimedia
Support and images support
Event Handling More flexible, uses Traditional event
lambda expressions model

Click :Youtube Channel | Free Material | Download App


Performance Uses hardware Slower, uses native OS
acceleration, lightweight rendering
components
FXML Support Supports FXML No XML-based UI
(separates UI and logic) support
Cross-Platform Works consistently across UI looks different
platforms based on OS

OR Q5(B) Explain ArrayList Class with its methods? (4M)

ANS

ArrayList is a resizable array implementation of the List interface in


Java. It is part of the java.util package and provides dynamic arrays,
which can grow or shrink as needed.
Key Features of ArrayList:
 Dynamic resizing (unlike arrays, which have a fixed size).
 Allows duplicate elements.
 Maintains insertion order.
 Allows random access using indexes (O(1) time complexity).
 Not synchronized (use Collections.synchronizedList() for thread
safety).

Declaration and Initialization


import java.util.ArrayList;
public class ArrayListExample {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>(); // Creating ArrayList
list.add("Apple");
list.add("Banana");
list.add("Mango");
System.out.println(list); // Output: [Apple, Banana, Mango]
}
}

Click :Youtube Channel | Free Material | Download App


Common Methods in ArrayList
Method Description
add(E e) Adds an element to the end of the list.
add(int index, E Inserts an element at a specific index.
element)
get(int index) Retrieves an element at the specified index.
set(int index, E Replaces an element at the given index.
element)
remove(int index) Removes an element at the specified index.
remove(Object o) Removes the first occurrence of the specified
element.
size() Returns the number of elements in the list.
contains(Object o) Returns true if the list contains the specified
element.
isEmpty() Returns true if the list is empty.
clear() Removes all elements from the list.
indexOf(Object o) Returns the index of the first occurrence of
the element, or -1 if not found.
lastIndexOf(Object o) Returns the last occurrence of an element.
toArray() Converts the ArrayList to an array.
iterator() Returns an iterator for traversing elements.

Click :Youtube Channel | Free Material | Download App


OR Q5(C) Design and develop EMI Calculator using JavaFX? The user
will enter a loan amount, annual interest 3 rate, and number of years
and click the Calculate button to get EMI and total payment ? formula
is EMI= P*r*(1+r)n /((1+r)n -1) P is Principal Loan Amount r is rate of
interest calculated on monthly basis. (i.e., r = Rate of Annual
interest/12/100. If rate of interest is 10.5% per annum, then r =
10.5/12/100=0.00875) n is loan term / tenure / duration in number of
months? (7M)

ANS
\

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;

public class EMICalculator extends Application {

@Override
public void start(Stage primaryStage) {
// Create UI elements
Label lblInterestRate = new Label("Annual Interest Rate:");
TextField txtInterestRate = new TextField();

Label lblYears = new Label("Number of Years:");

Click :Youtube Channel | Free Material | Download App


TextField txtYears = new TextField();

Label lblLoanAmount = new Label("Loan Amount:");


TextField txtLoanAmount = new TextField();

Label lblMonthlyPayment = new Label("Monthly Payment:");


TextField txtMonthlyPayment = new TextField();
txtMonthlyPayment.setEditable(false); // Read-only

Label lblTotalPayment = new Label("Total Payment:");


TextField txtTotalPayment = new TextField();
txtTotalPayment.setEditable(false); // Read-only

Button btnCalculate = new Button("Calculate");

// Layout GridPane
GridPane gridPane = new GridPane();
gridPane.setPadding(new Insets(15));
gridPane.setVgap(10);
gridPane.setHgap(10);

// Add elements to the grid


gridPane.add(lblInterestRate, 0, 0);
gridPane.add(txtInterestRate, 1, 0);

gridPane.add(lblYears, 0, 1);
gridPane.add(txtYears, 1, 1);

gridPane.add(lblLoanAmount, 0, 2);
gridPane.add(txtLoanAmount, 1, 2);

gridPane.add(lblMonthlyPayment, 0, 3);
gridPane.add(txtMonthlyPayment, 1, 3);

gridPane.add(lblTotalPayment, 0, 4);
gridPane.add(txtTotalPayment, 1, 4);

Click :Youtube Channel | Free Material | Download App


gridPane.add(btnCalculate, 1, 5);

// Button event handler


btnCalculate.setOnAction(e -> {
try {
double P = Double.parseDouble(txtLoanAmount.getText()); //
Loan Amount
double annualRate =
Double.parseDouble(txtInterestRate.getText()); // Annual Interest Rate
int years = Integer.parseInt(txtYears.getText()); // Number of
Years

// Convert to monthly interest rate


double r = annualRate / 12 / 100;
int n = years * 12; // Convert years to months

// EMI formula
double EMI = (P * r * Math.pow(1 + r, n)) / (Math.pow(1 + r,
n) - 1);
double totalPayment = EMI * n;

// Display results
txtMonthlyPayment.setText(String.format("$%.2f", EMI));
txtTotalPayment.setText(String.format("$%.2f",
totalPayment));

} catch (NumberFormatException ex) {


// Error handling
Alert alert = new Alert(Alert.AlertType.ERROR, "Invalid
Input! Please enter numeric values.", ButtonType.OK);
alert.showAndWait();
}
});

// Set up stage
Scene scene = new Scene(gridPane, 350, 250);
primaryStage.setTitle("Loan Calculator");

Click :Youtube Channel | Free Material | Download App


primaryStage.setScene(scene);
primaryStage.show();
}

public static void main(String[] args) {


launch(args);
}
}

Click :Youtube Channel | Free Material | Download App

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy