- 1 1. Basic Knowledge for Converting Between Numbers and Strings in Java
- 2 2. How to Convert Numbers to Strings
- 3 3. How to Convert Strings to Numbers
- 4 4. Conversions Using BigDecimal and BigInteger (Finance / Precision Calculations)
- 5 5. Common Errors During Conversion and How to Handle Them
- 6 6. Recommended Conversion Methods by Use Case
- 7 7. Common Mistakes and Anti-Patterns
- 8 8. Summary
- 9 9. Frequently Asked Questions (FAQ)
- 9.1 Q1. What is the single best way to convert a number to a string in Java?
- 9.2 Q2. Which should I use: parseInt or valueOf?
- 9.3 Q3. Is there a way to check if a string is numeric before converting?
- 9.4 Q4. Why does NumberFormatException happen during numeric conversion?
- 9.5 Q5. Why shouldn’t I use double for money calculations?
- 9.6 Q6. What should I be careful about when converting form input values to numbers?
- 9.7 Q7. What if I want to control the display format after converting to a string?
1. Basic Knowledge for Converting Between Numbers and Strings in Java
When developing in Java, you will inevitably encounter situations like “data that looks like a number but is handled as a string” or “values received as strings that you want to calculate as numbers.” For example, form inputs, CSV imports, API responses, and log output often arrive as strings even if they appear numeric.
In this section, we’ll organize why conversion is necessary and the points beginners commonly struggle with.
1.1 Why Conversion Becomes Necessary
Java programs handle the data type (type) explicitly. However, real-world data inputs and outputs tend to become “strings,” such as:
- User input: Even if you type “123” into a text box, what the program receives is basically a string
- Files (CSV / JSON / config files): When you read them, you often get values as strings
- HTTP/API: Many values are passed as strings (or the JSON type may be ambiguous)
- Display and logs: Rather than outputting numbers as-is, it’s common to convert to strings and format them
Because of this, two directions of conversion occur frequently in real work:
- Number → String: UI display, logs, messages, concatenation, etc.
- String → Number: calculations, comparisons, range checks, aggregation, etc.
What’s important here is: even if it looks numeric, different types mean different things.
"10"(string) and10(number) may look the same, but they are different types in code- String
"10" + "2"becomes"102"(concatenation) - Number
10 + 2becomes12(addition)
Mistakes like “I thought I was adding, but it turned into string concatenation” happen easily if you don’t keep this distinction in mind.
1.2 Java Is Strict About Types
Java is a statically typed language, so operations with mismatched types generally result in a compile-time error. This improves safety, but when moving between different types like strings and numbers, you need proper conversions.
For example, if you try to use a string input directly as a number, you’ll get an error.
- You want to calculate using the string
"123"as anint→ You must convert it tointbefore using it
Also, Java has two kinds of numeric types: primitive types and wrapper classes, which can be a common source of confusion.
- Primitive types:
int,long,double, etc. (lightweight, basic numbers) - Wrapper classes:
Integer,Long,Double, etc. (numbers handled as objects)
For example, Integer.valueOf("123") returns an Integer (object), while Integer.parseInt("123") returns an int (primitive).
We’ll cover this difference in more detail in the next section, but beginners often get stuck because “the same conversion seems to return different types.”
1.3 Differences Between Automatic and Explicit Conversion
When you hear “conversion,” you might imagine Java handles it automatically. In fact, there are behaviors that look like automatic conversion in some cases.
A common example is string concatenation.
- If you write
"Total: " + 10, the 10 appears to be automatically converted into a string
However, while convenient, this can also cause unintended results.
"10" + 2→"102"(string concatenation, not numeric addition)
So, Java has cases where values are implicitly stringified, but String → Number is basically not converted automatically.
In other words:
- Number → String: can happen implicitly in some contexts (such as concatenation)
- String → Number: always requires explicit conversion (such as parseInt)
Remembering this will keep you safe.
Also, when converting strings to numbers, inputs are not always valid.
- Empty string
"" - Spaces
" 123 " - Comma-separated
"1,000" - Trying to convert a decimal
"12.34"toint - Non-numeric characters
"12a"
In such cases, a runtime exception (typically NumberFormatException) will occur.
In real-world systems, it’s crucial to design assuming “invalid input may arrive.”
2. How to Convert Numbers to Strings
In this section, we’ll explain the most common ways to convert numbers into strings in Java, along with how to choose among them.
This conversion is used constantly in logs, UI output, and message building.
2.1 Using String.valueOf() (Most Common)
For converting numbers to strings, the safest and most recommended approach is String.valueOf().
int i = 100;
String s = String.valueOf(i);It supports not only int but also long, double, float, boolean, and almost all primitive types.
double d = 12.34;
String s = String.valueOf(d);Key features of this approach:
- Consistent syntax that’s easy to remember
- Works with both primitive types and wrapper classes
- High readability
- Clear intent (“this is a string conversion” at a glance)
It also safely stringifies wrapper objects.
Integer num = null;
String s = String.valueOf(num); // "null"Even if you pass null, it won’t throw a NullPointerException, which is especially useful for logging.
2.2 Using Integer.toString() / Double.toString()
Each numeric wrapper class provides a toString() utility method.
int i = 100;
String s = Integer.toString(i);double d = 12.34;
String s = Double.toString(d);This works correctly, but has these characteristics:
- The method differs by type (Integer / Double / Long, etc.)
- It’s a bit tedious to remember them all
- Less general-purpose than
String.valueOf()
So in real projects, String.valueOf() is often preferred unless you want to explicitly emphasize a specific type.
2.3 Caution When Calling toString() on Objects
You can also directly call toString() on wrapper objects or your own objects.
Integer i = 100;
String s = i.toString();This works, but you must be careful if null is possible.
Integer i = null;
String s = i.toString(); // NullPointerExceptionIf the object is null, this causes a runtime error.
For safety, String.valueOf() is a better fit in cases like:
- Log output
- Debug string generation
- Code paths where null may appear
2.4 Should You Use “+ “”” for Conversion?
You may have seen code like this:
int i = 100;
String s = i + "";Yes, it converts a number into a string. However, this is not a recommended approach.
Reasons:
- The intent is not obvious at a glance
- It’s ambiguous whether it’s concatenation or conversion
- Often disliked in code reviews
- More likely to cause misunderstandings during future changes
It may appear in short demos or quick tests, but it’s best avoided for maintainable code.
2.5 Summary: How to Choose Number → String Conversion
To avoid confusion in real work, remember this:
- Default choice: String.valueOf()
- If you want to emphasize the type: Integer.toString() / Double.toString()
- Calling toString() on objects requires null awareness
- Avoid + “” in principle
3. How to Convert Strings to Numbers
From here, we’ll explain the especially important topic in real projects: converting strings into numbers.
Because user input and external data are not guaranteed to be valid, understanding conversion methods and pitfalls is essential.
3.1 Using Integer.parseInt() (Most Basic)
A representative method for converting a string into an int is Integer.parseInt().
String s = "123";
int i = Integer.parseInt(s);This method returns the primitive type int, which is convenient when you want to immediately perform calculations or comparisons.
int total = Integer.parseInt("10") + Integer.parseInt("20");
// total is 30However, passing strings like the following will cause a runtime exception.
"abc"""(empty string)"12.3"(decimal)"1,000"(with commas)
int i = Integer.parseInt("abc"); // NumberFormatExceptionThis exception is not detected at compile time—it occurs at runtime, so you must be careful.
3.2 Using Integer.valueOf()
Integer.valueOf() is another representative way to convert a string into a number.
String s = "123";
Integer i = Integer.valueOf(s);The biggest difference from parseInt() is that the return type is Integer (a wrapper class).
parseInt()→intvalueOf()→Integer
This difference matters in scenarios like:
- Storing values in collections (List / Map)
- Designs that handle null
- When you want to treat the value as an object
Internally, valueOf() also throws NumberFormatException if conversion fails.
So it is not “less error-prone” than parseInt().
3.3 How to Choose Between parseInt and valueOf
If you’re unsure which to use, these criteria help:
- If the goal is calculation or comparison → parseInt()
- If you want to handle it as an object → valueOf()
Because modern Java has autoboxing, the practical difference is smaller, but it’s still important to develop the habit of choosing based on the return type.
3.4 Converting to Other Numeric Types Like double / long
You often need to convert strings into types other than integers.
long l = Long.parseLong("100000");
double d = Double.parseDouble("12.34");The basic rules are the same:
Long.parseLong()→longDouble.parseDouble()→doubleFloat.parseFloat()→float
All of them throw NumberFormatException if the string cannot be converted.
A key pitfall is trying to convert a decimal string into an integer type:
int i = Integer.parseInt("12.34"); // exceptionIn that case, you need a design that treats the value as double from the start.
3.5 Watch Out for Leading/Trailing Spaces
User input often contains spaces unintentionally.
String s = " 123 ";
int i = Integer.parseInt(s); // exceptionIn such cases, it’s common to use trim() before conversion.
int i = Integer.parseInt(s.trim());However, even after trim(), an exception will occur if non-numeric characters remain.
3.6 Summary: Key Points for String → Number Conversion
To convert strings into numbers safely, keep these points in mind:
- Always distrust external input
- Design assuming exceptions can occur
- Decide the numeric type clearly (int / long / double)
- Preprocess when needed (trim, etc.)
4. Conversions Using BigDecimal and BigInteger (Finance / Precision Calculations)
The int and double types introduced so far are convenient, but you must be careful when calculation precision is critical.
Especially for money, quantities, and rates, BigDecimal and BigInteger are used to avoid rounding and precision issues.
4.1 Why double Is Not Enough
Because double is a floating-point type, it is stored internally as an approximation in binary.
As a result, you may see behavior like this:
double d = 0.1 + 0.2;
System.out.println(d); // 0.30000000000000004This is not a bug—it’s by design.
It may look minor, but it can be fatal in cases like:
- Money calculations
- Billing and settlement processing
- Cumulative calculations of interest rates or ratios
In such cases, you need a type that does not introduce floating-point error.
4.2 String → Number Conversion Using BigDecimal
With BigDecimal, the rule is: create it from a string.
BigDecimal bd = new BigDecimal("12.34");A pattern you should avoid is:
BigDecimal bd = new BigDecimal(12.34); // not recommendedBecause the original double already contains an approximation error, converting to BigDecimal will carry that error forward.
Remember: always create BigDecimal from a String.
4.3 Number → String Conversion (BigDecimal)
To convert BigDecimal into a string, it’s common to use toString().
BigDecimal bd = new BigDecimal("12.3400");
String s = bd.toString(); // "12.3400"If you want display formatting, you can use DecimalFormat, but the best practice is to separate internal processing from display formatting.
4.4 When to Use BigInteger
BigInteger is used to handle very large integers.
BigInteger bi = new BigInteger("12345678901234567890");Typical use cases:
- Numbers with extremely large digit counts
- Numeric representation of IDs or hash values
- Integer calculations that exceed the range of
long
It’s less common in typical business applications, but it’s effective when you must handle integers with unknown or unbounded limits.
4.5 Summary: How to Think About BigDecimal / BigInteger
- Money / precision-critical calculations → BigDecimal
- Huge integers → BigInteger
- BigDecimal should be created from String
- Keep formatting separate from calculations
5. Common Errors During Conversion and How to Handle Them
When converting strings into numbers, you must assume errors can always happen.
In this section, we’ll organize common exceptions and safe handling approaches.
5.1 What Is NumberFormatException?
NumberFormatException is a runtime exception thrown when a string cannot be interpreted as a number.
int i = Integer.parseInt("abc"); // NumberFormatExceptionThis exception is not detected at compile time—it appears only when the code runs.
Therefore, if the input comes from outside (forms, files, APIs, etc.), you must always account for it.
Common causes include:
- Contains non-numeric characters
- Empty string or null
- Trying to convert a decimal into an integer type
- Contains commas or symbols (e.g., “1,000”)

5.2 Basic Handling with try-catch
The most basic approach is to use try-catch to catch the exception.
try {
int i = Integer.parseInt(input);
} catch (NumberFormatException e) {
// Handling when conversion fails
}Key points:
- Reliably handles the error path
- Makes failure behavior explicit
- Most commonly used in real projects
Combined with logging and error messages, this enables safe processing.
5.3 A Pre-check Approach to Avoid Exceptions
Separate from exception handling, you can also validate whether it’s numeric beforehand.
boolean isNumber = input.matches("\\d+");With a regex, you can check if the string contains only digits. However, there are important caveats:
- Hard to support decimals and negative numbers
- Can become complex
- Does not provide a complete guarantee
So, in practice, it’s realistic to treat try-catch as the final safety net.
5.4 Be Careful with null and Empty Strings
Before numeric conversion, it’s important to check for null or empty strings.
if (input == null || input.isEmpty()) {
// Error handling
}Skipping this check can lead to exceptions or unexpected behavior.
Empty strings are especially common in form inputs and config files.
5.5 Summary: How to Think About Error Handling
- Treat external input as potentially invalid
- Use try-catch to reliably catch exceptions
- Use pre-checks as supplemental validation
- Exclude null and empty strings early
6. Recommended Conversion Methods by Use Case
So far, we’ve covered the main ways to convert between numbers and strings in Java.
In this section, we’ll organize the use-case-based mindset so you won’t hesitate in real development.
6.1 UI Display and Log Output
For UI display and logs, safety and readability come first.
Recommended:
- Number → String:
String.valueOf() - Even when an object might be involved, use
String.valueOf()
log.info("count=" + String.valueOf(count));Even if null can appear, it prevents exceptions.
6.2 Calculations and Comparisons
For calculations and comparisons, the basic rule is to convert to numeric types as early as possible.
- String → Number:
parseInt()/parseLong()/parseDouble() - After conversion, complete processing using numeric types
int price = Integer.parseInt(inputPrice);
int total = price * quantity;Continuing to process as strings can cause subtle bugs.
6.3 Form Inputs and External Data Processing
Treat user input and external data under the assumption that invalid values will arrive.
- null / empty string checks
- Exception handling via try-catch
- Return error messages as needed
try {
int age = Integer.parseInt(input);
} catch (NumberFormatException e) {
// Input error handling
}Avoid writing “only the happy path”—think about error paths first.
6.4 Money and Precision-Critical Processing
For money, rates, and other cases where floating-point error is not acceptable, use BigDecimal.
- String → BigDecimal:
new BigDecimal(String) - Separate display formatting from calculations
BigDecimal amount = new BigDecimal(inputAmount);The key is not to go through double.
6.5 Storing in Collections or Handling as Objects
When storing values in a List or Map, or when your design handles null, wrapper classes are suitable.
Integer.valueOf()Long.valueOf()
List<Integer> list = new ArrayList<>();
list.add(Integer.valueOf("10"));6.6 Use-Case Summary
Summarized by use case:
- Display / logs →
String.valueOf() - Calculations →
parseXxx() - Money / precision →
BigDecimal - External input → design for exceptions
- Collections →
valueOf()
7. Common Mistakes and Anti-Patterns
Converting between numbers and strings is basic, but both beginners and experienced developers can make mistakes.
This section summarizes anti-patterns you should avoid in real projects.
7.1 Trying to Calculate While Keeping Strings
This code looks plausible but is risky:
String a = "10";
String b = "20";
String result = a + b; // "1020"This is not calculation—it’s string concatenation.
For numeric calculations, convert to numeric types first:
int result = Integer.parseInt(a) + Integer.parseInt(b); // 307.2 Overusing “+ “”” Conversion
String s = value + "";It works, but the intent is unclear and maintainability is low, so it’s not recommended.
- Likely to be called out in code reviews
- Confuses readers later
- Ambiguous whether it’s conversion or concatenation
Using String.valueOf() explicitly is safer.
7.3 Passing double Directly to BigDecimal
BigDecimal bd = new BigDecimal(0.1); // not recommendedThis is dangerous because it uses a double that already contains approximation error.
The correct approach:
BigDecimal bd = new BigDecimal("0.1");For money and precision-critical cases, always create it from a string.
7.4 Writing Code Assuming Exceptions Won’t Happen
int i = Integer.parseInt(input);In real projects, the assumption that input is always valid rarely holds.
When handling external input, always include exception handling:
try {
int i = Integer.parseInt(input);
} catch (NumberFormatException e) {
// Error handling
}7.5 Using Values Without Being Aware of Type Differences
It’s also common to use types without thinking about differences like int vs Integer, or double vs BigDecimal.
- Is your goal calculation?
- Is your goal display?
- Is precision critical?
Choosing types based on the purpose is the quickest way to prevent bugs.
8. Summary
In Java, converting between numbers and strings is used daily, but it’s also a process where small mistakes can lead to major issues.
Key takeaways from this article:
- For Number → String,
String.valueOf()is the default - For String → Number, choose between
parseXxx()andvalueOf()based on return type - Handle external input assuming exceptions can occur
- Use
BigDecimalfor money and precision-critical calculations - Avoid ambiguous patterns like
+ ""
Rather than memorizing methods, it’s more important to choose based on the use case and type.
With this mindset, you’ll get stuck far less often in Java’s fundamental processing.
9. Frequently Asked Questions (FAQ)
Here we summarize common stumbling points for readers searching “java number string conversion” in a Q&A format.
This section is meant to fill gaps that may remain after reading the main text.
Q1. What is the single best way to convert a number to a string in Java?
In general, the most recommended method is String.valueOf().
Reasons:
- Consistent and easy to understand
- Works with both primitive types and wrapper classes
- Does not throw an exception when passing null
String s = String.valueOf(100);In real projects, using this as your default helps you avoid mistakes.
Q2. Which should I use: parseInt or valueOf?
Choose based on the return type.
Integer.parseInt()→int(primitive)Integer.valueOf()→Integer(wrapper class)
If your goal is calculations, use parseInt().
If you want to store it in collections or treat it as an object, valueOf() is more suitable.
Q3. Is there a way to check if a string is numeric before converting?
A simple approach is to use a regular expression.
boolean isNumber = input.matches("\\d+");However, this method has limitations:
- Decimals and negatives are difficult to support
- It cannot guarantee complete safety
So, in practice, it’s best to assume that try-catch is still necessary as the final safety measure.
Q4. Why does NumberFormatException happen during numeric conversion?
NumberFormatException occurs when a string cannot be interpreted as a number.
Common causes:
- Contains non-numeric characters
- Empty string or null
- Trying to convert a decimal into an integer type
- Contains commas or symbols
When handling external input, always design under the assumption that exceptions can occur.
Q5. Why shouldn’t I use double for money calculations?
Because double is stored as an approximation in binary, floating-point error can occur.
double d = 0.1 + 0.2; // 0.30000000000000004For money, rates, and other precision-critical cases, the correct choice is to use BigDecimal created from a string.
BigDecimal bd = new BigDecimal("0.1");Q6. What should I be careful about when converting form input values to numbers?
Always keep these points in mind:
- Check for null / empty strings
- Catch exceptions with try-catch
- Define clear behavior for error cases
Treat user input as “potentially invalid” by default to prevent bugs.
Q7. What if I want to control the display format after converting to a string?
Keep numeric conversion and display formatting separate.
- Conversion:
String.valueOf()orBigDecimal - Formatting: use
DecimalFormat, etc.
Separating internal processing from presentation improves maintainability.


