Visualization 01pi.com logo 01pi.com

Strings: Very useful objects

Created with Snap012345678910111213

Code

                        ...
String strA;
strA = "A";
boolean b1 = strA == "A";
boolean b2 = strA.equals("A");
String strB = "B";
String strC = "AB";
String strD;
strD = strA + strB;
boolean b3 = strC == strD;
boolean b4 = strC.equals(strD);
...

	
                    

Board

Created with Snap024681012memory02468symbol tablecolor coding tableStringGarbage0000

Trace

                        
Statements                       | "A" "B" "AB"  strA strB strC strD  b1     b2     b3     b4    
-------------------------------- | --- --- ----  ---- ---- ---- ----  ------ ------ ------ ------

                    

Description

We will be investigating String objects.

  • String is frequently used

    • but it is not easy to understand
    • There are surprises, too. See b2.
  • To start with, String is object.

  • String is immutable

    • Once created it cannot be changed.
  • Because of immutability, your code creates and destroys many String objects during its execution

    • It is better to understand this process
System.out.println("AB".length());

Is this an error?