String
1. Declare: double quotes "" and Constructor
double quotes:
String x = "a";String y = "a";
here, both x == y and x.equals(y) will return true, since x and y are referring to the same string literal in the method area, the memory references are the same. thus, when the same string literal is created multi-times, only one copy is stored, which is also called "Intern". All compile-time constant strings in Java are auto-interned.
Constructor:
String x = new String("a");String y = new String("a");
here, x == y will return false, but x.equals(y) still return true. Because every time we use constructor, we create a new object, so x and y are two different objects in the heap, so the memory references are different. we can also do the intern at run-time.
String x = new String("a").intern();String y = new String("a").intern();
Now, x == y will return true, since there is only one copy of "a" and the references of x and y are the same.
From above, we can know that "==" compares two objects' reference, but equals() method only compare their value. In the practice, if we do need to create a new object in the heap, construcor should be used.
2. Immutable
String is immutable class, and its instances cannot be modified.
Once a String is created in heap/memory, it can't be changed. All methods of String do not change the string itself, but rather return a new String. We can use StringBuilder or StringBuffer to modify string, StringBuffer is thread-safe, so the performance is worse than StringBuilder which is not thread-safe.
String x = "a";String y = x;
y stores the same reference value, since the string is the same with x
Immutable is very important feature of String. If String is not immutable, changing string from one reference will lead to wrong value for other references.
a. String Pool: exist in Method Area. if the same string is created, the reference of the existing string will be returned instead of creating a new object.
b. Caching Hashcode: being immutable guarantees that hashcode will always be the same
c. Security: String is widely used as parameter for many classes, if String is mutable, it may cause security problem in reflection, network connection, File open, etc.
d. Thread-safe: immutable objects can be shared among multi-threads without change, eliminate use of synchronization.
3. FAQ
why is char[] preferred over String for security sensitive?
With an array, we can change its elements, but String is immutable, once created, can only wait GC to kick them out.
Convert String to Date
String s = "Jun, 30, 2014";Date date = new SimpleDateFormat("MMMM d yyyy", Locale.ENGLISH).parse(s);
4. Some String method:
char charAt(int index); int compareTo(Object o); String concat(String s); boolean equals(Object o); int hashCode(); int indexOf(String s); String intern(); int length(); String replace(char old, char new); String[] split(String regex); char[] toCharArray(); String toLowerCase(); String toUpperCase(); String toString(); String trim();