Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

23CST304 Set-B

Download as pdf or txt
Download as pdf or txt
You are on page 1of 25

23CST304 – OBJECT ORIENTED PROGRAMMING

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.

2. How can you create threads in java?


In Java, you can create threads in two primary ways: by extending the Thread class or by implementing the
Runnable interface. Here’s how each method works:
1. By Extending the Thread Class:
You can create a class that implements the Runnable interface, which requires implementing the run()
method. The Runnable object is passed to a Thread object, which is then started using the start()
method.
class MyRunnable implements Runnable {
public void run() {
System.out.println("Thread is running");
}
}

public class Main {


public static void main(String[] args) {
MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start(); // Starts the thread
}
}
3. Differentiate build in exception and user defined exception.
User-defined exceptions are created by extending the base Exception class or its subclasses. By
creating customized exceptions, you can handle application-specific exceptional conditions that are not
covered by the built-in exceptions. They are handled using keywords like try, catch, finally, throw, and
throws.
4. What are the Restrictions and Limitations to be followed on generics?
Primitive type parameters is not allowed for generic programming. For example: Stack<int> is not
allowed. 3. For the instances of generic class throw and catch instances are not allowed.
5. How Generics works in Java?
Generics in Java is a powerful feature that allows you to define classes, interfaces, and methods with a
placeholder for types, enabling type-safe operations without the need for casting. This helps in writing
flexible and reusable code while maintaining type safety at compile time.

Key Features of Generics:

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

Character Stream Class Hierarchy:


Reader Class Hierarchy:

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.

Example Program: Copying a Text File Using BufferedReader and BufferedWriter

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";

// Try with resources ensures streams are closed automatically


try (
// Create BufferedReader to read from input file
BufferedReader reader = new BufferedReader(new FileReader(inputFilePath));

// Create BufferedWriter to write to output file


BufferedWriter writer = new BufferedWriter(new FileWriter(outputFilePath))
){
String line;

// 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
}

System.out.println("File copied successfully.");

} 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

1. Extending the Thread Class

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");
}
}

public class ThreadExample {


public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread t1 = new Thread(myRunnable);
t1.start(); // Starts the thread, invokes the run() method
}
}
Managing Multiple Threads
Java provides several mechanisms to manage multiple threads:
start(): Starts the thread.
join(): Makes one thread wait for the completion of another thread.
sleep(): Pauses the execution of a thread for a specified time.
yield(): Temporarily pauses the currently executing thread and allows other threads to execute.
interrupt(): Interrupts a thread’s execution, signaling it to stop.
Example of Managing Multiple Threads:

class MyRunnable implements Runnable {


private String name;

public MyRunnable(String name) {


this.name = name;
}

public void run() {


for (int i = 0; i < 5; i++) {
System.out.println(name + " is running - " + i);
try {
Thread.sleep(500); // Sleep for 500ms
} catch (InterruptedException e) {
System.out.println(name + " was interrupted.");
}
}
}
}

public class MultiThreadExample {


public static void main(String[] args) {
Thread t1 = new Thread(new MyRunnable("Thread 1"));
Thread t2 = new Thread(new MyRunnable("Thread 2"));

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:

class MyRunnable implements Runnable {


public void run() {
System.out.println(Thread.currentThread().getName() + " is running");
}
}

public class ThreadPriorityExample {


public static void main(String[] args) {
Thread t1 = new Thread(new MyRunnable(), "Thread 1");
Thread t2 = new Thread(new MyRunnable(), "Thread 2");

t1.setPriority(Thread.MIN_PRIORITY); // Set t1 to minimum priority (1)


t2.setPriority(Thread.MAX_PRIORITY); // Set t2 to maximum priority (10)

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;

// Synchronized method to prevent race conditions


public synchronized void withdraw(int amount) {
if (balance >= amount) {
System.out.println(Thread.currentThread().getName() + " is withdrawing " + amount);
balance -= amount;
System.out.println("Remaining balance: " + balance);
} else {
System.out.println(Thread.currentThread().getName() + " cannot withdraw. Insufficient balance.");
}
}
}
class WithdrawalRunnable implements Runnable {
private BankAccount account;

public WithdrawalRunnable(BankAccount account) {


this.account = account;
}
public void run() {
for (int i = 0; i < 3; i++) {
account.withdraw(300);
}
}
}
public class SyncExample {
public static void main(String[] args) {
BankAccount account = new BankAccount();
Thread t1 = new Thread(new WithdrawalRunnable(account), "Thread 1");
Thread t2 = new Thread(new WithdrawalRunnable(account), "Thread 2");

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;
}

public String getDescription() {


return description;
}

public int getRequestQuantity() {


return requestQuantity;
}

public double getCostPrice() {


return costPrice;
}

public double getSellingPrice() {


return sellingPrice;
}

@Override
public String toString() {
return "Item Number: " + itemNumber +
", Description: " + description +
", Request Quantity: " + requestQuantity +
", Cost Price: $" + costPrice +
", Selling Price: $" + sellingPrice;
}
}

public class DepartmentStore {


private ArrayList<Item> items;
private Scanner scanner;

public DepartmentStore() {
items = new ArrayList<>();
scanner = new Scanner(System.in);
}

public void addItem() {


System.out.print("Enter Item Number: ");
int itemNumber = scanner.nextInt();
scanner.nextLine(); // Consume newline

System.out.print("Enter Item Description: ");


String description = scanner.nextLine();

System.out.print("Enter Request Quantity: ");


int requestQuantity = scanner.nextInt();

System.out.print("Enter Cost Price: ");


double costPrice = scanner.nextDouble();

Item item = new Item(itemNumber, description, requestQuantity, costPrice);

System.out.print("Enter Minimum Selling Price: ");


double minSellingPrice = scanner.nextDouble();

// Calculate selling price based on markup percentage


System.out.print("Enter Markup Percentage: ");
double markupPercentage = scanner.nextDouble();
item.calculateSellingPrice(markupPercentage);

// Check if selling price exceeds minimum selling price


if (item.getSellingPrice() < minSellingPrice) {
System.out.println("Selling price must exceed the minimum selling price of $" + minSellingPrice);
return;
}

items.add(item);
System.out.println("Item added successfully!\n");
}

public void listItems() {


if (items.isEmpty()) {
System.out.println("No items in the store.");
} else {
System.out.println("\nItems in the store:");
for (Item item : items) {
System.out.println(item);
}
}
}

public void removeItem() {


System.out.print("Enter Item Number to remove: ");
int itemNumber = scanner.nextInt();
boolean found = false;

for (Item item : items) {


if (item.getItemNumber() == itemNumber) {
items.remove(item);
found = true;
System.out.println("Item removed successfully!");
break;
}
}

if (!found) {
System.out.println("Item not found.");
}
}

public void run() {


int choice;

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);
}

public static void main(String[] args) {


DepartmentStore store = new DepartmentStore();
store.run();
}
}

How the Code Works:


Item Class:
Represents an item with attributes: itemNumber, description, requestQuantity, costPrice, and
sellingPrice.
The method calculateSellingPrice(double markupPercentage) computes the selling price based on the
cost price and markup percentage.
The toString() method provides a string representation of the item.

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

int replacementCount = replaceWords(inputFile, outputFile, wordToReplace, replacementWord);


System.out.println("Number of replacements: " + replacementCount);
}
public static int replaceWords(String inputFile, String outputFile, String wordToReplace, String
replacementWord) {
int count = 0;

try (BufferedReader reader = new BufferedReader(new FileReader(inputFile));


BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile))) {

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();

// Replace the word and write to the output file


line = line.replace(wordToReplace, replacementWord);
writer.write(line);
writer.newLine();
}
} catch (IOException e) {
e.printStackTrace();
}

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

String str = "Hello, World!";


int length = str.length();
System.out.println("Length: " + length); // Output: Length: 13

charAt(int index)

Returns the character at the specified index.


Example:
char ch = str.charAt(7);
System.out.println("Character at index 7: " + ch); // Output: Character at index 7: W

substring(int beginIndex) / substring(int beginIndex, int endIndex)

Returns a new string that is a substring of this string.


Example:

String sub1 = str.substring(7); // "World!"


String sub2 = str.substring(0, 5); // "Hello"
System.out.println("Substring from index 7: " + sub1); // Output: World!
System.out.println("Substring from index 0 to 5: " + sub2); // Output: Hello

indexOf(String str) / lastIndexOf(String str)

Returns the index of the first or last occurrence of the specified substring.
Example:

int index = str.indexOf("o");


int lastIndex = str.lastIndexOf("o");
System.out.println("First occurrence of 'o': " + index); // Output: 4
System.out.println("Last occurrence of 'o': " + lastIndex); // Output: 8

toLowerCase() / toUpperCase()

Converts the string to lower or upper case.


Example:

String lower = str.toLowerCase(); // "hello, world!"


String upper = str.toUpperCase(); // "HELLO, WORLD!"
System.out.println("Lowercase: " + lower); // Output: hello, world!
System.out.println("Uppercase: " + upper); // Output: HELLO, WORLD!

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!'

replace(char oldChar, char newChar) / replace(CharSequence oldChar, CharSequence newChar)

Replaces all occurrences of a specified character or substring with a new character or substring.
Example:

String replaced = str.replace("World", "Java");


System.out.println("Replaced: " + replaced); // Output: Hello, Java!

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)

Concatenates the specified string to the end of this string.


Example:
String additional = " How are you?";
String concatenated = str.concat(additional);
System.out.println("Concatenated: " + concatenated); // Output: Hello, World! How are you?

equals(Object obj) / equalsIgnoreCase(String anotherString)


Compares the string with another object or string, returning true if they are equal.
Example:
String str1 = "Hello";
String str2 = "hello";
System.out.println("Equals: " + str1.equals(str2)); // Output: false
System.out.println("Equals Ignore Case: " + str1.equalsIgnoreCase(str2)); // Output: true

Example Program Using String Methods

Here’s a simple program that demonstrates the usage of some String methods:

public class StringMethodsExample {


public static void main(String[] args) {
String str = " Hello, World! This is a String example. ";

// 1. Length of the string


System.out.println("Original Length: " + str.length()); // Output: 49

// 2. Trim the string


String trimmedStr = str.trim();
System.out.println("Trimmed String: '" + trimmedStr + "'"); // Output: 'Hello, World! This is a String
example.'

// 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);
}

// 7. Find index of a character


System.out.println("Index of 'W': " + trimmedStr.indexOf('W')); // Output: 7

// 8. Substring example
System.out.println("Substring (0, 5): " + trimmedStr.substring(0, 5)); // Output: Hello
}
}

Output of the Example Program

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.

You might also like