Java Winter 23
Java Winter 23
Java Winter 23
b) Define constructor.
Ans.Constructor: A constructor is a special member which initializes an object immediately
upon creation. It has the same name as class name in which it resides and it is syntactically
similar to any method. When a constructor is not defined, java executes a default constructor
which initializes all numeric members to zero and other types to null or spaces. Once defined,
constructor is
automatically called immediately after the object is created before new operator completes.
Types of constructors:
1. Default constructor
2. Parameterized constructor
3. Copy constructor
Array Initialization
dataType[] arrayName = {value1, value2, value3, ...};
e) Differentiate between starting thread with run ( ) method and start ( ) method.
Ans.
Aspect run() Method start() Method
Invoca Directly called like a normal method Initiates a new thread of execution
tion
Thread Does not create a new thread Creates a new thread
Creatio
n
Execut Code runs in the current thread Code runs in a new, separate thread
ion
Use Useful for testing the thread's run() Used to start the thread and execute run()
Case method directly in a new thread
Examp java Thread t = new Thread(new java Thread t = new Thread(new
le MyRunnable()); t.run(); // No new thread is MyRunnable()); t.start(); // New thread is
created created
f) State the classes that can an applet extend.
Ans.
1. java.applet.Applet:This is the original applet class provided in Java 1.0. When you extend
this class, you can create basic applets that include methods like init(), start(), stop(), and
destroy(), which are used for controlling the applet's lifecycle.
2. javax.swing.JApplet :This class extends Applet and provides a Swing-based applet. It allows
you to create GUI components using Swing, which is more flexible and powerful compared to
the AWT components that Applet supports.
g) Give syntax to open a file using Inputstream class.
Ans.InputStream inputStream = new FileInputStream("path/to/file");
Thread Life Cycle Thread has five different states throughout its
life.
1. Newborn State
2. Runnable State
3. Running State
4. Blocked State
5. Dead State
Thread should be in any one state of above and it can be move from one state to another by
different methods and ways.
Newborn state: When a thread object is created it is said to be in a new born state. When the
thread is in a new born state it is not scheduled running from this state it can be scheduled for
running by start() or killed by stop(). If put in a queue it moves to runnable state.
Runnable State: It means that thread is ready for execution and is waiting for the availability of
the processor i.e. the thread has joined the queue and is waiting for execution. If all threads have
equal priority, then they are given time slots for execution in round robin fashion. The thread that
relinquishes control joins the queue at the end and again waits for its turn. A thread can
relinquish the control to another before its turn comes by yield().
Running State: It means that the processor has given its time to the thread for execution. The
thread runs until it relinquishes control on its own or it is pre-empted by a higher priority thread.
Blocked state: A thread can be temporarily suspended or blocked from entering into the
runnable and running state by using either of the following thread method.
1) suspend() : Thread can be suspended by this method. It can be rescheduled by resume().
2) wait(): If a thread requires to wait until some event occurs, it can be done using wait method
and can be scheduled to run again by notify().
3) sleep(): We can put a thread to sleep for a specified time period using sleep(time) where time
is in ms. It re-enters the runnable state as soon as period has elapsed /over
Dead State: Whenever we want to stop a thread form running further we can call its stop().The
statement causes the thread to move to a dead state. A thread will also move to dead state
automatically when it reaches to end of the method. The stop method may be used when the
premature death is required.
public ATMMachine() {
this.balance = 0.0; // Initialize balance to zero
}
// Method to check balance
public void checkBalance() {
System.out.println("Your current balance is: $" + balance);
}
// Method to deposit money
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
System.out.println("Successfully deposited: $" + amount);
} else {
System.out.println("Deposit amount must be positive.");
}
}
// Method to withdraw money
public void withdraw(double amount) {
if (amount <= balance && amount > 0) {
balance -= amount;
System.out.println("Successfully withdrawn: $" + amount);
} else if (amount > balance) {
System.out.println("Insufficient balance.");
} else {
System.out.println("Withdrawal amount must be positive.");
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ATMMachine atm = new ATMMachine(); // Create an instance of ATMMachine
while (true) {
System.out.println("\n--- ATM Menu ---");
System.out.println("1. Check Balance");
System.out.println("2. Deposit");
System.out.println("3. Withdraw");
System.out.println("4. Exit");
System.out.print("Choose an option (1-4): ");
int choice = scanner.nextInt(); // Read user choice
switch (choice) {
case 1:
atm.checkBalance(); // Check balance
break;
case 2:
System.out.print("Enter amount to deposit: $");
double depositAmount = scanner.nextDouble();
atm.deposit(depositAmount); // Deposit money
break;
case 3:
System.out.print("Enter amount to withdraw: $");
double withdrawAmount = scanner.nextDouble();
atm.withdraw(withdrawAmount); // Withdraw money
break;
case 4:
System.out.println("Thank you for using the ATM. Goodbye!");
scanner.close();
return; // Exit the program
default:
System.out.println("Invalid choice. Please choose a valid option.");
}
}
}
}
d) Differentiate between Byte Stream Class and Character Stream Class. (Any four points)
Ans.
Aspect Character Streams Byte Streams
Data Handling Handle character-based data Handle raw binary data
Representation Classes end with "Reader" or Classes end with "InputStream" or
"Writer" "OutputStream"
Suitable for Textual data, strings, human- Non-textual data, binary files,
readable info multimedia
Character Encoding Automatic encoding and decoding No encoding or decoding
Text vs non-Text Text-based data, strings Binary data, images, audio, video
data
Performance Additional conversion may impact Efficient for handling large binary
performance data
Handle Large Text May impact performance due to Efficient, no encoding overhead
Files encoding
String Operations Convenient methods for string Not specifically designed for string
operations operations
Convenience Higher-level abstractions for text Low-level interface for byte data
Methods data
Reading Line by Line Convenient methods for reading Byte-oriented, no built-in line-reading
lines methods
File Handling Read/write text files Read/write binary files
Network Sending/receiving text data Sending/receiving binary data
Communication
Handling Not designed for handling binary Suitable for handling binary
Images/Audio/Video data directly multimedia data
Text Encoding Supports various character No specific text encoding support
encodings
class Rectangle
{
int length;
int breadth;
Rectangle(int l, int b)
{
length = l;
breadth= b;
}
//copy constructor
Rectangle(Rectangle obj)
{
length = obj.length;
breadth= obj.breadth;
}
public static void main(String[] args)
{
Rectangle r1= new Rectangle(5,6);
Rectangle r2= new Rectangle(r1);
System.out.println("Area of First Rectangle : "+
(r1.length*r1.breadth));
System .out.println("Area of First Second Rectangle : "+
(r1.length*r1.breadth));
}
}
// Subclass 1
class Dog extends Animal {
void bark() {
System.out.println("The dog barks.");
}
}
// Subclass 2
class Cat extends Animal {
void meow() {
System.out.println("The cat meows.");
}
}
// Main class
public class HierarchicalInheritanceExample {
public static void main(String[] args) {
// Creating an object of Dog
Dog dog = new Dog();
dog.eat(); // Calling method from Animal class
dog.bark(); // Calling method from Dog class
Example:
import javax.swing.*;
import java.awt.*;
add(textArea);
setVisible(true);
}
appendFileContent(sourceFilePath, destinationFilePath);
}
public static void appendFileContent(String source, String destination) {
try (BufferedReader reader = new BufferedReader(new FileReader(source));
BufferedWriter writer = new BufferedWriter(new FileWriter(destination, true))) { //
'true' for append mode
String line;
while ((line = reader.readLine()) != null) { // Read until the end of the source file
writer.write(line); // Write the line to the destination file
writer.newLine(); // Add a new line after each line
}
System.out.println("Content appended successfully from " + source + " to " +
destination);
} catch (IOException e) {
System.out.println("An error occurred: " + e.getMessage());
}
}
}
a) Explain vector with the help of example. Explain any 3 methods of vector class.
Ans.A Vector is a part of the Java Collection Framework and is used to store a dynamically sized
collection of objects. It implements the List interface and is similar to an array but provides more
flexible sizing and built-in synchronization.
Characteristics of Vector
1. Dynamic Size: Unlike arrays, which have a fixed size, a Vector can grow and shrink as
elements are added or removed.
2. Thread Safety: The methods in a Vector are synchronized, which means that it is thread-
safe and can be used safely in concurrent applications.
3. Element Access: Like arrays, Vectors allow for random access to their elements through
an index.
4. Growth Policy: When a Vector needs to grow, it typically doubles its size, which can lead
to wasted space if not managed properly.
Example:
import java.util.Vector;
The Vector class in Java is part of the java.util package and is a dynamic array that can grow as
needed to accommodate new elements. It implements the List interface and is synchronized,
making it thread-safe. Here, we'll explore three important methods of the Vector class in detail:
add(), get(), and remove().
1. add(E e)
Description: The add() method is used to append an element to the end of the vector. If the
vector's capacity is reached, it will automatically increase its size to accommodate the new
element.
Syntax:
public boolean add(E e)
2. get(int index)
Description: The get() method is used to retrieve an element at a specified index in the vector.
The index is zero-based, meaning the first element is at index 0.
Syntax:
public E get(int index)
3. remove(int index)
Description: The remove() method is used to remove an element from the vector at a specified
index. After removal, all subsequent elements are shifted to the left (decreased in index).
Syntax:
public E remove(int index)
b) Develop and Interest Interface which contains Simple Interest and Compound Interest
methods and static final field of rate 25%. Write a class to implement those methods.
Ans.
// Step 1: Define the Interest Interface
public interface Interest {
double RATE = 25.0; // Static final field for interest rate
@Override
public double calculateSimpleInterest(double principal, double time) {
return (principal * RATE * time) / 100; // Simple Interest formula
}
@Override
public double calculateCompoundInterest(double principal, double time, int
numberOfTimesCompounded) {
return principal * Math.pow((1 + RATE / (100 * numberOfTimesCompounded)),
numberOfTimesCompounded * time) - principal; // Compound Interest
formula
}
}
// Example values
double principal = 1000; // Principal amount
double time = 2; // Time in years
int numberOfTimesCompounded = 4; // Quarterly compounding
try {
checker.checkString(testString);
} catch (NoMatchException e) {
System.out.println("Exception caught: " + e.getMessage());
}
}
}
Output:
Exception caught: Input does not match 'India': USA
If you change testString to "India" and run the program, the output will be:
Input matches 'India'.
6. Attempt any TWO of the following : 12
a) Write a program to print the sum, difference and product of two complex numbers by
creating a class named “Complex” with separate methods for each operation whose real
and imaginary parts are entered by user.
Ans.
import java.util.Scanner;
// Perform operations
Complex sum = complex1.add(complex2);
Complex difference = complex1.subtract(complex2);
Complex product = complex1.multiply(complex2);
// Display results
System.out.println("Sum: " + sum);
System.out.println("Difference: " + difference);
System.out.println("Product: " + product);
scanner.close();
}
}
2. Runtime Errors
Runtime errors are exceptions that occur during the execution of the program. These errors
indicate that the application has encountered a condition that it cannot handle, leading to a crash
or unintended behavior.
Example:
public class MemoryErrorExample {
public static void main(String[] args) {
try {
int[] arr = new int[Integer.MAX_VALUE]; // Attempting to allocate huge array
} catch (OutOfMemoryError e) {
System.out.println("Caught OutOfMemoryError: " + e);
}
}
}
Threads are a fundamental part of concurrent programming. Each thread has a priority that helps
the thread scheduler determine the order in which threads should be executed. Java provides
methods in the Thread class to set and get the priority of a thread. Here’s a detailed explanation
of these methods:
Thread Priority in Java
Java threads have priorities that range from 1 (minimum priority) to 10 (maximum priority). The
default priority for a thread is 5. The priority of a thread can influence the order in which threads
are scheduled for execution, but it does not guarantee execution order.
Methods to Set and Get Thread Priority
1. setPriority(int newPriority)
a. Description: This method is used to set the priority of the thread. The priority
must be between Thread.MIN_PRIORITY (1) and Thread.MAX_PRIORITY (10).
b. Syntax:
public final void setPriority(int newPriority) throws IllegalArgumentException
2.getPriority()
Description: This method returns the priority of the thread.
Syntax:
public final int getPriority()
Example:
public class ThreadPriorityExample {
public static void main(String[] args) {
Thread thread1 = new Thread(() -> {
System.out.println("Thread 1 is running.");
});
// Setting priorities
thread1.setPriority(Thread.MAX_PRIORITY); // Setting maximum priority
thread2.setPriority(Thread.MIN_PRIORITY); // Setting minimum priority
// Starting threads
thread1.start();
thread2.start();
}
}