Java Data Conversion 

 

When a Java program receives input data from a user, it must often convert it from one form (e.g., String) into another (e.g., double or int) for processing. Checking data for validity is also highly desirable.  In this lesson, we look at several issues for validating and converting data.


Validity

Consider including one or more isValidXXX methods, where XXX is the type involved, such as Number or Double.  By doing so, you isolate that function and you make the process reusable in different parts of your program.  It also makes you conscious of this important step in designing your program.  For example:

public boolean isValidNumber(String n) {
    
    }

Validation can refer both to the format of a type of data and its semantics.  

For example, suppose a program expects to obtain a numerical value from a TextField where the user types a value.  The java.awt.TextField provides access to data entered by a user in the form of a Java String (i.e. getText() ).  Assume, further, that the program will attempt to convert the String representation of the (supposed) numerical value to a double value for processing.  The first issue, then, is whether or not the String can be parsed as a number.  Things that would cause problems would be the String's including special or alphabetic characters.  A user might understandably include such as indicators of metrics, for example, inches or pounds. 

One can, of course, check for specific characters or ranges, but it is often more convenient to try to parse the numeric String and to catch an appropriate exception if the parse fails.  For example:

try  {
      do the conversion
      return true;
      }
catch (NumberFormatException e) {
      e.printStackTrace();
      return false;
      }

If the conversion process is successful, the validation method returns true; if it fails, it prints out a trace of the problem and returns false.

Of course, if the number requires or permits special formatting, such as Social security numbers (NNN-NN-NNNN) or telephone numbers (nnn-nnn-nnnn), the value must be parsed as a String.

A second issue is semantic validation.  Once a data type that is to be converted has been validated with respect to format, it may require validation with respect to the specific value represented.  Is it too large, too small, negative when it should be positive, etc.?  

A natural place to perform such test is immediately following the conversion step within a try clause.  For example:

try  {
      do the conversion
      if (value >= 0) return true;
      else return false;
      }
catch (NumberFormatException e) {
      e.printStackTrace();
      return false;
      }

Conversion

Since conversion is part of the validation process, duplicating that code in a conversion method should be straight forward.  For example:

public boolean getNumber(String n) {
    
    }

Some of the methods that are often used include the following:

Double

Integer

String