The problem of entering boolean input values into a program
 

Recall how boolean values are represented inside a computer program:

  • The Boolean value false is represented by the binary number 00000000

  • The Boolean value true is represented by the binary number 00000001          

How we enter boolean inputs (values) from a keyboard

  • We type the (ASCII) text "false"       or

  • the (ASCII) text "true"

The problem of entering boolean input values into a program

What is the problem:

  • When you type in the input into the keyboard:

         true              
      

    the computer will receive these ASCII codes:

             01110100 01110010 01110101 01100101         
      
       which represents: t r u e
      

    The computer will not receive the Boolean representation 00000001 for true !!!

The problem of entering boolean input values into a program
 

The boolean input problem explained graphically (with a picture):

The keyboard cannot be used to enter the boolean representation for true !!!

Solution ?
 

  • We need to convert the input representation (in ASCII codes) to the internal boolean representation

    (Converting boolean strings is easy because there are only 2 possible input strings....)

Java's library contains a String ⇒ Boolean conversion method:

  • boolean parseBoolean( String s ) in the Boolean class: click here

    This method converts a "String representation" for a boolean value into the boolean representation for the boolean value

The solution of entering boolean input values problem explained graphically
 

parseBoolean( ) converts its input string into the corresponding boolean representation:

The boolean output value of parseBoolean( ) is stored in a boolean typed variable

The parseBoolean( ) conversion method
 

Description of the parseBoolean( ) method:

   boolean  parseBoolean( String s ): 

      return a boolean value depending
      on input string s

      If s is equal to "true",  returns true (= 1)
      If s is equal to "false", returns false (= 0)   
   

 

The parseBoolean( ) is very easy to write
(That was the main reason I chose this example to introduce the input conversion problem)

The parseBoolean( ) conversion method
 

How is the method parseBoolean( ) implementated in Java:

  public static boolean  parseBoolean( String s )  
  {
     if ( s.comparesTo("true") == 0 )
        return true;    // Note: true  ≡ binary number 00000001
     else
        return false;   // Note: false ≡ binary number 00000000  
  } 

Note 1: the statement return true will return the binary number 00000001 !!

Note 2: the statement return false will return the binary number 00000000 !!

DEMO: /home/cs255001/demo/java/String2Bool.java