Converting Between String and Other Types
Everything a user types, every value in a file and every field in a web request arrives as text. Before you can add a quantity or compare a price, you have to turn that text into a number. And when you show results, you turn numbers back into text. These conversions happen in almost every program, so it's worth knowing the right method for each direction and what goes wrong when the text isn't valid.
Text to Values
FromText.java▶ Try it
public class FromText {
public static void main(String[] args) {
int qty = Integer.parseInt("12");
double price = Double.parseDouble("49.50");
boolean member = Boolean.parseBoolean("true");
long phone = Long.parseLong("9876543210");
System.out.println("Bill: " + qty * price);
System.out.println(member + " " + phone);
double fromForm = Double.parseDouble("1,234.5".replace(",", ""));
System.out.println(fromForm);
try {
Integer.parseInt("12.5");
} catch (NumberFormatException e) {
System.out.println("Not a whole number: " + e.getMessage());
}
}
}Output
Bill: 594.0
true 9876543210
1234.5
Not a whole number: For input string: "12.5"How it works
- Each wrapper class has a
parseXxxmethod:Integer.parseInt,Double.parseDouble,Long.parseLong,Boolean.parseBoolean. - A 10-digit phone number is too big for
int, so it needslong. - Text with thousands separators must be cleaned first;
parseDoubledoesn't understand commas. "12.5"isn't a whole number, soparseIntthrowsNumberFormatException. Always be ready for it with user input.
Values to Text
ToText.java▶ Try it
import java.util.Arrays;
public class ToText {
public static void main(String[] args) {
int qty = 12;
double price = 49.5;
String a = String.valueOf(qty);
String b = Integer.toString(255, 2);
String c = "" + price;
String d = String.format("%.2f", price);
System.out.println(a + " " + b + " " + c + " " + d);
char[] letters = "Java".toCharArray();
Arrays.sort(letters);
System.out.println(new String(letters));
Object nothing = null;
System.out.println(String.valueOf(nothing));
}
}Output
12 11111111 49.5 49.50
Jaav
nullHow it works
String.valueOf(x)works for every type and is the clearest choice.Integer.toString(255, 2)converts to base 2 (binary). Use 16 for hexadecimal."" + priceworks too, butvalueOfsays what you mean.String.formatcontrols the look, such as two decimal places (see "String Formatting in Java").- A
char[]becomes a string withnew String(chars)orString.valueOf(chars). Sorting the letters of "Java" puts the capitalJfirst. String.valueOf(null object)returns the text"null"instead of throwing.
Conversion Table
| From | To | Method |
|---|---|---|
String | int, long, double | Integer.parseInt, Long.parseLong, Double.parseDouble |
String | Integer object | Integer.valueOf (see "Integer.parseInt() vs Integer.valueOf()") |
String | boolean | Boolean.parseBoolean (true only for "true", any case) |
String | char[] | s.toCharArray() |
String | BigDecimal | new BigDecimal(s) |
| Any value | String | String.valueOf(x) |
int | String in another base | Integer.toString(n, radix), Integer.toHexString(n) |
char[] | String | new String(chars) |
char | String | String.valueOf(c) or Character.toString(c) |
| List or array | String | list.toString(), Arrays.toString(array) |
Common Mistakes
Parsing text with spaces or commas. Call strip() and remove separators first.
Using parseInt for big numbers. Phone numbers and account numbers need long, or should stay as text.
Calling obj.toString() on a possibly null reference. It throws; String.valueOf(obj) doesn't.
Practice
- Easy: Read two numbers as strings from
args, convert them and print their sum. - Harder: Write
static int toIntOrDefault(String text, int fallback)that strips the text, removes commas, and returnsfallbackfor null, blank or invalid input. Test it with" 1,200 ","abc"andnull.
Key Takeaways
Was this tutorial helpful?
Lesson 197 of 482