Translated from: Top 10 questions of Java Strings
Simply put, "==" tests whether the references of two strings are the same, and equals() tests whether the values of the two strings are the same. Unless you want to check whether two strings are the same object, it's better to use equals().
It would be better if you know the string persistence mechanism.
Strings are immutable, which means that once they are created, they remain there until they are cleaned up by the garbage collector. With an array, you can explicitly modify its elements. This way, security-sensitive information (such as passwords) will not appear anywhere else on the system.
For Java7 the answer is yes. Starting from JDK7, we can use String as the condition of the switch statement. Before JDK6, we could not use String as the condition of switch statement.
// java 7 only!switch (str.toLowerCase()) { case "a": value = 1; break; case "b": value = 2; break;}
int n = Integer.parseInt("10");
Quite simply, it is used so often that it is sometimes ignored.
We can simply use regular expressions to decompose it. "/s" represents white space characters, such as " ", "/t", "/r", "/n".
String[] strArray = aString.split("//s+");
In JDK6, the substring() method provides a window into a character array representing an existing string, but does not create a new string. To create a new string represented by a new character array, add an empty string as follows:
str.substring(m, n) + ""
This creates a completely new character array representing the new string. The above approach sometimes makes the code faster because the garbage collector will collect large unused strings and only keep a substring.
In Oracle JDK 7, substring() creates a new character array without using the existing array. The diagram in The substring() Method in JDK 6 and JDK 7 illustrates the differences between substring() in JDK 6 and JDK 7.
String vs StringBuilder: StringBuilder is mutable, which means that one can change its value after creation.
StringBuilder vs StringBuffer: StringBuffer is synchronous, which means it is thread-safe, but slower than StringBuilder.
In Python, we can repeat a string by multiplying it by a number. In Java, we can repeat a string through the repeat() method of the StringUtils class in the Apache Commons Lang package.
String str = "abcd";String repeated = StringUtils.repeat(str,3);//abcdabcdabcd
String str = "Sep 17, 2013";Date date = new SimpleDateFormat("MMMM d, yy", Locale.ENGLISH).parse(str);System.out.println(date);//Tue Sep 17 00:00 :00 EDT 2013
Use the StringUtils class from the Apache Commons Lang package.
int n = StringUtils.countMatches("11112222", "1");System.out.println(n);
Additional question: How to detect that a string contains only uppercase letters
Translated from: Top 10 questions of Java Strings