23CST304 Set-B
23CST304 Set-B
23CST304 Set-B
INTERNAL TEST- II
ANSWER KEY
SET- B
Part - A
1. Why suspended() and resume() methods are deprecated?
The suspend() and resume() methods in Java were deprecated because they could lead to serious issues like
deadlocks and inconsistent states. Here's why:
1. Deadlock Risk:
o When a thread is suspended using suspend(), it stops wherever it is, even if it holds a lock. This
can cause other threads waiting for that lock to block indefinitely, leading to a deadlock.
2. Inconsistent State:
o If a thread is suspended in the middle of updating a shared resource, it may leave the resource in
an inconsistent or incomplete state. Since suspend() doesn't release locks or clean up, the
resource could remain corrupted until the thread is resumed.
1. Type Parameters: Generics use type parameters, typically represented by letters like E (Element), T
(Type), K (Key), V (Value), etc. These parameters allow you to define a class or method that can
operate on objects of various types.
2. Compile-Time Type Checking: Generics enable compile-time type checking, which helps to catch
type-related errors early in the development process, reducing the risk of ClassCastException at
runtime.
3. Code Reusability: Generics allow the creation of a single class, method, or interface that can work with
different types, promoting code reusability and reducing redundancy.
PART-B
6 (a) List and explain data types and corresponding wrapper class.
Here’s a list of primitive data types in Java along with their corresponding wrapper classes:
byte
Wrapper Class: Byte
Description: Stores an 8-bit signed integer, useful for saving memory in large arrays.
Size: 1 byte
Range: -128 to 127
short
Wrapper Class: Short
Description: Stores a 16-bit signed integer, used when memory savings are important.
Size: 2 bytes
Range: -32,768 to 32,767
int
Wrapper Class: Integer
Description: Stores a 32-bit signed integer, the default choice for integer values.
Size: 4 bytes
Range: -2^31 to 2^31 - 1
long
Wrapper Class: Long
Description: Stores a 64-bit signed integer, used when larger values than int are needed.
Size: 8 bytes
Range: -2^63 to 2^63 - 1
float
Wrapper Class: Float
Description: Stores a single-precision 32-bit floating-point number, used for saving memory in large
arrays of floating-point numbers.
Size: 4 bytes
Range: Approximately ±3.40282347E+38F (6-7 significant decimal digits)
double
Wrapper Class: Double
Description: Stores a double-precision 64-bit floating-point number, used as the default type for
decimal values.
Size: 8 bytes
Range: Approximately ±1.79769313486231570E+308 (15 significant decimal digits)
char
Wrapper Class: Character
Description: Stores a single 16-bit Unicode character.
Size: 2 bytes
Range: 0 to 65,535 (Unsigned)
boolean
Wrapper Class: Boolean
Description: Stores a value of true or false.
Size: Not precisely defined; depends on the JVM implementation.
Wrapper Classes Explanation:
Purpose: Java's wrapper classes provide a way to use primitive data types as objects. These wrapper
classes offer utility methods and the ability to include primitives in collections like ArrayList, HashMap,
etc., which require objects, not primitives.
Autoboxing/Unboxing: Java automatically converts between primitive types and their corresponding
wrapper classes when necessary (called autoboxing and unboxing). For example:
Integer intObject = 10; // Autoboxing
int primitiveInt = intObject; // Unboxing
OR
6 (b) Explain the Reader and Writer stream class hierarchy with an example program.
In Java, the Reader and Writer classes are part of the Character Stream hierarchy, designed to handle
reading and writing character data, as opposed to byte streams (InputStream and OutputStream) which deal
with raw binary data.
Hierarchy Overview:
Reader Class (Abstract):
Base class for reading character streams. It provides methods like read(), close(), etc.
Subclasses:
BufferedReader
InputStreamReader
FileReader
CharArrayReader
StringReader
Writer Class (Abstract):
Base class for writing character streams. It provides methods like write(), flush(), and close().
Subclasses:
BufferedWriter
OutputStreamWriter
FileWriter
CharArrayWriter
StringWriter
java.lang.Object
java.io.Reader
BufferedReader
InputStreamReader
FileReader
CharArrayReader
StringReader
Writer Class Hierarchy:
java.lang.Object
java.io.Writer
BufferedWriter
OutputStreamWriter
FileWriter
CharArrayWriter
StringWriter
Explanation of Important Classes:
FileReader / FileWriter:
Used to read/write text files.
Example: Reading from and writing to a text file.
BufferedReader / BufferedWriter:
Provides buffering, improving efficiency when reading or writing larger chunks of data.
InputStreamReader / OutputStreamWriter:
Converts byte streams to character streams and vice versa, often used with network streams.
This example reads from a text file (input.txt) and writes the content to another text file (output.txt) using
BufferedReader and BufferedWriter to handle the character stream efficiently.
import java.io.*;
public class CopyTextFileExample {
public static void main(String[] args) {
// Define the file paths
String inputFilePath = "input.txt";
String outputFilePath = "output.txt";
// Read each line from the input file and write it to the output file
while ((line = reader.readLine()) != null) {
writer.write(line);
writer.newLine(); // Add a new line after each line
}
} catch (IOException e) {
System.out.println("An error occurred: " + e.getMessage());
}
}
}
Explanation:
BufferedReader: This reads character data efficiently from a file. The readLine() method is used to read a
full line at a time.
BufferedWriter: This writes character data efficiently to a file. It provides a newLine() method to insert a
line separator after each line.
PART-C
7 (a) Discuss the Java thread model in detail. Explain the process of creating a thread and managing
Java Thread Model Overview
The Java thread model is designed around the concept of multithreading, which allows multiple threads of
execution to run concurrently within a program. Multithreading enables Java to perform multiple tasks at
the same time, making it useful for applications such as graphical user interfaces (GUIs), server
applications, and parallel processing tasks.
Thread: A thread in Java is a lightweight subprocess, the smallest unit of processing. It runs
independently and shares resources like memory with other threads.
Multithreading: In Java, multithreading allows multiple threads to execute independently within the same
program. These threads share the same memory space and can communicate with each other, but their
execution is asynchronous unless synchronized.
Creating a Thread in Java
There are two primary ways to create a thread in Java:
By extending the Thread class
By implementing the Runnable interface
When you extend the Thread class, you override the run() method that contains the code the thread should
execute.
Example:
class MyThread extends Thread {
public void run() {
System.out.println("Thread is running");
}
}
public class ThreadExample {
public static void main(String[] args) {
MyThread t1 = new MyThread();
t1.start(); // Starts the thread, invokes the run() method in a separate call stack
}
}
2. Implementing the Runnable Interface
The Runnable interface is more commonly used, as it provides more flexibility (Java allows multiple
inheritance through interfaces, so implementing Runnable is preferred if the class already extends another
class).
Example:
class MyRunnable implements Runnable {
public void run() {
System.out.println("Thread is running");
}
}
t1.start();
t2.start();
try {
t1.join(); // Waits for t1 to finish before continuing
t2.join(); // Waits for t2 to finish before continuing
} catch (InterruptedException e) {
System.out.println("Thread interrupted");
}
System.out.println("All threads finished.");
}
}
Thread Priorities
Java threads can have a priority, which determines the order in which threads are scheduled for execution.
Thread priorities are integers ranging from 1 (MIN_PRIORITY) to 10 (MAX_PRIORITY), with 5
(NORM_PRIORITY) as the default.
Threads with higher priorities are generally executed before those with lower priorities.
However, thread priority does not guarantee order of execution, as thread scheduling depends on the
operating system.
Example:
t1.start();
t2.start();
}
}
Thread Synchronization
In multithreaded programs, multiple threads can access shared resources, leading to inconsistent results or
race conditions. Java provides a mechanism called synchronization to control access to shared resources by
allowing only one thread to access the resource at a time.
Synchronized Block/Method: You can synchronize a method or block of code to ensure that only one
thread can execute it at a time.
Locks/Monitors: Every object in Java has an implicit lock (or monitor). When a thread enters a
synchronized method or block, it acquires the lock for that object.
Example: Thread Synchronization
Consider a scenario where multiple threads try to withdraw money from a bank account simultaneously.
Without synchronization, the balance might become inconsistent.
class BankAccount {
private int balance = 1000;
t1.start();
t2.start();
}
}
Explanation:
The withdraw() method is marked as synchronized, which ensures that only one thread can access the
method at a time.
Without synchronization, both threads could potentially withdraw money at the same time, leading to an
incorrect balance.
Concepts of Synchronization:
Synchronized Method: A method marked as synchronized allows only one thread to access it at a time.
Synchronized Block: Synchronizing a specific block of code inside a method rather than the whole
method can offer more fine-grained control.
Deadlock: A situation where two or more threads are blocked forever, waiting for each other to release
resources.
Wait and Notify: Java provides wait(), notify(), and notifyAll() methods to allow threads to communicate
with each other when working with shared resources.
Conclusion
The Java thread model provides powerful capabilities for handling multithreading and concurrency. Using
thread priorities, synchronization, and proper thread management can improve program efficiency and
prevent issues like race conditions. By understanding how to create, manage, and synchronize threads,
developers can write robust multithreaded applications.
OR
(b) Create a software for department store maintain item no item description request quantity, cost price,
calculate selling price exceeds given amount.
Here’s a more comprehensive Java application for a department store that maintains item details such as
item number, description, requested quantity, cost price, and calculates the selling price. This program will
also ensure that the selling price exceeds a given amount set by the user.
Department Store Management System
This application will include the following features:
Add Items: Input item details and calculate selling price.
List Items: Display all items in the store.
Remove Items: Remove items by item number.
Calculate Selling Price: Ensure the selling price exceeds a specified amount.
Java Code Implementation
Below is a complete code implementation of the described functionality.
import java.util.ArrayList;
import java.util.Scanner;
class Item {
private int itemNumber;
private String description;
private int requestQuantity;
private double costPrice;
private double sellingPrice;
// Constructor
public Item(int itemNumber, String description, int requestQuantity, double costPrice) {
this.itemNumber = itemNumber;
this.description = description;
this.requestQuantity = requestQuantity;
this.costPrice = costPrice;
}
// Calculate selling price based on markup percentage
public void calculateSellingPrice(double markupPercentage) {
double calculatedSellingPrice = costPrice + (costPrice * markupPercentage / 100);
this.sellingPrice = calculatedSellingPrice;
}
// Getters
public int getItemNumber() {
return itemNumber;
}
@Override
public String toString() {
return "Item Number: " + itemNumber +
", Description: " + description +
", Request Quantity: " + requestQuantity +
", Cost Price: $" + costPrice +
", Selling Price: $" + sellingPrice;
}
}
public DepartmentStore() {
items = new ArrayList<>();
scanner = new Scanner(System.in);
}
items.add(item);
System.out.println("Item added successfully!\n");
}
if (!found) {
System.out.println("Item not found.");
}
}
do {
System.out.println("\nDepartment Store Menu:");
System.out.println("1. Add Item");
System.out.println("2. List Items");
System.out.println("3. Remove Item");
System.out.println("4. Exit");
System.out.print("Enter your choice: ");
choice = scanner.nextInt();
switch (choice) {
case 1:
addItem();
break;
case 2:
listItems();
break;
case 3:
removeItem();
break;
case 4:
System.out.println("Exiting the program. Thank you!");
break;
default:
System.out.println("Invalid choice! Please try again.");
}
} while (choice != 4);
}
DepartmentStore Class:
Manages a list of items using an ArrayList<Item>.
Contains methods to add, list, and remove items.
Add Item Method:
Prompts the user for item details and calculates the selling price.
Checks if the selling price exceeds a given minimum selling price.
List Items Method:
Displays all items in the store.
Remove Item Method:
Removes an item based on the provided item number.
User Interaction:
The program displays a menu to the user to select actions: add items, list items, remove items, or exit.
Uses a Scanner to take input from the user.
Conclusion
This Java console application provides a basic framework for managing items in a department store. It can
be expanded with additional features like data persistence (storing items in a database or file), enhanced
input validation, or a graphical user interface (GUI) for a better user experience.
8 (a) Write a program to replace all "word1" by "word2" from a file 1, and output is written to file2 file
and display the number of replacements.
Here’s a Java program that reads from one file (file1), replaces all occurrences of "word1" with "word2",
writes the result to another file (file2), and displays the number of replacements made.
Java Program: Word Replacement
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class WordReplacement {
public static void main(String[] args) {
String inputFile = "file1.txt"; // Input file path
String outputFile = "file2.txt"; // Output file path
String wordToReplace = "word1"; // Word to be replaced
String replacementWord = "word2"; // Word to replace with
String line;
while ((line = reader.readLine()) != null) {
// Count occurrences of the word to be replaced
int occurrences = line.length() - line.replace(wordToReplace, "").length();
count += occurrences / wordToReplace.length();
return count;
}
}
Explanation of the Code:
Imports: The program imports the necessary classes for file handling.
Main Method:
Defines the input file (file1.txt), output file (file2.txt), the word to be replaced (word1), and the
replacement word (word2).
Calls the replaceWords method and displays the number of replacements made.
replaceWords Method:
Parameters: Takes the input file name, output file name, the word to replace, and the replacement
word.
Initializes a counter (count) for tracking the number of replacements.
Uses a BufferedReader to read the input file line by line and a BufferedWriter to write to the output
file.
For each line:
Calculates the number of occurrences of the word to be replaced by comparing the length of the line
before and after the replacement.
Replaces all occurrences of the word in the line and writes the modified line to the output file.
Returns the total count of replacements.
Usage Instructions:
Prepare Input File: Create a file named file1.txt in the same directory as the program, and populate it with
some text that contains the word "word1".
Compile and Run: Compile the program using a Java compiler (e.g., javac WordReplacement.java) and
run it (e.g., java WordReplacement).
Check Output: After running, check the output file file2.txt to see the text with "word1" replaced by
"word2". The console will also display the number of replacements made.
OR
(b) Explain in details about String class and String methods with suitable example.
The String class in Java is a fundamental class that represents a sequence of characters. It is widely used for
manipulating text and is part of the java.lang package. Strings are immutable in Java, meaning once a String
object is created, its value cannot be changed. Instead, any modifications to a string result in the creation of
a new string.
Key Features of the String Class
Immutability: Once a string is created, its value cannot be changed. Any operation that seems to modify a
string actually creates a new string.
String Pool: Java optimizes memory usage by storing string literals in a special memory area called the
string pool. If you create a string with the same value, it will reference the same object in memory.
Various Constructors: Strings can be created using different constructors or directly using string literals.
Common String Methods
Here’s a detailed explanation of some commonly used methods of the String class along with examples.
length()
Returns the length of the string.
Example:
java
charAt(int index)
Returns the index of the first or last occurrence of the specified substring.
Example:
toLowerCase() / toUpperCase()
trim()
Removes leading and trailing whitespace from the string.
Example:
String strWithSpaces = " Hello, World! ";
String trimmed = strWithSpaces.trim();
System.out.println("Trimmed: '" + trimmed + "'"); // Output: 'Hello, World!'
Replaces all occurrences of a specified character or substring with a new character or substring.
Example:
split(String regex)
Splits the string into an array based on the specified regular expression.
Example:
String[] words = str.split(", ");
for (String word : words) {
System.out.println("Word: " + word);
}
// Output:
// Word: Hello
// Word: World!
concat(String str)
Here’s a simple program that demonstrates the usage of some String methods:
// 3. Convert to uppercase
System.out.println("Uppercase: " + trimmedStr.toUpperCase()); // Output: HELLO, WORLD! THIS
IS A STRING EXAMPLE.
// 4. Convert to lowercase
System.out.println("Lowercase: " + trimmedStr.toLowerCase()); // Output: hello, world! this is a
string example.
// 5. Replace word
System.out.println("Replaced: " + trimmedStr.replace("World", "Java")); // Output: Hello, Java! This
is a String example.
// 6. Split the string
String[] words = trimmedStr.split(" ");
System.out.println("Words in the string:");
for (String word : words) {
System.out.println(word);
}
// 8. Substring example
System.out.println("Substring (0, 5): " + trimmedStr.substring(0, 5)); // Output: Hello
}
}
vbnet
Original Length: 49
Trimmed String: 'Hello, World! This is a String example.'
Uppercase: HELLO, WORLD! THIS IS A STRING EXAMPLE.
Lowercase: hello, world! this is a string example.
Replaced: Hello, Java! This is a String example.
Words in the string:
Hello,
World!
This
is
a
String
example.
Index of 'W': 7
Substring (0, 5): Hello
Conclusion
The String class is a powerful and versatile tool for working with text in Java. Understanding its methods is
essential for effective string manipulation, and this knowledge can significantly enhance your ability to
process and handle textual data in your Java applications.