Java beginners must know about Java strings (1)
Below I have summarized 10 questions that Java developers often raise about Java strings. If you are also a beginner in Java, take a closer look:
1. How to compare strings? Should I use "=" or equals ()?
In general, "=" is used to compare the reference address of a string, while equals () is used to compare the value of a string. When two strings with the same value are compared with "=", the result may be false, while when equals () is used, it must be true. Unless the two strings are the same new objects, equals () should be used to compare whether the string values are the same ().
2. Why should char [] be used to store security-sensitive information better than String?
String is immutable, which means that once it is created, it will permanently reside in the memory until the Garbage Collector recycles it. However, with Array Storage, You can explicitly change the elements in the array. Therefore, with array storage, security information may not exist anywhere in the system memory.
3. Can I declare the switch statement using a string?
JAVA 7 and later versions are supported. In JDK 7, you can use strings to compare the switch statements. Jdk 6 or earlier versions cannot be used as follows:
- // java 7 only!
- switch (str.toLowerCase()) {
- case "a":
- value = 1;
- break;
- case "b":
- value = 2;
- break;
- }
4. How to convert a string to a numeric int type?
- int n = Integer.parseInt("10");
It is very simple, but it is often used and easy to be ignored.
5. How to use space characters to separate strings?
We can easily use regular expressions to separate strings. "s" indicates space characters, such as "", "t", "r", and "n"
- String[] strArray = aString.split("s+");