CSW2 Assignment5 Soln
CSW2 Assignment5 Soln
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
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:
Immutability Demonstration:
Original String: Hello, World!
Modified String: Hello, Java!
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.");
OUTPUT:
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();
OUTPUT:
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:
Converted Strings:
First String -> Lowercase: anindya | Uppercase: ANINDYA
Second String -> Lowercase: anindya | Uppercase: ANINDYA
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:
Results:
First occurrence of 'l': Index 2
Last occurrence of 'l': Index 3
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
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:
OUTPUT:
Enter a string:
Hello
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:
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:
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
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: