Simple Java: 10 common problems in Java strings. simplejava
The following are the 10 most common questions about strings in Java.
How to compare strings? Use = or equals ()
In short, "=" is used to determine whether the reference is equal, and equals () is used to determine whether the value is equal. Unless you want to compare whether two strings are the same object, you should use the equals () method. It is better if you know the concept of string resident.
Character arrays instead of strings are preferred for sensitive information.
Strings are immutable, meaning they will exist until they are recycled by the garbage collector. However, for an array, You can explicitly change its elements. Using this method, sensitive information (such as passwords) will not be stored in the system for a long time.
Whether the switch statement can use string
Yes, for JDK 7, we can use a string as the switch condition. However, in JDK 6, we cannot use a string as the switch condition.
// java 7 only!switch (str.toLowerCase()) { case "a": value = 1; break; case "b": value = 2; break;}
How to convert a string to an integer
int n = Integer.parseInt("10");
It is simple, but sometimes it is ignored.
How to split strings by white space characters (multiple possible)
String[] strArray = aString.split("\\s+");
What is the substring () method?
In JDK 6, the substring () method does not create a new character array, but uses the character array of the original string. To create a new character array, you can add an empty string to the end, as shown below:
str.substring(m, n) + ""
This creates a new character array to form a new String object. This method sometimes improves performance, because the garbage collector can recycle useless large strings and only keep the remaining substrings.
In JDK7, the substring () method creates a new character array instead of using an existing one. For more information, see the following link.