String Immutability Demo

Problem

Read a word s. Call s.concat("!") and s.replace("a", "o") WITHOUT saving the results back into s, then print s (original). Then print the two new strings. Output three lines: original: <s>, after concat: <s>!, after replace: <s with every a replaced by o>. This shows that strings never change; every operation makes a new string.

Constraints

  • 1 <= length <= 100, no spaces

Examples

Input

banana

Output

original: banana
after concat: banana!
after replace: bonono

Solutions

Best approachTime O(n)Space O(n)

A String object can never change. Methods like concat and replace create a new object. If you forget to save the result, the original stays the same. That is a common beginner bug. Immutability makes strings safe to share between threads and to use as map keys.

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Show immutability.
 * Input   : One word.
 * Output  : Three lines.
 * Approach: Results are new strings.
 * Time    : O(n)
 * Space   : O(n)
 * Java    : 8 or newer.
 */
import java.util.Scanner;

public class Main {
    // This method solves the task. It receives the input and returns the answer.
    static String[] solve(String s) {
        // Step 1: concat and replace return NEW strings. They do not change s.
        String withExclamation = s.concat("!");
        String replaced = s.replace("a", "o");

        // Step 2: s is still the same as before. We print the original first.
        return new String[] {
            "original: " + s,
            "after concat: " + withExclamation,
            "after replace: " + replaced
        };
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String s = scanner.hasNextLine() ? scanner.nextLine() : "";
        System.out.println(String.join("\n", solve(s)));
    }
}
Hints (1)
  1. What does s.concat('!') do to s?