java string type converts methods of type boolean

  • 2020-05-17 05:23:55
  • OfStack

Today, I happened to want to convert string type to boolean type. I checked the api document and found that the document seemed a little wrong.

Well, just send the test code.


String s1 = "false"; 
String s2 = "true"; 
String s3 = "fAlSe"; 
String s4 = "TrUe"; 
String s5 = "true_a"; 

The above string is used separately


Boolean.getBoolean(s1); 
Boolean.getBoolean(s2) 
Boolean.getBoolean(s3); 
Boolean.getBoolean(s4); 
Boolean.getBoolean(s5); 

The return value of the above five is false

The api document says:

getBoolean
public static boolean getBoolean(String name)

Returns true if and only if the system property named with the parameter exists and is equal to the "true" string. (starting with version 1.0.2 of the JavaTM platform, string tests are no longer case sensitive.) System properties are accessed through the getProperty method, which is defined by the System class.

If there is no property named with the specified name or if the specified name is null or null, false is returned.

But it turns out I don't know why it happened...

Well, it turns out it's all false, so what do we do when we convert? Well, there's another method called Boolean.parseBoolean(string s);



Boolean.parseBoolean(s1); 
Boolean.parseBoolean(s2) 
Boolean.parseBoolean(s3); 
Boolean.parseBoolean(s4); 
Boolean.parseBoolean(s5); 

The api document reads like this:

public static boolean parseBoolean(String s)

Parses the string argument to an boolean value. If the String parameter is not null and is equal to "true" when case is ignored, the boolean returned represents the true value.

Example: Boolean.parseBoolean ("True") returns true.

Example: Boolean.parseBoolean ("yes") returns false.

This conversion will do... The results were: false, true, false, true, false

So, when you convert, you just use parseBoolean


Related articles: