Search code examples
immutabilityoperator-keywordternary

Immutable Strings with Ternary Operator


I was working on a project and I wrote this piece of code
dna = Math.random() > PERCENT ? dna + LETTERA : dna + LETTERB; and I don't exactly know why it works.

dna is a String
LETTERA and LETTERB are char

The code itself works how I want it to, the problem is I don't understand why. I thought that Strings in Java were immutable so when I say dna + LETTERA I should receive an error, but I don't.

At first when I wrote the code I did not use dna + LETTERB I used dna += LETTERB but I receive the following error, Syntax error on token "+=", + expected

If you write something like:
String testStr = "test";
testStr + "example";
you get an error InvalidAssignmentOperator so can someone explain to me why you can add to a String within a ternary operator like this?


Solution

  • string + something creates a new String, so the original String is unchanged (it has to be since it's immutable) and there's a new immutable String created with the new character on the end of it.

    So that's why the ternary operator works fine. It'll create one or the other new String on either side of the : (depending on the condition before ?) and give you back the one it created.


    The error with the code you gave is different for me, so I'm unsure:

    error: not a statement
            testStr + "example";
                    ^
    

    I think you might have meant this:

    String testStr = "test";
    testStr += "example";
    

    That compiles. The reason why is that the object "test" is immutable, but not the variable testStr. Unless the variable is marked final by you, you can have the variable refer to a different object later.

    It's a bit like if you erase an address from an envelope and write a different address. You haven't changed anything about the house at that address (you haven't mutated the house). You've just changed which house you're referring to (you've just mutated the envelope that refers to the house).

    At first, testStr refers to "test". Later, it refers to "testexample". The old, immutable "test" is still there until it's garbage collected. It wasn't changed. A completely new String was created and now the variable, which isn't immutable, refers to a new immutable String.