Ad
  • Custom User Avatar

    Cool take! I didn't know you could use if statements inside matches like that!

  • Default User Avatar

    This comment is hidden because it contains spoiler information about the solution

  • Custom User Avatar

    This comment is hidden because it contains spoiler information about the solution

  • Custom User Avatar

    It works because a new object is returned. The variable 'x' does not change.
    public String replace(char oldChar, char newChar)
    Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.

  • Custom User Avatar

    Thanks for your guys' explanation!
    Correct me if I'm wrong. So, if my understanding is correct, the reason "final" is used is to ensure that String x does not change in the hands of outsiders, and the reason "x.replace" works is because String x is an object...

  • Custom User Avatar

    Warning: a mutable object declared as final will still be mutable. The only thing that final locks is the binding between the variable name and the reference of the object in memory, so final "protects the code" only when used on immutable data structures or basic data types:

    final List<String> lst = new ArrayList<>();
    lst.add("stuff");                              // => works like a charm!
    
  • Custom User Avatar

    If you try to assign new object or value to the variable with final keyword, the code will not compile.
    You should use it, if you specifically do not want any other programmist (or yourself) to change the value, because some of your code depends on it. In example:

    final double PI = 3.1415;
    // PI = 10.0; this line would not compile

    In this kata:
    x = "my custom solution"; // would not compile

  • Custom User Avatar

    Can someone explain the purpose of "final"?