PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, August 4, 2022

[FIXED] Why is Boolean.valueOf(String) returning false when given neither true or false but a random String?

 August 04, 2022     boolean, exception, java, try-catch     No comments   

Issue

When using the method Boolean.valueOf(String) the return value is false when given any String besides "true". This try block neverseems to fail even if it should?

boolean a;

String b = "randomTextThatsNotTrueOrFalse";

try{
a= Boolean.valueOf(b);
} 
catch(IllegalArgumentException e) {

 LOG.error(b  + "is invalid. Only true or false are possible  Options.");

}

Solution

As per the spec (and, as expected, the source code of the OpenJDK implementation follows this spec), "true" (with any casing) is parsed as true, and all other strings are parsed as false:

   * Returns a {@code Boolean} with a value represented by the
   * specified string.  The {@code Boolean} returned represents a
   * true value if the string argument is not {@code null}
   * and is equal, ignoring case, to the string {@code "true"}.
   * Otherwise, a false value is returned, including for a null
   * argument.

Reading javadoc is important; you should make a habit of it.

If you want a method that returns true if passed "true", false if passed "false", and throws an IAEx otherwise, you'd have to write it yourself. It's about 80 characters worth of code.



Answered By - rzwitserloot
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing