Java Numbers and Strings - Complete Guide
Introduction to Numbers and Strings
In Java, numbers and strings are frequently used together. Java provides automatic string conversion when using the + operator with numbers and strings, making concatenation simple.
However, explicit conversion methods are often needed for reliability, formatting, or when parsing user input. Understanding these conversions helps avoid errors and improves program clarity.
Converting Numbers to Strings
Numbers can be converted to strings using multiple approaches. Each method is useful in different contexts such as formatting or simple display.
public class NumberToString {
public static void main(String[] args) {
int number = 42;
double pi = 3.14159;
String str1 = "The answer is " + number;
System.out.println(str1);
String str2 = String.valueOf(number);
System.out.println("String value: " + str2);
String str3 = Integer.toString(number);
System.out.println("Integer string: " + str3);
String str4 = Double.toString(pi);
System.out.println("Double string: " + str4);
String str5 = String.format("Formatted: %.2f", pi);
System.out.println(str5);
StringBuilder sb = new StringBuilder();
sb.append("Pi is approximately ").append(pi);
System.out.println(sb.toString());
String nanStr = String.valueOf(Double.NaN);
String infinityStr = String.valueOf(Double.POSITIVE_INFINITY);
System.out.println("NaN: " + nanStr);
System.out.println("Infinity: " + infinityStr);
}
}
The answer is 42 String value: 42 Integer string: 42 Double string: 3.14159 Formatted: 3.14 Pi is approximately 3.14159 NaN: NaN Infinity: Infinity
Converting Strings to Numbers
Strings must be explicitly parsed into numbers using wrapper class methods. If a string does not contain a valid number, a NumberFormatException will be thrown.
public class StringToNumber {
public static void main(String[] args) {
String intStr = "123";
int intValue = Integer.parseInt(intStr);
System.out.println("Parsed int: " + intValue);
String doubleStr = "3.14";
double doubleValue = Double.parseDouble(doubleStr);
System.out.println("Parsed double: " + doubleValue);
Integer integerObj = Integer.valueOf("456");
Double doubleObj = Double.valueOf("2.718");
System.out.println("Integer object: " + integerObj);
System.out.println("Double object: " + doubleObj);
String hexStr = "FF";
int hexValue = Integer.parseInt(hexStr, 16);
System.out.println("Hex FF = " + hexValue);
String binaryStr = "1010";
int binaryValue = Integer.parseInt(binaryStr, 2);
System.out.println("Binary 1010 = " + binaryValue);
try {
int invalid = Integer.parseInt("abc");
System.out.println(invalid);
} catch (NumberFormatException e) {
System.out.println("Cannot parse 'abc' as integer: " + e.getMessage());
}
String testStr = "123.45";
boolean isNumeric = testStr.matches("-?\\d+(\\.\\d+)?");
System.out.println("Is '" + testStr + "' numeric? " + isNumeric);
}
}
Parsed int: 123 Parsed double: 3.14 Integer object: 456 Double object: 2.718 Hex FF = 255 Binary 1010 = 10 Cannot parse 'abc' as integer: For input string: "abc" Is '123.45' numeric? true
Number Formatting
Java offers several APIs for formatting numbers, including NumberFormat, DecimalFormat, and String.format(). These allow locale-specific formatting, currency formatting, and custom patterns.
import java.text.NumberFormat;
import java.text.DecimalFormat;
import java.util.Locale;
public class NumberFormatting {
public static void main(String[] args) {
double number = 12345.6789;
NumberFormat usFormat = NumberFormat.getInstance(Locale.US);
NumberFormat frFormat = NumberFormat.getInstance(Locale.FRANCE);
System.out.println("US format: " + usFormat.format(number));
System.out.println("France format: " + frFormat.format(number));
NumberFormat currencyFormat = NumberFormat.getCurrencyInstance(Locale.US);
System.out.println("US currency: " + currencyFormat.format(number));
DecimalFormat decimalFormat = new DecimalFormat("#,##0.00");
System.out.println("Custom format: " + decimalFormat.format(number));
DecimalFormat percentFormat = new DecimalFormat("0.00%");
System.out.println("Percent format: " + percentFormat.format(0.4567));
String formatted = String.format("Formatted: %,.2f", number);
System.out.println(formatted);
String padded = String.format("Padded: %08d", 42);
System.out.println(padded);
int intValue = 1000000;
double doubleValue = 1234.5678;
System.out.println(String.format("Integer with commas: %,d", intValue));
System.out.println(String.format("Float with 2 decimals: %.2f", doubleValue));
System.out.println(String.format("Scientific notation: %.2e", doubleValue));
}
}
US format: 12,345.679 France format: 12 345,679 US currency: $12,345.68 Custom format: 12,345.68 Percent format: 45.67% Formatted: 12,345.68 Padded: 00000042 Integer with commas: 1,000,000 Float with 2 decimals: 1234.57 Scientific notation: 1.23e+03
Best Practices for Numbers and Strings
- ✅ Use wrapper parse methods (e.g., Integer.parseInt, Double.parseDouble) for conversion
- ✅ Always handle NumberFormatException when parsing user input
- ✅ Use String.valueOf for consistent number-to-string conversion
- ✅ Use NumberFormat for locale-sensitive formatting
- ✅ Use String.format for straightforward formatting needs
- ✅ Use DecimalFormat for complex custom patterns
- ✅ Validate strings before parsing them as numbers
- ✅ Be cautious with floating-point precision issues when converting to strings