0% found this document useful (0 votes)
22 views15 pages

CSW2 Assignment5 Soln

The document contains solutions for a Java assignment focused on strings, I/O operations, and file management. It includes multiple Java programs demonstrating string manipulation, immutability, comparisons, and text editing functionalities using StringBuffer and StringBuilder. Each program is accompanied by sample outputs and explanations of the operations performed.

Uploaded by

humanoperator8
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)
22 views15 pages

CSW2 Assignment5 Soln

The document contains solutions for a Java assignment focused on strings, I/O operations, and file management. It includes multiple Java programs demonstrating string manipulation, immutability, comparisons, and text editing functionalities using StringBuffer and StringBuilder. Each program is accompanied by sample outputs and explanations of the operations performed.

Uploaded by

humanoperator8
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/ 15

CSW2 ASSIGNMENT 5

(CHAPTER 16 – STRINGS, I/O OPERATIONS AND FILE MANAGEMENT)


SOLUTIONS
--------------------------------------------------------------------------------

STRINGS
1. Write a Java program that illustrates the difference between using string literals and
the new keyword for creating String objects. Your program should demonstrate the
memory usage implications and how string comparison behaves differently in each case.

package strings;
public class Q1 {
public static void main(String[] args) {
String str1 = "Hello";
String str2 = "Hello";
String str3 = new String("Hello");
String str4 = new String("Hello");
System.out.println("Using == to compare:");
System.out.println("str1 == str2: " + (str1 == str2));
System.out.println("str1 == str3: " + (str1 == str3));
System.out.println("str3 == str4: " + (str3 == str4));
System.out.println("\nUsing .equals() to compare:");
System.out.println("str1.equals(str2): " + str1.equals(str2));
System.out.println("str1.equals(str3): " + str1.equals(str3));
System.out.println("str3.equals(str4): " + str3.equals(str4));
}
}

OUTPUT:

Using == to compare:
str1 == str2: true
str1 == str3: false
str3 == str4: false

Using .equals() to compare:


str1.equals(str2): true
str1.equals(str3): true
str3.equals(str4): true

CSW - 2 | 4ᵗʰ SEMESTER • ITER Prepared by MAJI, A.


2. Write a Java program that demonstrates the immutability of the String class and how
it implements the CharSequence interface. Your program should illustrate the behaviours
that highlight String immutability and its usage as a CharSequence.

package strings;
public class Q2 {
public static void main(String[] args) {
String originalStr = "Hello, World!";
System.out.println("Original String: " + originalStr);
String modifiedStr = originalStr.replace("World", "Java");
System.out.println("Modified String: " + modifiedStr);
System.out.println("\nImmutability Demonstration:");
System.out.println("Original String: " + originalStr);
System.out.println("Modified String: " + modifiedStr);
CharSequence charSeq = originalStr;
System.out.println("\nUsing String as CharSequence:");
System.out.println("Length of CharSequence: " + charSeq.length());
System.out.println("Char at index 7: " + charSeq.charAt(7));
System.out.println("Subsequence (0 to 4): " + charSeq.subSequence(0,
5));
}
}

OUTPUT:

Original String: Hello, World!


Modified String: Hello, Java!

Immutability Demonstration:
Original String: Hello, World!
Modified String: Hello, Java!

Using String as CharSequence:


Length of CharSequence: 13
Char at index 7: W
Subsequence (0 to 4): Hello

CSW - 2 | 4ᵗʰ SEMESTER • ITER Prepared by MAJI, A.


3. Write a Java program that uses StringBuffer to construct a simple text editor which
can perform the following operations:
a. Append a given string to the existing text.
b. Insert a given string at a specified index within the existing text.
c. Delete a portion of text between two specified indices.
d. Reverse the entire text.
e. Replace a portion of the text between two specified indices with a given string.
Your program should display a menu with options to perform each of the above operations.
After each operation, print the current state of the text. Also, display the current capacity
and length of the StringBuffer after each operation to showcase its dynamic nature.

package strings;
import java.util.Scanner;
public class Q3 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
StringBuffer textBuffer = new StringBuffer();
while (true) {
System.out.println("\n--- Simple Text Editor ---");
System.out.println("Current Text: \"" + textBuffer + "\"");
System.out.println("Length: " + textBuffer.length() + ", Capacity: "
+ textBuffer.capacity());
System.out.println("Choose an operation:");
System.out.println("1. Append a string");
System.out.println("2. Insert a string at an index");
System.out.println("3. Delete text between indices");
System.out.println("4. Reverse the text");
System.out.println("5. Replace text between indices");
System.out.println("6. Exit");
System.out.print("Enter your choice: ");
int choice = sc.nextInt();
sc.nextLine();
switch (choice) {
case 1:
System.out.print("Enter the string to append: ");
String appText = sc.nextLine();
textBuffer.append(appText);
break;
case 2:
System.out.print("Enter the string to insert: ");
String insText = sc.nextLine();
System.out.print("Enter the index where you want to insert:
");
int n = sc.nextInt();
sc.nextLine();
try {
textBuffer.insert(n, insText);
} catch (StringIndexOutOfBoundsException e) {
System.out.println("Error: Invalid index.");
}
break;
case 3:
System.out.print("Enter the start index for deletion: ");
int s = sc.nextInt();
System.out.print("Enter the end index for deletion: ");
int e = sc.nextInt();
sc.nextLine();
try {
textBuffer.delete(s, e);
} catch (StringIndexOutOfBoundsException err) {
System.out.println("Error: Invalid indices.");

CSW - 2 | 4ᵗʰ SEMESTER • ITER Prepared by MAJI, A.


}
break;
case 4:
textBuffer.reverse();
break;
case 5:
System.out.print("Enter the start index for replacement: ");
int start = sc.nextInt();
System.out.print("Enter the end index for replacement: ");
int end = sc.nextInt();
sc.nextLine();
System.out.print("Enter the replacement string: ");
String repText = sc.nextLine();
try {
textBuffer.replace(start, end, repText);
} catch (StringIndexOutOfBoundsException err) {
System.out.println("Error: Invalid indices.");
}
break;
case 6:
sc.close();
return;
default:
System.out.println("Invalid choice! Please try again.");
break;
}
}
}
}

OUTPUT:

--- Simple Text Editor ---


Current Text: ""
Length: 0, Capacity: 16
Choose an operation:
1. Append a string
2. Insert a string at an index
3. Delete text between indices
4. Reverse the text
5. Replace text between indices
6. Exit
Enter your choice: 1
Enter the string to append: Hello World

--- Simple Text Editor ---


Current Text: "Hello World"
Length: 11, Capacity: 16
Choose an operation:
1. Append a string
2. Insert a string at an index
3. Delete text between indices
4. Reverse the text
5. Replace text between indices
6. Exit
Enter your choice: 6

CSW - 2 | 4ᵗʰ SEMESTER • ITER Prepared by MAJI, A.


4. Create a Java program that uses StringBuilder to perform a series of text manipulations
on a user-provided string. The program should allow users to:
a. Add a substring at a specified position.
b. Remove a range of characters from the string.
c. Modify a character at a specified index.
d. Concatenate another string at the end.
e. Display the current string after each operation.
The program should repeatedly prompt the user to choose an operation until they decide
to exit. After each operation, it should display the modified string, demonstrating the
mutable nature of StringBuilder.

package strings;
import java.util.Scanner;
public class Q4 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the initial string: ");
StringBuilder stringBuilder = new StringBuilder(sc.nextLine());
while (true) {
System.out.println("\n--- Text Manipulation Menu ---");
System.out.println("Current Text: \"" + stringBuilder + "\"");
System.out.println("Choose an operation:");
System.out.println("1. Add a substring at a specified position");
System.out.println("2. Remove a range of characters");
System.out.println("3. Modify a character at a specified index");
System.out.println("4. Concatenate another string at the end");
System.out.println("5. Display the current string");
System.out.println("6. Exit");
System.out.print("Enter your choice: ");
int choice = sc.nextInt();
sc.nextLine();
switch (choice) {
case 1:
System.out.print("Enter the substring to add: ");
String substring = sc.nextLine();
System.out.print("Enter the position to add the substring:
");
int pos = sc.nextInt();
sc.nextLine();
try {
stringBuilder.insert(pos, substring);
} catch (StringIndexOutOfBoundsException err) {
System.out.println("Error: Invalid position.");
}
break;
case 2:
System.out.print("Enter the start index for removal: ");
int s = sc.nextInt();
System.out.print("Enter the end index for removal: ");
int e = sc.nextInt();
sc.nextLine();
try {
stringBuilder.delete(s, e);
} catch (StringIndexOutOfBoundsException err) {
System.out.println("Error: Invalid indices.");
}
break;
case 3:
System.out.print("Enter the index of the character to
modify: ");
int charIndex = sc.nextInt();

CSW - 2 | 4ᵗʰ SEMESTER • ITER Prepared by MAJI, A.


sc.nextLine();
System.out.print("Enter the new character: ");
char newChar = sc.nextLine().charAt(0);
try {
stringBuilder.setCharAt(charIndex, newChar);
} catch (StringIndexOutOfBoundsException err) {
System.out.println("Error: Invalid index.");
}
break;
case 4:
System.out.print("Enter the string to concatenate: ");
String concatStr = sc.nextLine();
stringBuilder.append(concatStr);
break;
case 5:
System.out.println("Current String: \"" + stringBuilder +
"\"");
break;
case 6:
sc.close();
return;
default:
System.out.println("Invalid choice! Please try again.");
break;
}
}
}
}

OUTPUT:

Enter the initial string: Hello

--- Text Manipulation Menu ---


Current Text: "Hello"
Choose an operation:
1. Add a substring at a specified position
2. Remove a range of characters
3. Modify a character at a specified index
4. Concatenate another string at the end
5. Display the current string
6. Exit
Enter your choice: 1
Enter the substring to add: World
Enter the position to add the substring: 5

--- Text Manipulation Menu ---


Current Text: "Hello World"
Choose an operation:
1. Add a substring at a specified position
2. Remove a range of characters
3. Modify a character at a specified index
4. Concatenate another string at the end
5. Display the current string
6. Exit
Enter your choice: 6

CSW - 2 | 4ᵗʰ SEMESTER • ITER Prepared by MAJI, A.


5. Case Conversion and Comparison: Prompt the user to input two strings. Convert both
strings to lowercase and uppercase. Compare the converted strings to check case-
insensitive equality. Display the converted strings and the result of the comparison.

package strings;
import java.util.Scanner;
public class Q5 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the first string: ");
String str1 = sc.nextLine();
System.out.print("Enter the second string: ");
String str2 = sc.nextLine();
String str1Lower = str1.toLowerCase();
String str2Lower = str2.toLowerCase();
String str1Upper = str1.toUpperCase();
String str2Upper = str2.toUpperCase();
boolean areEqual = str1Lower.equals(str2Lower);
System.out.println("\nConverted Strings:");
System.out.println("First String -> Lowercase: " + str1Lower + " |
Uppercase: " + str1Upper);
System.out.println("Second String -> Lowercase: " + str2Lower + " |
Uppercase: " + str2Upper);
System.out.println("\nCase-insensitive comparison result: " + (areEqual
? "Equal" : "Not Equal"));
sc.close();
}
}

OUTPUT:

Enter the first string: AninDYa


Enter the second string: aNiNDya

Converted Strings:
First String -> Lowercase: anindya | Uppercase: ANINDYA
Second String -> Lowercase: anindya | Uppercase: ANINDYA

Case-insensitive comparison result: Equal

CSW - 2 | 4ᵗʰ SEMESTER • ITER Prepared by MAJI, A.


6. Character Array and Search: Ask for a string from the user. Convert the string to a
character array. Prompt the user to enter a character to search in the string. Find the first
and last occurrences of the character. Display the character array and the positions found
(if any).

package strings;
import java.util.Scanner;
public class Q6 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string: ");
String inputString = sc.nextLine();
char[] charArray = inputString.toCharArray();
System.out.print("Character Array: ");
for (char c : charArray) {
System.out.print(c + " ");
}
System.out.println();
System.out.print("Enter a character to search: ");
char searchChar = sc.next().charAt(0);
int firstOccur = -1;
int lastOccur = -1;
for (int i = 0; i < charArray.length; i++) {
if (charArray[i] == searchChar) {
if (firstOccur == -1) {
firstOccur = i;
}
lastOccur = i;
}
}
System.out.println("\nResults:");
if (firstOccur == -1) {
System.out.println("Character '" + searchChar + "' not found in the
string.");
} else {
System.out.println("First occurrence of '" + searchChar + "': Index
" + firstOccur);
System.out.println("Last occurrence of '" + searchChar + "': Index "
+ lastOccur);
}
sc.close();
}
}

OUTPUT:

Enter a string: Hello


Character Array: H e l l o
Enter a character to search: l

Results:
First occurrence of 'l': Index 2
Last occurrence of 'l': Index 3

CSW - 2 | 4ᵗʰ SEMESTER • ITER Prepared by MAJI, A.


7. Word Replacement in Sentences: Request a sentence and two words from the user: one
to search for and one to replace it with. Find the first occurrence of the search word in the
sentence. Replace the word using substring operations and concatenation. Display the
original and the modified sentences.

package strings;
import java.util.Scanner;
public class Q7 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a sentence:");
String originalStr = sc.nextLine();
System.out.println("Enter the word you want to search for:");
String searchStr = sc.nextLine();
System.out.println("Enter the word you want to replace with:");
String replaceStr = sc.nextLine();
int index = originalStr.indexOf(searchStr);
if (index != -1) {
String modifiedString = originalStr.substring(0, index) + replaceStr
+ originalStr.substring(index + searchStr.length());
System.out.println("Original Sentence: " + originalStr);
System.out.println("Modified Sentence: " + modifiedString);
} else {
System.out.println("The word '" + searchStr + "' was not found in
the sentence.");
}
sc.close();
}
}

OUTPUT:

Enter a sentence:
Hello World
Enter the word you want to search for:
World
Enter the word you want to replace with:
Java
Original Sentence: Hello World
Modified Sentence: Hello Java

CSW - 2 | 4ᵗʰ SEMESTER • ITER Prepared by MAJI, A.


8. Interactive String Explorer: Prompt the user for a string. Display a menu with options
to perform various operations: convert to lowercase/uppercase, search for a
character/index, or concatenate with another string. Based on user selection, perform the
appropriate string operation and show the result.

package strings;
import java.util.Scanner;
public class Q8 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string:");
String str1 = sc.nextLine();
while (true) {
System.out.println("\n--- String Operations Menu ---");
System.out.println("1. Convert to Lowercase");
System.out.println("2. Convert to Uppercase");
System.out.println("3. Search for a Character");
System.out.println("4. Search for an Index");
System.out.println("5. Concatenate with Another String");
System.out.println("6. Exit");
System.out.print("Please choose an option (1-6): ");
int choice = sc.nextInt();
sc.nextLine();
switch (choice) {
case 1:
System.out.println("Lowercase: " + str1.toLowerCase());
break;
case 2:
System.out.println("Uppercase: " + str1.toUpperCase());
break;
case 3:
System.out.print("Enter the character to search for: ");
char charToSearch = sc.nextLine().charAt(0);
int charIndex = str1.indexOf(charToSearch);
if (charIndex != -1) {
System.out.println("Character '" + charToSearch + "'
found at index: " + charIndex);
} else {
System.out.println("Character '" + charToSearch + "' not
found.");
}
break;
case 4:
System.out.print("Enter the index to get the character: ");
int index = sc.nextInt();
if (index >= 0 && index < str1.length()) {
System.out.println("Character at index " + index + " is:
" + str1.charAt(index));
} else {
System.out.println("Invalid index.");
}
break;
case 5:
System.out.print("Enter the string to concatenate: ");
String str2 = sc.nextLine();
String concatStr = str1 + str2;
System.out.println("Concatenated String: " + concatStr);
break;
case 6:
sc.close();
return;
default:

CSW - 2 | 4ᵗʰ SEMESTER • ITER Prepared by MAJI, A.


System.out.println("Invalid choice. Please select a valid
option (1-6).");
}
}
}
}

OUTPUT:

Enter a string:
Hello

--- String Operations Menu ---


1. Convert to Lowercase
2. Convert to Uppercase
3. Search for a Character
4. Search for an Index
5. Concatenate with Another String
6. Exit
Please choose an option (1-6): 2
Uppercase: HELLO

--- String Operations Menu ---


1. Convert to Lowercase
2. Convert to Uppercase
3. Search for a Character
4. Search for an Index
5. Concatenate with Another String
6. Exit
Please choose an option (1-6): 6

CSW - 2 | 4ᵗʰ SEMESTER • ITER Prepared by MAJI, A.


I/O OPERATIONS AND FILE MANAGEMENT
9. Create and Write to a File: Write a Java program that prompts the user for a diary entry,
then creates a file named "diary.txt" and writes the current date followed by the user's
entry into this file. Ensure the program checks if the file already exists and informs the
user, to avoid overwriting any previous content.

package filemanagement;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
public class Q9 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String fileName = "diary.txt";
File diaryFile = new File(fileName);
if (diaryFile.exists()) {
System.out.println("The diary file already exists.");
return;
}
try (BufferedWriter writer = new BufferedWriter(new
FileWriter(diaryFile))) {
System.out.print("Please enter your diary entry: ");
String entry = sc.nextLine();
String currentDate = new SimpleDateFormat("yyyy-MM-dd
HH:mm:ss").format(new Date());
writer.write("Date: " + currentDate);
writer.newLine();
writer.write("Entry: " + entry);
writer.newLine();
System.out.println("Your diary entry has been saved to " +
fileName);
} catch (IOException e) {
System.out.println("An error occurred while writing to the file.");
e.printStackTrace();
}
}
}

OUTPUT:

The diary file already exists.

CSW - 2 | 4ᵗʰ SEMESTER • ITER Prepared by MAJI, A.


10. Read from a File: Write a Java application that opens the "diary.txt" file created in the
previous question and displays its content on the console. The program should handle
cases where the file does not exist by displaying an appropriate error message.

package filemanagement;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class Q10 {
public static void main(String[] args) {
String fileName = "diary.txt";
File diaryFile = new File(fileName);
if (!diaryFile.exists()) {
System.out.println("The diary file does not exist. Please create a
diary entry first.");
return;
}
try (BufferedReader reader = new BufferedReader(new
FileReader(diaryFile))) {
String line;
System.out.println("Your Diary Entries:");
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("An error occurred while reading the diary
file.");
e.printStackTrace();
}
}
}

OUTPUT:

Your Diary Entries:


Date: 2025-04-03 15:18:40
Entry: Had a Great Day!

CSW - 2 | 4ᵗʰ SEMESTER • ITER Prepared by MAJI, A.


11. Append Content to an Existing File: Write a Java program that adds a new diary entry
to the "diary.txt" file without overwriting its existing content. The program should ask the
user for the new entry and append it to the file along with a timestamp.

package filemanagement;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
public class Q11 {
public static void main(String[] args) {
String fileName = "diary.txt";
File diaryFile = new File(fileName);
try (Scanner scanner = new Scanner(System.in);
BufferedWriter writer = new BufferedWriter(new
FileWriter(diaryFile, true))) {
System.out.print("Please enter your new diary entry: ");
String entry = scanner.nextLine();
String currentDate = new SimpleDateFormat("yyyy-MM-dd
HH:mm:ss").format(new Date());
writer.write("Date: " + currentDate);
writer.newLine();
writer.write("Entry: " + entry);
writer.newLine();
System.out.println("Your new diary entry has been added to " +
fileName);
} catch (IOException e) {
System.out.println("An error occurred while appending to the diary
file.");
e.printStackTrace();
}
}
}

OUTPUT:

Please enter your new diary entry: Need to complete the tasks.
Your new diary entry has been added to diary.txt

CSW - 2 | 4ᵗʰ SEMESTER • ITER Prepared by MAJI, A.


12. List Files and Directories: Write a program in Java that asks the user for a directory
path and then lists all files and subdirectories in that directory. If the directory does not
exist, the program should inform the user.

package filemanagement;
import java.io.File;
import java.util.Scanner;
public class Q12 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Please enter a directory path: ");
String directoryPath = scanner.nextLine();
File directory = new File(directoryPath);
if (directory.exists() && directory.isDirectory()) {
System.out.println("Listing files and subdirectories in: " +
directoryPath);
String[] filesAndDirs = directory.list();
if (filesAndDirs != null) {
for (String name : filesAndDirs) {
System.out.println(name);
}
} else {
System.out.println("The directory is empty.");
}
} else {
System.out.println("The specified directory does not exist. Please
check the path and try again.");
}
scanner.close();
}
}

OUTPUT:

Please enter a directory path: E:\CSW SOLUTION CODE FILE


The specified directory does not exist. Please check the path and try again.

CSW - 2 | 4ᵗʰ SEMESTER • ITER Prepared by MAJI, A.

You might also like