Home » Java Basics » 03 - Java Installation and Simple Programs
3

Basic Java Objects - Strings

An array of characters that cannot be modified

A String is not a primitive type in Java. It may be envisioned as an Object defined in the class java.lang.String. Strings may also be considered an array of characters. A string in Java, once created, is immutable; that is, it cannot be modified. You may apply methods to change the string or append other strings to the original string. Setting the original string's variable name equal to the name of the changed string would not modify the string. Such commands create new strings. The original string remains but is no longer referred to by the variable name. For ‘string appends’, a new string is created for each variable or literal between the '+' plus symbol. The de-referenced objects hang around in memory waiting for the garbage collector to pick them up. Look at the picture below to understand the immutable property of strings. The lines of code involving 'myString' represent four sequential lines of code. Objects colored orange represent new string objects created for that line of code.

Figure 3a: Strings Immutability in Java
Figure 3a: Strings Immutability in Java