Today I accidentally wanted to convert the string type to the boolean type. After checking the API document, I found that the document seemed to be a little incorrect. . .
Well, just send the test code directly, I don’t bother to say nonsense. . .
String s1 = "false"; String s2 = "true"; String s3 = "fAlSe"; String s4 = "TrUe"; String s5 = "true_a";
The above strings are used separately
Boolean.getBoolean(s1); Boolean.getBoolean(s2) Boolean.getBoolean(s3); Boolean.getBoolean(s4); Boolean.getBoolean(s5);
The returned values of the above 5 are false
The API documentation says this:
getBoolean
public static boolean getBoolean(String name)
true is returned if and only if a system property named after a parameter exists and is equal to a "true" string. (Starting with version 1.0.2 of the JavaTM platform, string testing is no longer case sensitive.) System properties are accessible through the getProperty method, which is defined by the System class.
If there is no attribute named after the specified name or if the specified name is empty or null, false is returned.
But I don't know why this happened. . .
Well, the result is false, so what should we do if we convert? It's okay, there is another method called Boolean.parseBoolean(string s);
Boolean.parseBoolean(s1); Boolean.parseBoolean(s2) Boolean.parseBoolean(s3); Boolean.parseBoolean(s4); Boolean.parseBoolean(s5);
The API documentation is written like this:
public static boolean parseBoolean(String s)
Parses the string parameter to a boolean value. If the String parameter is not null and equals "true" when case is ignored, the returned boolean represents a true value.
Example: Boolean.parseBoolean("True") returns true.
Example: Boolean.parseBoolean("yes") returns false.
This conversion is OK. . . . The results are: false , true , false , true , false
So, just use parseBoolean when converting
The above is the full content of the java string type conversion method brought to you by the editor. I hope everyone will support Wulin.com~