Java int and String Conversion Guide: Safe, Fast, and Best Practices

目次

1. Introduction: Why int ⇔ String Conversion Is Essential

When developing applications in Java, converting between int and String is one of the most fundamental operations you cannot avoid. For example, when a user enters a numeric value into an input form, the program initially receives it as a String. However, if you want to perform calculations, you must convert it into an int or another numeric type. Conversely, when displaying calculation results on the screen or storing them in a file or database, you need to convert numeric values back into Strings.

Such type conversions are common across many programming languages, but in Java, explicit conversion (using casting or methods) is required. This makes it a frequent stumbling point for beginners. In addition, depending on the conversion method used, errors may occur or unexpected behavior may appear. Therefore, acquiring correct knowledge and best practices is extremely important.

This article explains how to convert between int and String in Java, starting from the basics and extending to practical real-world use cases. In addition to fundamental usage, it covers common mistakes, performance comparisons, and frequently asked questions. Use this guide as a reliable reference for your Java development work.

2. Basics: Methods for Converting int to String

There are several ways to convert an int value into a String in Java. While you can choose based on preference or situation, considering readability, performance, and long-term maintainability leads to recommended approaches. Below are three representative methods and their characteristics.

2.1 Using String.valueOf(int)

The most versatile and safest method is using String.valueOf(int).
This method supports not only int, but also other primitive types (long, float, double, etc.) and object types.

int num = 123;
String str = String.valueOf(num);  // str becomes "123"

String.valueOf returns the literal string "null" when passed a null value, which helps prevent unexpected NullPointerException. If you prioritize safety and readability, this should be your default choice.

2.2 Using Integer.toString(int)

Another commonly used method is Integer.toString(int).
The Integer class is a wrapper for the primitive int type, and this static method converts an int value directly into a String.

int num = 456;
String str = Integer.toString(num);  // str becomes "456"

This method offers performance comparable to String.valueOf. While there is little difference in practice, Integer.toString can feel more intuitive when your intent is explicitly “convert int to String.”

2.3 Concatenation with an Empty String (“” + int)

A surprisingly common approach is converting via concatenation with an empty String.

int num = 789;
String str = "" + num;  // str becomes "789"

This works correctly according to Java specifications. However, the intent of conversion is less explicit, making the code harder to understand during reviews or team development. It may be acceptable for quick scripts, but it is generally less recommended.

2.4 Comparison Table: Differences and Recommended Usage

MethodReadabilityPerformanceRecommendationNotes
String.valueOf(int)HighExcellent◎ RecommendedNull-safe, works for many types
Integer.toString(int)HighExcellent◎ RecommendedSpecialized for int
“” + intMediumGood○ Limited useLess explicit intent

All methods work correctly, but as a general rule, use String.valueOf or Integer.toString. These are standard, well-accepted practices in professional Java development.

3. Basics: Methods for Converting String to int

Converting from String to int is just as common in Java. User input, configuration values, and external file data are usually received as Strings. To perform calculations, these values must be converted into int. This section explains three representative methods and their important considerations.

3.1 Using Integer.parseInt(String)

The most basic and widely used method is Integer.parseInt(String).
It converts a numeric String directly into an int value.

String str = "123";
int num = Integer.parseInt(str);  // num becomes 123

If the String cannot be interpreted as a valid number (for example, “abc” or an empty String), a NumberFormatException is thrown. When dealing with user input or uncertain data, wrapping this call in a try-catch block is strongly recommended.

3.2 Using Integer.valueOf(String)

Integer.valueOf(String) can also convert a String into a numeric value.
The key difference is that it returns an Integer object instead of a primitive int.

String str = "456";
Integer numObj = Integer.valueOf(str);  // Integer object
int num = numObj.intValue();            // primitive int

Internally, this method performs almost the same conversion as parseInt, and it also throws NumberFormatException for invalid input. It is useful when you need null handling or object-based processing.

4. Practical Examples: Sample Code

This section provides concrete code examples for converting between int and String in Java. From basic usage to exception handling techniques commonly used in real-world projects, these examples are ready to copy and use.

4.1 Converting int to String

int num = 100;

// 1. Using String.valueOf
String str1 = String.valueOf(num);

// 2. Using Integer.toString
String str2 = Integer.toString(num);

// 3. Using string concatenation
String str3 = "" + num;

System.out.println(str1); // Output: 100
System.out.println(str2); // Output: 100
System.out.println(str3); // Output: 100

5. Advanced: Converting Other Numeric Types (long / float / double)

In Java development, you frequently work not only with int, but also with other numeric types such as long, float, and double. In real-world projects, data received from databases or APIs is not always limited to int values. Understanding how to convert these numeric types to and from String is therefore extremely useful. This section explains the basic conversion methods and key points for each type.

5.1 Converting long and String

// long → String
long l = 123456789L;
String str1 = String.valueOf(l);        // Recommended
String str2 = Long.toString(l);         // Also acceptable

// String → long
String strLong = "987654321";
long l2 = Long.parseLong(strLong);      // Convert String to long
Long lObj = Long.valueOf(strLong);      // Wrapper class

5.2 Converting float / double and String

// float → String
float f = 3.14f;
String strF = String.valueOf(f);        // Recommended
String strF2 = Float.toString(f);       // Also acceptable

// String → float
String strFloat = "2.718";
float f2 = Float.parseFloat(strFloat);  // Convert String to float
Float fObj = Float.valueOf(strFloat);   // Wrapper class

// double → String
double d = 1.414;
String strD = String.valueOf(d);        // Recommended
String strD2 = Double.toString(d);      // Also acceptable

// String → double
String strDouble = "0.577";
double d2 = Double.parseDouble(strDouble);  // Convert String to double
Double dObj = Double.valueOf(strDouble);    // Wrapper class

5.3 Choosing Between Overloaded Methods and Wrapper Classes

String.valueOf(), parseXxx(), and valueOf() are overloaded for each numeric type. By selecting the appropriate method for the data type, you can perform conversions safely and concisely.
Understanding the difference between primitive types and wrapper classes (for example, int vs Integer, double vs Double) is also helpful when dealing with null values or collections.

5.4 Important Notes When Converting

  • When converting floating-point numbers (float / double), be aware of rounding errors, scientific notation, and decimal precision. Use DecimalFormat or String.format when formatting is required.
  • Because long and double support larger ranges than int, always consider the risk of overflow or precision loss during conversion.

For other numeric types as well, the basic conversion patterns are almost identical to int ⇔ String. Creating reusable utility methods can greatly improve development efficiency across different scenarios.

6. Common Mistakes and Failure Cases

Although int and String conversion may look simple, there are many common pitfalls that beginners and even experienced developers encounter. This section introduces representative problem cases along with concrete examples and countermeasures to help you avoid errors and unexpected behavior.

6.1 Errors Caused by Full-Width Digits, Empty Strings, and null

In systems designed for Japanese or international environments, user input may include full-width digits, empty strings, or even null values.
Attempting to convert these directly into numeric values will result in exceptions.

String zenkaku = "123";   // Full-width digits
String empty = "";          // Empty string
String nullStr = null;      // null

try {
    int num1 = Integer.parseInt(zenkaku); // NumberFormatException
} catch (NumberFormatException e) {
    System.out.println("Full-width digits cannot be converted");
}

try {
    int num2 = Integer.parseInt(empty);   // NumberFormatException
} catch (NumberFormatException e) {
    System.out.println("Empty strings cannot be converted");
}

try {
    int num3 = Integer.parseInt(nullStr); // NullPointerException
} catch (NullPointerException e) {
    System.out.println("null cannot be converted");
}

Countermeasures:

  • Always perform null checks and empty string checks before conversion
  • Convert full-width digits to half-width before parsing (for example, using replaceAll)

6.2 Handling NumberFormatException

Integer.parseInt and Integer.valueOf will always throw NumberFormatException when an invalid string is provided.
Ignoring this risk can cause your program to terminate unexpectedly.

Example countermeasure:

String input = "abc";
try {
    int num = Integer.parseInt(input);
} catch (NumberFormatException e) {
    System.out.println("Invalid numeric input: " + input);
}

6.3 Application Termination Due to Unhandled Exceptions

If no exception handling is implemented, errors caused by user input or external data can immediately terminate the application.
In web or server-side applications, this may lead to service outages or corrupted data.

Countermeasures:

  • Always implement exception handling, especially for external data and user input
  • Clearly define recovery behavior, such as default values or error messages

Summary

Although int ⇔ String conversion seems straightforward, it contains many hidden pitfalls in real-world scenarios.
Always implement the following three as a set: input normalization, null / empty checks, and exception handling.
Doing so will significantly reduce bugs and operational issues.

7. Practical Techniques for Safe Conversion

Depending on the content of input or external data, int and String conversion can cause unexpected exceptions or defects. This section introduces safe and practical techniques, along with best practices commonly used in professional development.

7.1 Using a Custom safeParseInt Method

When dealing with user input or external files where unexpected values may appear, creating a custom “safe conversion method” is highly effective.
By catching exceptions and returning a default value, you can greatly reduce the risk of application failure.

public static int safeParseInt(String str, int defaultValue) {
    if (str == null || str.isEmpty()) {
        return defaultValue;
    }
    try {
        return Integer.parseInt(str);
    } catch (NumberFormatException e) {
        return defaultValue;
    }
}

Usage examples:

int n1 = safeParseInt("456", 0);      // → 456
int n2 = safeParseInt("abc", 0);      // → 0
int n3 = safeParseInt("", 99);        // → 99
int n4 = safeParseInt(null, -1);      // → -1

7.2 Thorough null and Empty String Checks

Many exceptions originate from null or empty values.
Always validate input before conversion to prevent unnecessary errors.

String input = ...; // Value from any source

if (input != null && !input.isEmpty()) {
    int value = Integer.parseInt(input);
    // Safe to proceed
} else {
    // Apply default value or error handling
}

7.3 Readable and Maintainable Code Design

When the same conversion logic is used in multiple places, consolidating it into utility methods improves reusability and maintainability.
Additionally, variable and method names should clearly indicate what is being converted and for what purpose.

Good example:

int userAge = safeParseInt(form.get("age"), 0);

Bad example:

int x = Integer.parseInt(s);

7.4 Preparing for Unexpected Input with Unit Tests

After implementing custom conversion logic, adding unit tests further improves reliability.
Test null values, empty strings, invalid input, and boundary cases to ensure consistent behavior.

Safe type conversion relies on three pillars: validation, exception handling, and reusability.
Simple precautions can significantly reduce development stress.

8. Performance Verification and Measurement

There are multiple ways to convert between int and String in Java, and while differences are usually negligible, they may matter in large-scale data processing or high-frequency loops. This section discusses performance characteristics and benchmarking considerations.

8.1 Performance Characteristics of Common Methods

For the three main int → String conversion methods (String.valueOf, Integer.toString, and "" + int), performance differences are usually minimal.
However, precise benchmarks may reveal small variations.

  • Integer.toString(int) and String.valueOf(int): almost identical and very fast; depending on the JVM, Integer.toString may be slightly faster.
  • "" + int: internally uses StringBuilder, making it marginally slower for simple conversions, though the difference is usually insignificant.

8.2 Sample: Simple Benchmark Code

The following is a simple benchmark to measure conversion differences:

public class IntToStringBenchmark {
    public static void main(String[] args) {
        int count = 10_000_000;
        int num = 12345;
        long start, end;

        // Integer.toString
        start = System.currentTimeMillis();
        for (int i = 0; i < count; i++) {
            String s = Integer.toString(num);
        }
        end = System.currentTimeMillis();
        System.out.println("Integer.toString: " + (end - start) + "ms");

        // String.valueOf
        start = System.currentTimeMillis();
        for (int i = 0; i < count; i++) {
            String s = String.valueOf(num);
        }
        end = System.currentTimeMillis();
        System.out.println("String.valueOf: " + (end - start) + "ms");

        // "" + int
        start = System.currentTimeMillis();
        for (int i = 0; i < count; i++) {
            String s = "" + num;
        }
        end = System.currentTimeMillis();
        System.out.println("\"\" + int: " + (end - start) + "ms");
    }
}

8.3 Key Points for Large-Scale Processing

  • For a small number of conversions, performance differences can be ignored
  • In loops executed millions of times or in batch / real-time processing, choose simple and low-overhead methods
  • Readability and maintainability are still important—avoid over-optimizing prematurely
  • For precise measurements, consider tools such as JMH (Java Microbenchmark Harness)

Summary

In typical applications, any standard int ⇔ String conversion method is sufficient. However, in performance-critical systems, consistently using official and simple methods can yield small cumulative gains.
Choosing the optimal approach ultimately depends on benchmarking within your own environment.

9. Summary: Recommended Methods by Use Case

So far, we have covered various ways to convert between int and String in Java, along with practical considerations and pitfalls.
This section summarizes which method to choose depending on your use case.

9.1 When You Need Simple Conversion

  • int → String
  • String.valueOf(int) or Integer.toString(int)

    → Both offer excellent readability and performance and are standard choices.
  • String → int
  • Integer.parseInt(String)

    → The most straightforward approach with no unnecessary wrappers.

9.2 When Error Handling and Safety Matter

  • Always add validation and exception handling when dealing with unexpected input, null values, or empty strings.
  • Use custom methods such as safeParseInt to improve application stability.

9.3 For Performance-Critical Large-Scale Processing

  • Standard methods like Integer.toString(int) and Integer.parseInt(String) are generally the fastest.
  • String concatenation ("" + int) is acceptable for small tasks but should be avoided in extreme high-frequency loops.

9.4 When Wrapper Classes (Integer, etc.) Are Required

  • Use Integer.valueOf(String) or Integer.valueOf(int) when null values must be allowed or object-based handling is required.

9.5 Converting Other Numeric Types

  • long, float, and double can also be converted using corresponding valueOf and parseXxx methods.

9.6 Tips for Safe and Efficient Conversion Design

  • Centralize conversion logic into utility methods to improve reuse and maintainability.
  • Use clear variable and method names that express the purpose and direction of conversion.

Final Takeaway

Converting between int and String is a fundamental part of Java development.
By understanding subtle differences and best practices, you can write safer, cleaner, and more efficient code.
Use this guide to choose the most appropriate conversion strategy for your project.

10. Related Links and References

This section lists official documentation and related articles that will help deepen your understanding of int and String conversion in Java.

10.1 Official Java Documentation (External Links)

10.2 Recommended Related Articles

Related

1. Introduction Basics of Integer Types in Java When working with numbers in Java, one of the most fundamental da[…]

10.3 Additional Resources

Bookmark these resources to support your daily development and learning.
Combining official documentation with practical articles will help you build a stronger foundation.

11. FAQ: Frequently Asked Questions

This FAQ section summarizes common questions developers have when converting between int and String in Java.

Q1. Is it okay to convert using “” + int?

A. It works for simple or temporary use cases, but for better readability and maintainability, String.valueOf(int) or Integer.toString(int) is recommended—especially in team development.

Q2. What is the difference between String.valueOf(null) and null.toString()?

A. String.valueOf(null) returns the literal string "null", whereas null.toString() throws a NullPointerException. Always handle null values carefully.

Q3. How can I convert full-width digits or empty strings?

A. Full-width digits such as "123" will cause NumberFormatException. Convert them to half-width first. Empty strings cannot be parsed, so always check for null or emptiness before conversion.

Q4. What are the benefits of using wrapper classes like Integer?

A. Wrapper classes allow null values and object-based handling, which is useful when working with collections or frameworks that require objects rather than primitives.

Q5. How can I efficiently convert large amounts of data?

A. Standard methods such as Integer.parseInt() and Integer.toString() are generally the fastest. For critical paths, run benchmarks in your own environment.

Q6. Can I convert decimal numbers directly to int?

A. No. Strings like "123.45" will throw NumberFormatException. Parse them as double or float first, then cast to int if truncation is acceptable.

Q7. Can strings with signs be converted to int?

A. Half-width signs such as "-123" are supported. Full-width symbols are not, so ensure proper normalization.

This FAQ helps you avoid common conversion pitfalls and improve overall reliability.
If additional questions arise, consider expanding this section as your project evolves.

12. Appendix: Handy Utility Code for Copy & Paste

Below are practical utility methods for safely and efficiently converting between int and String in Java. These snippets can be directly reused in real projects.

12.1 Safe String → int Conversion: safeParseInt

This method returns a default value instead of throwing an exception when invalid input or null is provided.

public static int safeParseInt(String str, int defaultValue) {
    if (str == null || str.isEmpty()) {
        return defaultValue;
    }
    try {
        return Integer.parseInt(str);
    } catch (NumberFormatException e) {
        return defaultValue;
    }
}

Usage:

int n1 = safeParseInt("456", 0);      // → 456
int n2 = safeParseInt("abc", 0);      // → 0
int n3 = safeParseInt("", 999);       // → 999
int n4 = safeParseInt(null, -1);      // → -1

12.2 Safe int → String Conversion with Null Handling

While String.valueOf and Integer.toString are usually sufficient, this example handles null wrapper values safely.

public static String safeIntToString(Integer value, String defaultValue) {
    if (value == null) {
        return defaultValue;
    }
    return Integer.toString(value);
}

Usage:

String s1 = safeIntToString(123, "N/A");    // → "123"
String s2 = safeIntToString(null, "N/A");   // → "N/A"

12.3 Converting Full-Width Digits to Half-Width

If full-width digits appear in user input or external data, convert them before parsing.

public static String zenkakuToHankaku(String str) {
    if (str == null) {
        return null;
    }
    return str.replaceAll("[0-9]", m ->
        String.valueOf((char)(m.group().charAt(0) - '0' + '0'))
    );
}

Usage:

String halfWidth = zenkakuToHankaku("1234"); // → "1234"
int n = safeParseInt(halfWidth, 0);            // → 1234

12.4 Generic Utility Methods for Other Numeric Types

You can create similar utility methods for other numeric types.

public static long safeParseLong(String str, long defaultValue) { ... }
public static float safeParseFloat(String str, float defaultValue) { ... }
public static double safeParseDouble(String str, double defaultValue) { ... }

By preparing these utility methods in your project, you can significantly reduce unexpected bugs and exceptions while improving development efficiency.
Feel free to customize them to suit your needs.