0% found this document useful (0 votes)
2 views7 pages

Java String Programming Assignment

The document outlines a Java programming assignment focused on string manipulation and processing, including string creation, comparison, input handling, and text analysis. It consists of multiple problems that demonstrate various string methods and their applications, culminating in a text processor application. The assignment reflection highlights key learnings, challenges faced, and the total time spent on the project.

Uploaded by

sainithinpokala
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views7 pages

Java String Programming Assignment

The document outlines a Java programming assignment focused on string manipulation and processing, including string creation, comparison, input handling, and text analysis. It consists of multiple problems that demonstrate various string methods and their applications, culminating in a text processor application. The assignment reflection highlights key learnings, challenges faced, and the total time spent on the project.

Uploaded by

sainithinpokala
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

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


System.out.println("=== String Comparison Results ===");
System.out.println("str1 == str2: " + (str1 == str2));
System.out.println("str1.equals(str2): " + str1.equals(str2));
System.out.println("str1 == str3: " + (str1 == str3));
System.out.println("str1.equals(str3): " + str1.equals(str3));

System.out.println("\nExplanation:");
System.out.println("== compares memory references, while .equals() compares content");
System.out.println("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";
System.out.println("\n" + quote);
}
}
Problem 2: String Input and Processing

import java.util.Scanner;

public class StringMethods {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Getting user input


System.out.print("Enter your full name (First Last): ");
String fullName = scanner.nextLine();

System.out.print("Enter your favorite programming language: ");


String programmingLanguage = scanner.nextLine();

System.out.print("Enter a sentence about your programming experience: ");


String sentence = scanner.nextLine();

// Processing the input

// 1. Extract first and last name separately


String[] nameParts = fullName.split(" ", 2);
String firstName = nameParts.length > 0 ? nameParts[^1_0] : "";
String lastName = nameParts.length > 1 ? nameParts[^1_1] : "";

// 2. Count total characters in sentence (excluding spaces)


String sentenceNoSpaces = sentence.replace(" ", "");
int charCount = sentenceNoSpaces.length();

// 3. Convert programming language to uppercase


String langUpperCase = programmingLanguage.toUpperCase();

// 4. Display formatted summary


System.out.println("\n=== SUMMARY ===");
System.out.println("First Name: " + firstName);
System.out.println("Last Name: " + lastName);
System.out.println("Favorite Language: " + langUpperCase);
System.out.println("Experience: " + sentence);
System.out.println("Characters in experience (no spaces): " + charCount);

scanner.close();
}
}

Problem 3: String Arrays and Methods

public class StringArrays {

// Method to find the longest name


public static String findLongestName(String[] names) {
if (names.length == 0) return "";

String longest = names[^1_0];


for (String name : names) {
if (name.length() > longest.length()) {
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 = Character.toLowerCase(letter);

for (String name : names) {


if (name.length() > 0 && Character.toLowerCase(name.charAt(0)) == lowerLetter) {
count++;
}
}
return count;
}

// Method to format names to "Last, First" format


public static String[] formatNames(String[] names) {
String[] formattedNames = new String[names.length];

for (int i = 0; i < names.length; i++) {


String[] parts = names[i].split(" ", 2);
if (parts.length == 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


System.out.println("=== STRING ARRAY METHODS TEST ===");
System.out.println("Original names:");
for (String student : students) {
System.out.println("- " + student);
}

System.out.println("\nLongest name: " + findLongestName(students));


System.out.println("Names starting with 'D': " + countNamesStartingWith(students, 'D'));
System.out.println("Names starting with 'B': " + countNamesStartingWith(students, 'B'));
System.out.println("\nFormatted names (Last, First):");
String[] formatted = formatNames(students);
for (String name : formatted) {
System.out.println("- " + name);
}
}
}

Problem 4: Complete String Application

import java.util.Scanner;
import java.util.Arrays;

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 = input.trim().replaceAll("\\s+", " ");

// Convert to proper case (first letter of each sentence capitalized)


StringBuilder result = new StringBuilder();
boolean capitalizeNext = true;

for (char c : cleaned.toCharArray()) {


if (capitalizeNext && Character.isLetter(c)) {
result.append(Character.toUpperCase(c));
capitalizeNext = false;
} else {
result.append(Character.toLowerCase(c));
if (c == '.' || c == '!' || c == '?') {
capitalizeNext = true;
}
}
}

return result.toString();
}

// Method to analyze text


public static void analyzeText(String text) {
System.out.println("\n=== TEXT ANALYSIS ===");

// Count words
String[] words = text.split("\\s+");
System.out.println("Word count: " + words.length);

// Count sentences (approximate)


int sentences = text.split("[.!?]+").length;
System.out.println("Sentence count: " + sentences);

// Count characters (including spaces)


System.out.println("Total characters: " + text.length());

// Find longest word


String longestWord = "";
for (String word : words) {
String cleanWord = word.replaceAll("[^a-zA-Z]", "");
if (cleanWord.length() > longestWord.length()) {
longestWord = cleanWord;
}
}
System.out.println("Longest word: " + longestWord);

// Find most common character (excluding spaces)


int[] charCount = new int[^1_256];
char mostCommon = ' ';
int maxCount = 0;

for (char c : text.toCharArray()) {


if (c != ' ') {
charCount[c]++;
if (charCount[c] > maxCount) {
maxCount = charCount[c];
mostCommon = c;
}
}
}
System.out.println("Most common character: '" + mostCommon + "' (appears " + maxCount + "
times)");
}

// Method to create sorted word array


public static String[] getWordsSorted(String text) {
String[] words = text.split("\\s+");

// Remove punctuation and convert to lowercase


for (int i = 0; i < words.length; i++) {
words[i] = words[i].replaceAll("[^a-zA-Z]", "").toLowerCase();
}

// Sort alphabetically
Arrays.sort(words);

return words;
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.println("=== TEXT PROCESSOR ===");


System.out.println("Enter a paragraph of text to process:");
String inputText = scanner.nextLine();

// Clean and validate input


String cleanedText = cleanInput(inputText);
System.out.println("\nCleaned text: " + cleanedText);

// Analyze the text


analyzeText(cleanedText);

// Show words in alphabetical order


System.out.println("\n=== WORDS IN ALPHABETICAL ORDER ===");
String[] sortedWords = getWordsSorted(cleanedText);
for (String word : sortedWords) {
if (!word.isEmpty()) {
System.out.println("- " + word);
}
}

// Word search functionality


System.out.println("\n=== WORD SEARCH ===");
System.out.print("Enter a word to search for: ");
String searchWord = scanner.nextLine().toLowerCase();

boolean found = false;


for (String word : sortedWords) {
if (word.equals(searchWord)) {
found = true;
break;
}
}

if (found) {
System.out.println("✓ Word '" + searchWord + "' found in the text!");
} else {
System.out.println("✗ Word '" + searchWord + "' not found in the text.");
}

scanner.close();
System.out.println("\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

You might also like