Convert Text Input in Java
When working with numerical input values, sometimes plain text is the representation provided. These text values are of String
type, not Integer
, float
, or boolean
, and will require conversion to an appropriate value that Java can work with. Java's built-in arithmetic and higher-level math operations require values as primitives or their corresponding wrapper types to perform mathematical functions. Otherwise, we will encounter errors due to wrong operand types. For this reason, we need to convert our text representations into the most suitable primitive or reference type. This topic shows you how to convert a text representation into usable Java types that you can use in various operations.
Converting text representations
Text input from the command-line arguments is a good example of text conversion requirements. Let's look at a code snippet named ConvertText
. Two parameters are required as input to avoid the ArrayIndexOutOfBoundsException
exception. Arguments 20
and 5.5
are passed at runtime when starting the application; these are the values we want to convert. We bring in two values without type designation, parse them to the required types needed, and then perform a numerical calculation. Upon running, the program will assign the values 20
and 5.5
to String
reference values a
and b
. Integer.parseInt(a)
converts String
20
to int
20
. The same happens to String
5.5
as it is converted to type float
by Float.parseFloat(b)
. The final calculation uses integer and floating-point arithmetic, providing the float
total value. This program illustrates text conversion method using wrapper classes: Integer
and Float
. The final calculation uses two strings, parsed into int
and float
, then returning float
.
// ConvertText 20 5.5
public class ConvertText {
public static void main(String[] args) {
//args values: 20 5.5
String a = args[0]; // 20
String b = args[1]; // 5.5
int aInt = Integer.parseInt(a); // 20 converted to int
float bFloat = Float.parseFloat(b); // 5.5 converted to float
float total = aInt * bFloat; //
System.out.println("total " + total);
}
}
The float
value total
was calculated using the two converted arguments:
float total = aInt * bFloat; // float total = 110.0
As a note: You can eliminate reference values a
and b
if you directly substitute args[0]
and args[1]
into the parse methods. The String[] args
initially converts the input arguments to String
type anyway, removing the need for reference values a
and b
. As seen below:
int aInt = Integer.parseInt(args[0]); // 20 converted to int
float bFloat = Float.parseFloat(args[1]); // 5.5 converted to float
The boolean
primitive type also has a corresponding wrapper class named Boolean
. This type only has two values: true
and false
. This special method; Boolean.parseBoolean
, can convert text input — as a string argument — to a boolean. The String
must be equal to true
ignoring case (case-insensitive). Any other value — including null
— is evaluated to a boolean value false
. Let's now look at an example with the boolean
data type.
This example puts four values into booleanArray
. The first array entry evaluates to true after using parseBoolean
; all three remaining entries evaluate false
.
public class ConvertBoolean {
public static void main(String[] args) {
boolean[] booleanArray = {
Boolean.parseBoolean("true"), // true
Boolean.parseBoolean("false"), // false
Boolean.parseBoolean("anything"), // false
Boolean.parseBoolean(null) // false
};
for (boolean ba : booleanArray) {
System.out.println(ba);
}
}
}
Parse any type
In the previous section, we saw how to get values to float
, int
, and boolean
from strings using wrapper parse methods. It's important to know that the string argument parses as a signed integer; the string can contain a plus sign "+" or a minus sign "-" to indicate a positive or negative value. An explicit positive sign, or no sign at all, are both considered positive values. You can find examples of parsing signed values below:
double d = Double.parseDouble("-1.5"); // returns: -1.5
double d = Double.parseDouble("+1.5"); // returns: 1.5
double d = Double.parseDouble("1.5"); // returns: 1.5
2 * Double.parseDouble("-1.5"); // returns: -3.0
byte b = Byte.parseByte("-7"); // returns: -7
byte b = Byte.parseByte("+7"); // returns: 7
byte b = Byte.parseByte("7"); // returns: 7
3 * Byte.parseByte("-7"); // returns: -21
The table below shows all the remaining parse methods that can be applied as needed.
Parse methods for primitive wrapper classes
boolean bl = Boolean.parseBoolean("true");
byte b = Byte.parseByte("7");
short s = Short.parseShort("101");
int i = Integer.parseInt("25");
long l = Long.parseLong("5012345678");
float f = Float.parseFloat("9.205");
double d = Double.parseDouble("77.8989898989");
Assignment can be applied to an object or primitive type (Integer
, int
) as seen below:
int imPrimitive = Integer.parseInt("25");
Integer imObject = Integer.parseInt("25");
When converting text, we can choose the correct type value as needed. You would pass an object value when required, such as using the Collections API or generic classes. On the other hand, converting to a primitive avoids all the overhead associated with autoboxing. Using primitives in computationally intensive tasks is always recommended.
Radix argument
Radix indicates which number system to use. Up to this point, we have only looked at the parse method using the default radix, decimal (base 10). See below for some of the most common number systems in use:
- binary — base 2 (0, 1);
- octal — base 8 (0, 1, 2, 3, 4, 5, 6, 7);
- decimal — base 10 (0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
- hexadecimal — base 16 (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F).
Now let's look at another form of the parse method that requires a radix (base) as the second argument. In the following example, the number system is base 10. The two-argument method has an explicit radix 10, which can be changed to any base as required. The single-argument method defaults to radix 10. The return value is 25 decimal (base 10) in both cases.
int i = Integer.parseInt("25", 10); // return: 25 decimal
int i = Integer.parseInt("25"); // return: 25 decimal
Changing the radix to octal (base 8), as seen below, the output is now 21 decimal (base 10).
int i = Integer.parseInt("25", 8); // return: decimal 21
Again, changing the radix to hexadecimal (base 16), the return value is 37 decimal.
int i = Integer.parseInt("25", 16); // return: decimal 37
The following numerical wrapper classes (Byte
, Short
, Integer
, Long
) have a parse method with a radix. The first string argument is parsed in the radix as specified by the second argument. In the previous example, 16 is the number system that must be applied to "25"
to correctly interpret the value we want to convert to decimal 37.
NumberFormatException
When using the parsing methods, we must be careful not to throw a NumberFormatException
. This exception happens when we try to convert an improperly formatted or illegal string value. The following list provides conditions that throw a NumberFormatException
:
- a null first argument;
- zero-length string;
- radix is smaller or larger than permitted;
- characters in the string argument are not digits found in the radix — exceptions: "+", "-";
- the string argument is not of type
int
.
Let's apply these conditions to see what happens. Below is an example using null
:
Long.parseLong(null, 10) // NumberFormatException: null
Next, error thrown due to an empty string:
Long.parseLong("", 10) // NumberFormatException: For input string: ""
A Radix of 1 is not permitted here since it is less than Character.MIN_RADIX
.
Integer.parseInt("21", 1) // NumberFormatException: radix 1 less than Character.MIN_RADIX
Now the radix is too large — greater than Character.MAX_RADIX
.
Integer.parseInt("21", 37) // NumberFormatException: radix 37 greater than Character.MAX_RADIX
String "82" has a character not found in base 8. The only characters in base 8 are 0, 1, 2, 3, 4, 5, 6, and 7.
Integer.parseInt("82", 8) // NumberFormatException: For input string: "82"
In this case, "two"
will not convert to type int
.
Integer.parseInt("two", 10) // NumberFormatException: For input string: "two"
It should now be clear that your application will throw a NumberFormatException
whenever you try to convert a string with an improper format. Now, let's look at a code example illustrating the use of the parse methods covered here. Since throwing an exception is possible, using a try-catch block on the code containing the parse methods is good practice.
public class RadixArgument {
public static void main(String[] args) {
try {
int[] parsedArray = {
Integer.parseInt("11", 2), // decimal 3
Integer.parseInt("13", 4), // decimal 7
Integer.parseInt("11", 8), // decimal 9
Integer.parseInt("-201", 10), // decimal -201
Integer.parseInt("1F", 16), // decimal 31
Integer.parseInt("1N", 24) // decimal 47
};
for (int i : parsedArray) {
System.out.println(i);
}
} catch (NumberFormatException e) {
System.err.println(e);
}
}
}
Conclusion
When converting text input (string) into a primitive value or its respective object type, we can use special methods provided by wrapper classes like the parse methods to get each respective type from strings. All numerical types and boolean have separate parse methods. Also, we looked at the overloaded parse method for each primitive type; the single argument ("string") and the double arguments ("string", radix). Radix is key to the number system; it's crucial for the correct outcome. Finally, we saw that trying to convert improperly formatted string values will result in a NumberFormatException
.