Java String Programming Assignment
Student Name: [Your Name]
Course: Computer Science - Java Programming
Date: August 18, 2025
Assignment: String Manipulation and Processing
Problem 1: String Creation and Manipulation
public class StringManipulation {
public static void main(String[] args) {
// Creating the same string "Java Programming" using 3 different methods
// 1. String literal
String str1 = "Java Programming";
// 2. new String() constructor
String str2 = new String("Java Programming");
// 3. Character array
char[] charArray = {'J','a','v','a',' ','P','r','o','g','r','a','m','m','i','n','g'};
String str3 = new String(charArray);
// Comparing strings using == and .equals()
[Link]("=== String Comparison Results ===");
[Link]("str1 == str2: " + (str1 == str2));
[Link]("[Link](str2): " + [Link](str2));
[Link]("str1 == str3: " + (str1 == str3));
[Link]("[Link](str3): " + [Link](str3));
[Link]("\nExplanation:");
[Link]("== compares memory references, while .equals() compares content");
[Link]("String literals share the same memory location in string pool");
// String with escape sequences
String quote = "Programming Quote:\n\t\"Code is poetry\" - Unknown\nPath: C:\\Java\\Projects";
[Link]("\n" + quote);
}
}
Problem 2: String Input and Processing
import [Link];
public class StringMethods {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
// Getting user input
[Link]("Enter your full name (First Last): ");
String fullName = [Link]();
[Link]("Enter your favorite programming language: ");
String programmingLanguage = [Link]();
[Link]("Enter a sentence about your programming experience: ");
String sentence = [Link]();
// Processing the input
// 1. Extract first and last name separately
String[] nameParts = [Link](" ", 2);
String firstName = [Link] > 0 ? nameParts[^1_0] : "";
String lastName = [Link] > 1 ? nameParts[^1_1] : "";
// 2. Count total characters in sentence (excluding spaces)
String sentenceNoSpaces = [Link](" ", "");
int charCount = [Link]();
// 3. Convert programming language to uppercase
String langUpperCase = [Link]();
// 4. Display formatted summary
[Link]("\n=== SUMMARY ===");
[Link]("First Name: " + firstName);
[Link]("Last Name: " + lastName);
[Link]("Favorite Language: " + langUpperCase);
[Link]("Experience: " + sentence);
[Link]("Characters in experience (no spaces): " + charCount);
[Link]();
}
}
Problem 3: String Arrays and Methods
public class StringArrays {
// Method to find the longest name
public static String findLongestName(String[] names) {
if ([Link] == 0) return "";
String longest = names[^1_0];
for (String name : names) {
if ([Link]() > [Link]()) {
longest = name;
}
}
return longest;
}
// Method to count names starting with given letter (case-insensitive)
public static int countNamesStartingWith(String[] names, char letter) {
int count = 0;
char lowerLetter = [Link](letter);
for (String name : names) {
if ([Link]() > 0 && [Link]([Link](0)) == lowerLetter) {
count++;
}
}
return count;
}
// Method to format names to "Last, First" format
public static String[] formatNames(String[] names) {
String[] formattedNames = new String[[Link]];
for (int i = 0; i < [Link]; i++) {
String[] parts = names[i].split(" ", 2);
if ([Link] == 2) {
formattedNames[i] = parts[^1_1] + ", " + parts;
} else {
formattedNames[i] = names[i]; // Keep original if no space found
}
}
return formattedNames;
}
public static void main(String[] args) {
String[] students = {"John Smith", "Alice Johnson", "Bob Brown",
"Carol Davis", "David Wilson"};
// Testing all methods
[Link]("=== STRING ARRAY METHODS TEST ===");
[Link]("Original names:");
for (String student : students) {
[Link]("- " + student);
}
[Link]("\nLongest name: " + findLongestName(students));
[Link]("Names starting with 'D': " + countNamesStartingWith(students, 'D'));
[Link]("Names starting with 'B': " + countNamesStartingWith(students, 'B'));
[Link]("\nFormatted names (Last, First):");
String[] formatted = formatNames(students);
for (String name : formatted) {
[Link]("- " + name);
}
}
}
Problem 4: Complete String Application
import [Link];
import [Link];
public class TextProcessor {
// Method to clean and validate input
public static String cleanInput(String input) {
if (input == null) return "";
// Remove extra spaces and trim
String cleaned = [Link]().replaceAll("\\s+", " ");
// Convert to proper case (first letter of each sentence capitalized)
StringBuilder result = new StringBuilder();
boolean capitalizeNext = true;
for (char c : [Link]()) {
if (capitalizeNext && [Link](c)) {
[Link]([Link](c));
capitalizeNext = false;
} else {
[Link]([Link](c));
if (c == '.' || c == '!' || c == '?') {
capitalizeNext = true;
}
}
}
return [Link]();
}
// Method to analyze text
public static void analyzeText(String text) {
[Link]("\n=== TEXT ANALYSIS ===");
// Count words
String[] words = [Link]("\\s+");
[Link]("Word count: " + [Link]);
// Count sentences (approximate)
int sentences = [Link]("[.!?]+").length;
[Link]("Sentence count: " + sentences);
// Count characters (including spaces)
[Link]("Total characters: " + [Link]());
// Find longest word
String longestWord = "";
for (String word : words) {
String cleanWord = [Link]("[^a-zA-Z]", "");
if ([Link]() > [Link]()) {
longestWord = cleanWord;
}
}
[Link]("Longest word: " + longestWord);
// Find most common character (excluding spaces)
int[] charCount = new int[^1_256];
char mostCommon = ' ';
int maxCount = 0;
for (char c : [Link]()) {
if (c != ' ') {
charCount[c]++;
if (charCount[c] > maxCount) {
maxCount = charCount[c];
mostCommon = c;
}
}
}
[Link]("Most common character: '" + mostCommon + "' (appears " + maxCount + "
times)");
}
// Method to create sorted word array
public static String[] getWordsSorted(String text) {
String[] words = [Link]("\\s+");
// Remove punctuation and convert to lowercase
for (int i = 0; i < [Link]; i++) {
words[i] = words[i].replaceAll("[^a-zA-Z]", "").toLowerCase();
}
// Sort alphabetically
[Link](words);
return words;
}
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("=== TEXT PROCESSOR ===");
[Link]("Enter a paragraph of text to process:");
String inputText = [Link]();
// Clean and validate input
String cleanedText = cleanInput(inputText);
[Link]("\nCleaned text: " + cleanedText);
// Analyze the text
analyzeText(cleanedText);
// Show words in alphabetical order
[Link]("\n=== WORDS IN ALPHABETICAL ORDER ===");
String[] sortedWords = getWordsSorted(cleanedText);
for (String word : sortedWords) {
if (![Link]()) {
[Link]("- " + word);
}
}
// Word search functionality
[Link]("\n=== WORD SEARCH ===");
[Link]("Enter a word to search for: ");
String searchWord = [Link]().toLowerCase();
boolean found = false;
for (String word : sortedWords) {
if ([Link](searchWord)) {
found = true;
break;
}
}
if (found) {
[Link]("✓ Word '" + searchWord + "' found in the text!");
} else {
[Link]("✗ Word '" + searchWord + "' not found in the text.");
}
[Link]();
[Link]("\nThank you for using Text Processor!");
}
}
Assignment Reflection
This assignment helped me understand various aspects of Java String manipulation:
1. String Creation Methods: I learned the difference between string literals (stored
in string pool), constructor method, and character array conversion.
2. String Comparison: The distinction between == (reference comparison) and
.equals() (content comparison) is crucial for proper string handling.
3. String Methods: Practiced using essential methods like split(), replace(),
toUpperCase(), trim(), and charAt().
4. Array Processing: Implemented methods to process string arrays effectively,
including sorting and filtering operations.
5. Real-world Application: The text processor demonstrates practical use of string
manipulation in building useful applications.
Challenges faced:
Handling edge cases in string splitting and formatting
Implementing proper text cleaning with regex patterns
Managing memory efficiency in string operations
Key Learnings:
Strings are immutable in Java
StringBuilder is more efficient for multiple string modifications
Regular expressions are powerful for text processing
Input validation is essential for robust applications
Total Time Spent: 3 hours
Compilation Status: All programs compiled and tested successfully