Mastering Strings in Java: A complete Guide to the String Class

Java String Methods Demonstration

Overview

This project contains a collection of Java programs that demonstrate various methods of the String class in Java. Each program focuses on a specific category of string operations, showcasing their usage in practical scenarios. The programs are designed to be educational, with clear comments and structured code to illustrate how to manipulate strings effectively in Java.

The project covers the following categories of String methods:

  1. Creating and Basic Operations

  2. Comparison and Equality

  3. Searching and Indexing

  4. Substrings and Splitting

  5. Case Conversion

  6. Trimming and Cleaning

  7. Replacement and Modification

  8. Concatenation and Joining

  9. Formatting

  10. Conversion and Inspection

  11. Immutability Note

Each program is implemented in a separate Java file, using a unique scenario to ensure variety and practical relevance.

Project Structure

The project includes the following Java files, each corresponding to a specific category of String methods:

Prerequisites

  • Java Development Kit (JDK): Version 8 or higher is required for most programs. Some programs (e.g., FormInputCleaner.java, InvoiceFormatter.java) use features from Java 11+ (strip()) or Java 15+ (formatted()).

  • Java IDE or Compiler: Tools like IntelliJ IDEA, Eclipse, or the command-line javac compiler.

  • Optional: A text editor for viewing this README or modifying the code.

Setup Instructions

  1. Clone or Download: Copy the project files to your local machine.

  2. Organize Files: Place all .java files in a single directory (e.g., java-string-demo).

  3. Verify JDK Version:

    • For FormInputCleaner.java, ensure JDK 11+ for strip(), stripLeading(), and stripTrailing().

    • For InvoiceFormatter.java, ensure JDK 15+ for formatted(), or replace with String.format() for older versions.

    • All other programs are compatible with JDK 8+.

  4. Compile and Run: Use an IDE or command line to compile and execute the programs (see below).

Running the Programs

Each program is a standalone Java application with a main method. To run a program:

Using Command Line

  1. Navigate to the project directory:

     cd path/to/java-string-demo
    
  2. Compile a specific program:

     javac ProgramName.java
    

    Example: javac StringBasicOperations.java

  3. Run the compiled program:

     java ProgramName
    

    Example: java StringBasicOperations

Using an IDE

  1. Import the project or individual .java files into your IDE (e.g., IntelliJ IDEA, Eclipse).

  2. Set the JDK version in the IDE (11+ for full compatibility).

  3. Run each program by selecting its main method or using the IDE’s run configuration.

Program Descriptions

Below is a brief description of each program, its scenario, and the String methods demonstrated:

  1. StringBasicOperations.java

    • Scenario: Processing user profile data.

    • Methods: valueOf(), length(), isEmpty(), isBlank(), charAt(), toCharArray().

    • Output: Displays converted strings, lengths, emptiness checks, and character arrays.

    public class UserProfileStringDemo {
        public static void main(String[] args) {
            // Scenario: Processing a user profile with string operations
            // 1. String.valueOf(Object): Convert user data to String
            double userScore = 95.5;
            char userGrade = 'A';
            String scoreStr = String.valueOf(userScore);
            String gradeStr = String.valueOf(userGrade);
            System.out.println("User Score: " + scoreStr); // Output: 95.5
            System.out.println("User Grade: " + gradeStr); // Output: A

            // 2. length(): Check the length of a username
            String username = "CodeMaster";
            int usernameLength = username.length();
            System.out.println("Username '" + username + "' has " + usernameLength + " characters"); // Output: 9

            // 3. isEmpty(): Validate profile description
            String description = ""; // Simulating no description provided
            String validDescription = "Enthusiastic coder";
            boolean isDescriptionEmpty = description.isEmpty();
            System.out.println("Is profile description empty? " + isDescriptionEmpty); // Output: true
            System.out.println("Is valid description empty? " + validDescription.isEmpty()); // Output: false

            // 4. isBlank(): Check for whitespace-only input in status
            String status = "   "; // Simulating empty status with spaces
            String activeStatus = "Online";
            boolean isStatusBlank = status.isBlank();
            System.out.println("Is status blank? " + isStatusBlank); // Output: true
            System.out.println("Is active status blank? " + activeStatus.isBlank()); // Output: false

            // 5. charAt(int index): Extract first letter of email
            String email = "user@example.com";
            char firstLetter = email.charAt(0);
            System.out.println("First letter of email '" + email + "': " + firstLetter); // Output: u

            // 6. toCharArray(): Display individual characters of a tag
            String tag = "Developer";
            char[] tagChars = tag.toCharArray();
            System.out.print("Characters in tag '" + tag + "': ");
            for (int i = 0; i < tagChars.length; i++) {
                System.out.print(tagChars[i] + (i < tagChars.length - 1 ? "-" : "")); // Output: D-e-v-e-l-o-p-e-r
            }
            System.out.println();
        }
    }
  1. EmailComparisonDemo.java

    • Scenario: Validating email addresses in a registration system.

    • Methods: equals(), equalsIgnoreCase(), compareTo(), compareToIgnoreCase(), startsWith(), endsWith(), contains().

    • Output: Shows comparison results and prefix/domain checks.

    public class EmailComparisonDemo {
        public static void main(String[] args) {
            // Scenario: Validating and comparing email addresses in a registration system

            // 1. equals(): Check if two email addresses are identical
            String email1 = "user@example.com";
            String email2 = "user@example.com";
            String email3 = "admin@example.com";
            boolean areEmailsEqual = email1.equals(email2);
            boolean areEmailsNotEqual = email1.equals(email3);
            System.out.println("Are '" + email1 + "' and '" + email2 + "' equal? " + areEmailsEqual); // Output: true
            System.out.println("Are '" + email1 + "' and '" + email3 + "' equal? " + areEmailsNotEqual); // Output: false

            // 2. equalsIgnoreCase(): Compare emails ignoring case
            String email4 = "User@Example.Com";
            boolean emailsEqualIgnoreCase = email1.equalsIgnoreCase(email4);
            System.out.println("Are '" + email1 + "' and '" + email4 + "' equal (ignore case)? " + emailsEqualIgnoreCase); // Output: true

            // 3. compareTo(): Compare emails lexicographically
            String email5 = "alice@example.com";
            String email6 = "bob@example.com";
            int comparisonResult = email5.compareTo(email6);
            System.out.println("Lexicographic comparison of '" + email5 + "' and '" + email6 + "': " + comparisonResult); // Output: negative (alice < bob)

            // 4. compareToIgnoreCase(): Compare emails lexicographically, ignoring case
            String email7 = "ALICE@EXAMPLE.COM";
            int comparisonIgnoreCase = email5.compareToIgnoreCase(email7);
            System.out.println("Lexicographic comparison (ignore case) of '" + email5 + "' and '" + email7 + "': " + comparisonIgnoreCase); // Output: 0 (equal)

            // 5. startsWith(): Check if email starts with a specific prefix
            String prefix = "user";
            boolean startsWithPrefix = email1.startsWith(prefix);
            System.out.println("Does '" + email1 + "' start with '" + prefix + "'? " + startsWithPrefix); // Output: true

            // 6. endsWith(): Check if email ends with a specific domain
            String domain = "@example.com";
            boolean endsWithDomain = email1.endsWith(domain);
            System.out.println("Does '" + email1 + "' end with '" + domain + "'? " + endsWithDomain); // Output: true

            // 7. contains(): Check if email contains a specific substring
            String substring = "example";
            boolean containsSubstring = email1.contains(substring);
            System.out.println("Does '" + email1 + "' contain '" + substring + "'? " + containsSubstring); // Output: true
        }
    }
  1. ProductDescriptionSearch.java

    • Scenario: Analyzing a product description for keywords.

    • Methods: indexOf(int ch), indexOf(String str), lastIndexOf(int ch), lastIndexOf(String str).

    • Output: Displays indices of characters and substrings.

    public class ProductDescriptionSearch {
        public static void main(String[] args) {
            // Scenario: Analyzing a product description for keywords and characters in an e-commerce system
            String description = "Smartphone with advanced camera and long-lasting battery.";

            // 1. indexOf(int ch): Find the first occurrence of a character
            char searchChar = 'a';
            int firstCharIndex = description.indexOf(searchChar);
            System.out.println("First occurrence of '" + searchChar + "' in description: index " + firstCharIndex); // Output: 2 (from "advanced")

            // 2. indexOf(String str): Find the first occurrence of a substring
            String searchKeyword = "camera";
            int firstKeywordIndex = description.indexOf(searchKeyword);
            System.out.println("First occurrence of '" + searchKeyword + "' in description: index " + firstKeywordIndex); // Output: 22

            // 3. lastIndexOf(int ch): Find the last occurrence of a character
            char lastSearchChar = 'a';
            int lastCharIndex = description.lastIndexOf(lastSearchChar);
            System.out.println("Last occurrence of '" + lastSearchChar + "' in description: index " + lastCharIndex); // Output: 49 (from "battery")

            // 4. lastIndexOf(String str): Find the last occurrence of a substring
            String lastSearchKeyword = "and";
            int lastKeywordIndex = description.lastIndexOf(lastSearchKeyword);
            System.out.println("Last occurrence of '" + lastSearchKeyword + "' in description: index " + lastKeywordIndex); // Output: 29

            // Additional example: Handling cases where the search term is not found
            String missingKeyword = "screen";
            int missingIndex = description.indexOf(missingKeyword);
            System.out.println("Index of '" + missingKeyword + "' (not found): " + missingIndex); // Output: -1 (not found)
        }
    }
  1. LogEntryProcessor.java

    • Scenario: Parsing log entries in a monitoring system.

    • Methods: substring(int beginIndex), substring(int beginIndex, int endIndex), split(String regex), split(String regex, int limit).

    • Output: Shows extracted substrings and split log components.

    public class LogEntryProcessor {
        public static void main(String[] args) {
            // Scenario: Processing a log entry string in a system monitoring application
            String logEntry = "2025-04-19 10:15:32|ERROR|Database connection failed|Server01";

            // 1. substring(int beginIndex): Extract the timestamp from the log entry
            String timestamp = logEntry.substring(0); // From start to end
            System.out.println("Full log entry as substring: " + timestamp); // Output: Entire log entry
            // More practical use: Extract only date part
            String datePart = logEntry.substring(0, 10);
            System.out.println("Date part of log: " + datePart); // Output: 2025-04-19

            // 2. substring(int beginIndex, int endIndex): Extract the time part
            String timePart = logEntry.substring(11, 19);
            System.out.println("Time part of log: " + timePart); // Output: 10:15:32

            // 3. split(String regex): Split the log entry into components
            String[] logComponents = logEntry.split("\\|"); // Split by pipe delimiter
            System.out.println("Log components:");
            for (int i = 0; i < logComponents.length; i++) {
                System.out.println("Component " + (i + 1) + ": " + logComponents[i]);
            }
            // Output:
            // Component 1: 2025-04-19 10:15:32
            // Component 2: ERROR
            // Component 3: Database connection failed
            // Component 4: Server01

            // 4. split(String regex, int limit): Split with a limit on components
            String[] limitedSplit = logEntry.split("\\|", 2); // Limit to 2 components
            System.out.println("Limited split (2 components):");
            for (int i = 0; i < limitedSplit.length; i++) {
                System.out.println("Part " + (i + 1) + ": " + limitedSplit[i]);
            }
            // Output:
            // Part 1: 2025-04-19 10:15:32
            // Part 2: ERROR|Database connection failed|Server01
        }
    }
  1. MessageFormatter.java

    • Scenario: Formatting messages in a messaging application.

    • Methods: toLowerCase(), toUpperCase().

    • Output: Displays messages in different cases.

    public class MessageFormatter {
        public static void main(String[] args) {
            // Scenario: Formatting user input for a messaging application

            // Input: A user's message with mixed case
            String userMessage = "HeLLo! Welcome to Our Messaging App.";

            // 1. toLowerCase(): Convert the entire message to lowercase
            String lowerCaseMessage = userMessage.toLowerCase();
            System.out.println("Message in lowercase: " + lowerCaseMessage);
            // Output: hello! welcome to our messaging app.

            // 2. toUpperCase(): Convert the entire message to uppercase
            String upperCaseMessage = userMessage.toUpperCase();
            System.out.println("Message in uppercase: " + upperCaseMessage);
            // Output: HELLO! WELCOME TO OUR MESSAGING APP.

            // Practical example: Standardize a command input
            String userCommand = "sHoUt";
            String standardizedCommand = userCommand.toLowerCase();
            System.out.println("Standardized command: " + standardizedCommand);
            // Output: shout

            // Practical example: Format a title for display
            String title = "group chat announcement";
            String formattedTitle = title.toUpperCase();
            System.out.println("Formatted title: " + formattedTitle);
            // Output: GROUP CHAT ANNOUNCEMENT
        }
    }
  1. FormInputCleaner.java

    • Scenario: Cleaning form input for submission.

    • Methods: trim(), strip(), stripLeading(), stripTrailing().

    • Output: Shows cleaned input with removed whitespace.

    public class FormInputCleaner {
        public static void main(String[] args) {
            // Scenario: Cleaning user input for a form submission system

            // Input: User data with unwanted whitespace
            String fullName = "   John Doe   ";
            String email = "  user@example.com  ";
            String comment = "\t\tGreat service!\n\t";

            // 1. trim(): Remove leading and trailing whitespace (basic)
            String cleanedName = fullName.trim();
            System.out.println("Original name: '" + fullName + "'");
            System.out.println("Trimmed name: '" + cleanedName + "'");
            // Output:
            // Original name: '   John Doe   '
            // Trimmed name: 'John Doe'

            // 2. strip(): Remove leading and trailing whitespace (Unicode-aware)
            String cleanedEmail = email.strip();
            System.out.println("Original email: '" + email + "'");
            System.out.println("Stripped email: '" + cleanedEmail + "'");
            // Output:
            // Original email: '  user@example.com  '
            // Stripped email: 'user@example.com'

            // 3. stripLeading(): Remove only leading whitespace
            String cleanedCommentLeading = comment.stripLeading();
            System.out.println("Original comment: '" + comment + "'");
            System.out.println("Comment with leading whitespace removed: '" + cleanedCommentLeading + "'");
            // Output:
            // Original comment: '        Great service!
            //     '
            // Comment with leading whitespace removed: 'Great service!
            //     '

            // 4. stripTrailing(): Remove only trailing whitespace
            String cleanedCommentTrailing = comment.stripTrailing();
            System.out.println("Comment with trailing whitespace removed: '" + cleanedCommentTrailing + "'");
            // Output:
            // Comment with trailing whitespace removed: '        Great service!'
        }
    }
  1. CustomerReviewSanitizer.java

    • Scenario: Sanitizing customer reviews for a website.

    • Methods: replace(char oldChar, char newChar), replace(CharSequence target, CharSequence replacement), replaceAll(String regex, String replacement), replaceFirst(String regex, String replacement).

    • Output: Displays modified reviews.

    public class CustomerReviewSanitizer {
        public static void main(String[] args) {
            // Scenario: Sanitizing and formatting a customer review for a website
            String review = "This product is AWESOME!!! It has some issues, but it's great. AWESOME!!!";

            // 1. replace(char oldChar, char newChar): Replace exclamation marks with periods
            String calmReview = review.replace('!', '.');
            System.out.println("Original review: " + review);
            System.out.println("Review with exclamations replaced: " + calmReview);
            // Output:
            // Original review: This product is AWESOME!!! It has some issues, but it's great. AWESOME!!!
            // Review with exclamations replaced: This product is AWESOME... It has some issues, but it's great. AWESOME...

            // 2. replace(CharSequence target, CharSequence replacement): Replace "AWESOME" with "excellent"
            String refinedReview = review.replace("AWESOME", "excellent");
            System.out.println("Review with 'AWESOME' replaced: " + refinedReview);
            // Output: This product is excellent!!! It has some issues, but it's great. excellent!!!

            // 3. replaceAll(String regex, String replacement): Replace multiple punctuation marks with a single space
            String cleanedReview = review.replaceAll("[!]+", " ");
            System.out.println("Review with multiple punctuation replaced: " + cleanedReview);
            // Output: This product is AWESOME  It has some issues, but it's great. AWESOME 

            // 4. replaceFirst(String regex, String replacement): Replace only the first occurrence of "issues" with "features"
            String modifiedReview = review.replaceFirst("issues", "features");
            System.out.println("Review with first 'issues' replaced: " + modifiedReview);
            // Output: This product is AWESOME!!! It has some features, but it's great. AWESOME!!!
        }
    }
  1. TaskManagerFormatter.java

    • Scenario: Formatting task data in a task management system.

    • Methods: concat(String str), join(CharSequence delimiter, CharSequence... elements), String.join(CharSequence delimiter, Iterable<? extends CharSequence> elements).

    • Output: Shows concatenated and joined task details.

    import java.util.Arrays;
    import java.util.List;

    public class TaskManagerFormatter {
        public static void main(String[] args) {
            // Scenario: Generating formatted output for a task management application

            // 1. concat(String str): Concatenate task ID and description
            String taskId = "TASK001";
            String taskDescription = ": Complete project report";
            String taskEntry = taskId.concat(taskDescription);
            System.out.println("Concatenated task entry: " + taskEntry);
            // Output: Concatenated task entry: TASK001: Complete project report

            // 2. join(CharSequence delimiter, CharSequence... elements): Join task details with a delimiter
            String taskName = "Project Report";
            String priority = "High";
            String dueDate = "2025-04-25";
            String taskSummary = String.join(" | ", taskName, priority, dueDate);
            System.out.println("Task summary: " + taskSummary);
            // Output: Task summary: Project Report | High | 2025-04-25

            // 3. String.join(CharSequence delimiter, Iterable<? extends CharSequence> elements): Join a list of subtasks
            List<String> subtasks = Arrays.asList("Draft outline", "Write content", "Review edits");
            String subtaskList = String.join("; ", subtasks);
            System.out.println("Subtask list: " + subtaskList);
            // Output: Subtask list: Draft outline; Write content; Review edits

            // Practical example: Combine concat and join for a full task record
            String taskPrefix = "Task: ";
            String taskDetails = String.join(", ", taskName, dueDate);
            String fullTaskRecord = taskPrefix.concat(taskDetails);
            System.out.println("Full task record: " + fullTaskRecord);
            // Output: Full task record: Task: Project Report, 2025-04-25
        }
    }
  1. InvoiceFormatter.java

    • Scenario: Generating invoices in a billing system.

    • Methods: formatted(Object... args), String.format(String format, Object... args).

    • Output: Displays formatted invoice summaries and reminders.

    public class InvoiceFormatter {
        public static void main(String[] args) {
            // Scenario: Generating formatted invoices for a billing system

            // Input: Invoice details
            String customerName = "Jane Smith";
            int invoiceNumber = 1001;
            double totalAmount = 249.99;
            String itemDescription = "Wireless Headphones";

            // 1. formatted(Object... args): Format an invoice summary using the string as a template
            String invoiceTemplate = "Invoice #%d for %s - Total: $%.2f";
            String invoiceSummary = invoiceTemplate.formatted(invoiceNumber, customerName, totalAmount);
            System.out.println("Invoice Summary: " + invoiceSummary);
            // Output: Invoice Summary: Invoice #1001 for Jane Smith - Total: $249.99

            // 2. String.format(String format, Object... args): Format a detailed invoice line
            String detailedLine = String.format("Item: %s | Amount: $%.2f | Invoice No: %04d", 
                                              itemDescription, totalAmount, invoiceNumber);
            System.out.println("Detailed Invoice Line: " + detailedLine);
            // Output: Detailed Invoice Line: Item: Wireless Headphones | Amount: $249.99 | Invoice No: 1001

            // Practical example: Format a payment reminder
            String reminderTemplate = "Dear %s, please pay Invoice #%d ($%.2f) by %s.";
            String dueDate = "2025-05-01";
            String paymentReminder = String.format(reminderTemplate, customerName, invoiceNumber, totalAmount, dueDate);
            System.out.println("Payment Reminder: " + paymentReminder);
            // Output: Payment Reminder: Dear Jane Smith, please pay Invoice #1001 ($249.99) by 2025-05-01.

            // Additional example: Combine formatted() for a short confirmation
            String confirmationTemplate = "Payment for %s (Invoice #%d) confirmed.";
            String paymentConfirmation = confirmationTemplate.formatted(itemDescription, invoiceNumber);
            System.out.println("Payment Confirmation: " + paymentConfirmation);
            // Output: Payment Confirmation: Payment for Wireless Headphones (Invoice #1001) confirmed.
        }
    }
  1. PasswordAnalyzer.java

    • Scenario: Analyzing passwords in a security system.

    • Methods: getBytes(), codePoints(), chars(), hashCode(), matches(String regex).

    • Output: Shows byte arrays, code points, and complexity checks.

    import java.nio.charset.StandardCharsets;
    import java.util.stream.IntStream;

    public class PasswordAnalyzer {
        public static void main(String[] args) {
            // Scenario: Analyzing a password string for a security system
            String password = "Secure#2025!";

            // 1. getBytes(): Convert password to byte array
            byte[] passwordBytes = password.getBytes(StandardCharsets.UTF_8);
            System.out.print("Password as bytes: ");
            for (byte b : passwordBytes) {
                System.out.print(b + " ");
            }
            System.out.println();
            // Output: Password as bytes: 83 101 99 117 114 101 35 50 48 50 53 33

            // 2. codePoints(): Get Unicode code points of the password
            System.out.print("Unicode code points: ");
            IntStream codePoints = password.codePoints();
            codePoints.forEach(cp -> System.out.print(cp + " "));
            System.out.println();
            // Output: Unicode code points: 83 101 99 117 114 101 35 50 48 50 53 33

            // 3. chars(): Get character stream of the password
            System.out.print("Characters as int values: ");
            IntStream chars = password.chars();
            chars.forEach(ch -> System.out.print(ch + " "));
            System.out.println();
            // Output: Characters as int values: 83 101 99 117 114 101 35 50 48 50 53 33

            // 4. hashCode(): Compute the hash code of the password
            int hash = password.hashCode();
            System.out.println("Hash code of password: " + hash);
            // Output: Hash code of password: (varies, e.g., -1919076663)

            // 5. matches(String regex): Check if password meets complexity requirements
            // Regex: At least 8 characters, 1 digit, 1 special character
            String regex = "^(?=.*\\d)(?=.*[!@#$%^&*]).{8,}$";
            boolean isComplex = password.matches(regex);
            System.out.println("Is password complex (8+ chars, 1 digit, 1 special char)? " + isComplex);
            // Output: Is password complex (8+ chars, 1 digit, 1 special char)? true
        }
    }
  1. ProductLabelFormatter.java

    • Scenario: Formatting product labels for an e-commerce platform.

    • Methods: toUpperCase(), replace(), concat() (demonstrating immutability).

    • Output: Shows modified labels while confirming the original string remains unchanged.

    public class ProductLabelFormatter {
        public static void main(String[] args) {
            // Scenario: Preparing a product label for an e-commerce platform, demonstrating String immutability

            // Original product label
            String originalLabel = "Smart Watch - Model X123";
            System.out.println("Original label: " + originalLabel);

            // 1. Attempt to modify with toUpperCase() - creates a new String
            String upperCaseLabel = originalLabel.toUpperCase();
            System.out.println("Uppercase label: " + upperCaseLabel);
            System.out.println("Original label after toUpperCase(): " + originalLabel);
            // Output:
            // Uppercase label: SMART WATCH - MODEL X123
            // Original label after toUpperCase(): Smart Watch - Model X123
            // Note: originalLabel remains unchanged, showing immutability

            // 2. Attempt to modify with replace() - creates a new String
            String modifiedLabel = originalLabel.replace("Smart Watch", "Fitness Tracker");
            System.out.println("Modified label: " + modifiedLabel);
            System.out.println("Original label after replace(): " + originalLabel);
            // Output:
            // Modified label: Fitness Tracker - Model X123
            // Original label after replace(): Smart Watch - Model X123
            // Note: originalLabel remains unchanged

            // 3. Attempt to modify with concat() - creates a new String
            String extendedLabel = originalLabel.concat(" - In Stock");
            System.out.println("Extended label: " + extendedLabel);
            System.out.println("Original label after concat(): " + originalLabel);
            // Output:
            // Extended label: Smart Watch - Model X123 - In Stock
            // Original label after concat(): Smart Watch - Model X123
            // Note: originalLabel remains unchanged

            // 4. Practical example: Chain multiple operations, each creating a new String
            String formattedLabel = originalLabel.toLowerCase().replace("model", "Type").concat(" - Sale");
            System.out.println("Chained operations result: " + formattedLabel);
            System.out.println("Original label after chaining: " + originalLabel);
            // Output:
            // Chained operations result: smart watch - type x123 - Sale
            // Original label after chaining: Smart Watch - Model X123
            // Note: originalLabel remains unchanged, each method returns a new String
        }
    }

Notes

  • Java Version: Most programs work with Java 8+. For FormInputCleaner.java (uses strip()), use Java 11+. For InvoiceFormatter.java (uses formatted()), use Java 15+ or modify to use String.format().

  • Immutability: The ProductLabelFormatter.java program highlights that String objects are immutable, a key concept for understanding Java string operations.

  • Regex Usage: Programs like CustomerReviewSanitizer.java and PasswordAnalyzer.java use regular expressions, which may require familiarity with regex patterns.

  • Extensibility: Each program can be extended with additional features (e.g., reading input from files, integrating with a UI) for real-world applications.

0
Subscribe to my newsletter

Read articles from Prathamesh Karatkar directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Prathamesh Karatkar
Prathamesh Karatkar