Converting Between String and Other Types

Naveen AnamaneniUpdated · 4 min read

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

  1. Each wrapper class has a parseXxx method: Integer.parseInt, Double.parseDouble, Long.parseLong, Boolean.parseBoolean.
  2. A 10-digit phone number is too big for int, so it needs long.
  3. Text with thousands separators must be cleaned first; parseDouble doesn't understand commas.
  4. "12.5" isn't a whole number, so parseInt throws NumberFormatException. 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
null

How it works

  1. String.valueOf(x) works for every type and is the clearest choice.
  2. Integer.toString(255, 2) converts to base 2 (binary). Use 16 for hexadecimal.
  3. "" + price works too, but valueOf says what you mean.
  4. String.format controls the look, such as two decimal places (see "String Formatting in Java").
  5. A char[] becomes a string with new String(chars) or String.valueOf(chars). Sorting the letters of "Java" puts the capital J first.
  6. String.valueOf(null object) returns the text "null" instead of throwing.

Conversion Table

FromToMethod
Stringint, long, doubleInteger.parseInt, Long.parseLong, Double.parseDouble
StringInteger objectInteger.valueOf (see "Integer.parseInt() vs Integer.valueOf()")
StringbooleanBoolean.parseBoolean (true only for "true", any case)
Stringchar[]s.toCharArray()
StringBigDecimalnew BigDecimal(s)
Any valueStringString.valueOf(x)
intString in another baseInteger.toString(n, radix), Integer.toHexString(n)
char[]Stringnew String(chars)
charStringString.valueOf(c) or Character.toString(c)
List or arrayStringlist.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

  1. Easy: Read two numbers as strings from args, convert them and print their sum.
  2. Harder: Write static int toIntOrDefault(String text, int fallback) that strips the text, removes commas, and returns fallback for null, blank or invalid input. Test it with " 1,200 ", "abc" and null.

Quick check: Conversions

4 questions
1Which converts "42" to an int?
2What does Integer.parseInt("12.5") do?
3Which turns any value into text, even null?
4What does Integer.toString(255, 16) return?

Key Takeaways

Was this tutorial helpful?

Lesson 197 of 482