Java String’s Immutability

Here are a set of diagrams to illustrate Java String’s immutability.

1. Declare a string

 

String s = "abcd";

s stores the reference of the string object. The arrow below should be interpreted as “store reference of”.

String-Immutability-1

 

2. Assign a string variable to another string variable

String s2 = s;

s2 stores the same reference value, since it is the same string object.

String-Immutability-2

 

3. Concat string

s = s.concat("ef");

s now stores the reference of newly created string object.

string-immutability

 

Summary

Once a string is created in memory(heap), it can not be changed. We should note that all methods of String do not change the string itself, but rather return a new String.

If we need a string that can be modified, we will need StringBuffer or StringBuilder. Otherwise, there would be a lot of time wasted for Garbage Collection, since each time a new String is created.

Mistakes Java Developers Make

This list summarizes the top 10 mistakes that Java developers frequently make.

Convert Array to ArrayList

To convert an array to an ArrayList, developers often do this:

List<String> list = Arrays.asList(arr);

Arrays.asList() will return an ArrayList which is a private static class inside Arrays, it is not the java.util.ArrayList class. The java.util.Arrays.ArrayList class has set(),get()contains() methods, but does not have any methods for adding elements, so its size is fixed. To create a real ArrayList, you should do:

ArrayList<String> arrayList = new ArrayList<String>(Arrays.asList(arr));

The constructor of ArrayList can accept a Collection type, which is also a super type forjava.util.Arrays.ArrayList.