Sub topic 10
Converting Between Strings and Values
A String holds text. An int holds a whole number, a double holds a number that can have a fraction, and a boolean holds either true or false.
These types are not the same, even when their contents look alike. The string "42" contains the text 42. The value 42 is an int that Java can use in arithmetic.
Conversion matters when a program reads text, such as a value from a user, and needs to use it as a number or a true-or-false value. It also matters when the program needs to turn a value back into text.
Choose a conversion
A method is an operation you can call to do a task. Java provides these methods for common conversions:
| Task | Method | Example result |
|---|---|---|
| Text to an `int` | `Integer.parseInt(text)` | `"42"` becomes `42` |
| Text to a `long` | `Long.parseLong(text)` | `"42"` becomes a `long` value |
| Text to a `double` | `Double.parseDouble(text)` | `"2.5"` becomes `2.5` |
| Text to a `boolean` | `Boolean.parseBoolean(text)` | `"true"` becomes `true` |
| A value to text | `String.valueOf(value)` | `42` becomes `"42"` |
A long is a whole-number type that can hold values outside the range of int.
Convert text to numbers
Parsing is the process of reading text and turning it into a value. For example, Integer.parseInt("42") reads the text and returns the int value 42.
Save this program as ConvertValues.java, then run it with javac ConvertValues.java followed by java ConvertValues.
class ConvertValues {
public static void main(String[] args) {
String countText = "42";
int count = Integer.parseInt(countText);
String priceText = "12.50";
double price = Double.parseDouble(priceText);
int nextCount = count + 1;
String resultText = String.valueOf(nextCount);
System.out.println(count);
System.out.println(price);
System.out.println(nextCount);
System.out.println(resultText);
}
}The program prints 42, 12.5, 43, and 43, each on its own line.
Follow the value through the program:
countTextstarts as the string"42".Integer.parseIntconverts it to the number42.- The program adds
1to that number. String.valueOfconverts the result back to the string"43".
The last two lines of output look the same, but nextCount is an int and resultText is a String.
Number text must be suitable
For Integer.parseInt, the text must describe a whole number within the range of int. A leading minus or plus sign is allowed.
Integer.parseInt("-7")returns-7.Integer.parseInt("12.5")cannot produce anintbecause the text contains a decimal point.Integer.parseInt(" 42 ")fails because of the spaces.Integer.parseInt("999999999999")fails because that value is too large for anint.
Use Long.parseLong when a whole number may be too large for an int. A long also has a limit, so it cannot hold every possible number.
Double.parseDouble accepts decimal text such as "12.5". It also accepts text such as "1e3", which means 1 multiplied by 1,000. Unlike Integer.parseInt, it accepts ordinary spaces at the start and end of the text.
A double stores an approximation of many decimal numbers. Do not assume it can represent every decimal amount exactly. For money calculations that need exact decimal results, Java offers BigDecimal, a class for working with decimal values.
Handle invalid number text
An exception is a signal that something went wrong while a program was running. A failed number conversion can produce a NumberFormatException. If the program does not handle it, the program may stop.
A try block contains code that might cause an exception. A catch block handles a matching exception. This lets the program report a problem and continue.
Save this program as CheckCounts.java, then compile and run it.
class CheckCounts {
public static void main(String[] args) {
String[] inputs = {" 12 ", "12.5", "999999999999", "-3"};
for (String input : inputs) {
String cleaned = input.trim();
try {
int count = Integer.parseInt(cleaned);
if (count < 0) {
System.out.println(input + ": count must not be negative");
} else {
System.out.println(input + ": accepted " + count);
}
} catch (NumberFormatException error) {
System.out.println(input + ": not a valid int");
}
}
}
}The program checks four strings:
" 12 "is accepted as12. Thetrimmethod removes the ordinary spaces at the ends before parsing."12.5"is rejected because it is not whole-number text."999999999999"is rejected because it is outside theintrange."-3"parses successfully, but the program rejects it because the count must not be negative.
The last case shows an important difference. Parsing checks whether text can become a value of the requested type. Your program may need additional checks to decide whether that value makes sense for its task.
In this example every input is a string. If an input can be null, check for null before calling trim, because calling a method on null causes an exception.
Convert text to a boolean
Boolean.parseBoolean returns true when the text is "true", ignoring differences between uppercase and lowercase letters. It returns false for other text.
For example, "TRUE" becomes true, but both "false" and "yes" become false. This method does not report invalid text. It also does not remove spaces: " true " becomes false.
If you need to tell valid false from invalid input, check the text first. Save this program as CheckFlags.java, then compile and run it.
class CheckFlags {
public static void main(String[] args) {
String[] inputs = {"TRUE", "false", "yes"};
for (String input : inputs) {
if ("true".equalsIgnoreCase(input)
|| "false".equalsIgnoreCase(input)) {
boolean flag = Boolean.parseBoolean(input);
System.out.println(input + ": accepted " + flag);
} else {
System.out.println(input + ": enter true or false");
}
}
}
}The equalsIgnoreCase method compares text without treating uppercase and lowercase letters as different. The || operator means “or.” Here, the program accepts either spelling and rejects "yes" instead of silently treating it as false.
Convert values to strings
Use String.valueOf when you need a string version of a value. For example:
String.valueOf(42)returns"42".String.valueOf(2.5)returns"2.5".String.valueOf(true)returns"true".
The result is text, not the original number or boolean. For example, String.valueOf(42) + 1 produces the text "421"; it does not add 1 to the number.
A conversion back to text does not always preserve the original spelling. In the first program, "12.50" became the double value 12.5. Turning that value back into text gives "12.5", not the original "12.50". Keep the original string if its exact spelling matters.
Practice
Exercise
What happens when Java runs Integer.parseInt("3.5")?
Show answer
It throws a NumberFormatException because "3.5" is not whole-number text.
Exercise
A program needs a positive count. Is a successful call to Integer.parseInt enough to check it?
Show answer
No. Parsing checks that the text represents an int. The program must also check that the result is greater than zero.
Exercise
What does Boolean.parseBoolean("yes") return, and how can you reject that input?
Show answer
It returns false. Check that the text is "true" or "false", ignoring case, before parsing it.