WINTER 2023 _ OOP in Java
WINTER 2023 _ OOP in Java
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;
}
}
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?
***********
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
// (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
}
}
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.
// Creating Objects
public class CarDemo {
public static void main(String[] args) {
Car car1 = new Car(); // Object creation
car1.brand = "Toyota";
car1.speed = 120;
car1.display();
car2.display();
}
}
2. Key Relationships
1. Instance of a Class:
o Objects are instances of a class.
a single class.
2. Memory Allocation:
o A class does not occupy memory until an object is created.
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.
(display()).
The object (e.g., car1, car2) has actual values for these attributes.
ANS
Analysis of Given Code & Errors
Fixed Code
public class Circle {
private double radius;
// Corrected constructor
public Circle(double radius) {
this.radius = radius; // Fixed assignment
}
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.
ANS
// Rectangle class
public class Rectangle {
// Fields
private int length;
private int width;
(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).
(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
(v) The final keyword is used to prevent a class from being extended.
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
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
ANS
ANS
ANS
import java.util.Arrays;
import java.util.Scanner;
scanner.close();
}
}
import java.util.Scanner;
scanner.close();
}
// Method to check if a number is palindrome
public static boolean isPalindrome(int num) {
int originalNum = num;
int reversedNum = 0;
ANS
ANS
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.");
}
}
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.
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).
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.).
while (iterator.hasNext()) {
int num = iterator.next();
if (num == 30) {
iterator.remove(); // Removing 30 from the list
}
}
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
Output
Data written successfully.
Data read from file:
Integer: 100
Double: 99.99
String: Hello, Java
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).
ANS
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;
@Override
public void start(Stage primaryStage) {
// Create UI elements
Label lblInterestRate = new Label("Annual Interest Rate:");
TextField txtInterestRate = new TextField();
// Layout GridPane
GridPane gridPane = new GridPane();
gridPane.setPadding(new Insets(15));
gridPane.setVgap(10);
gridPane.setHgap(10);
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);
// 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));
// Set up stage
Scene scene = new Scene(gridPane, 350, 250);
primaryStage.setTitle("Loan Calculator");