How To Convert Integer Into String In Java

7 min read

How to Convert Integer to String in Java: A Complete Guide

Converting an int (or Integer) to a String is one of the most common tasks in Java programming. Whether you need to display a number in a GUI, write it to a file, or concatenate it with other text, knowing the right conversion technique makes your code cleaner, safer, and more efficient. This article walks you through every reliable method, explains when to use each one, and highlights performance considerations so you can choose the best approach for any situation.


Why Converting Integer to String Matters

In Java, primitive types like int are not objects, whereas String is a full‑featured class in the java.lang package. Many APIs—such as System.out.But println, JLabel. setText, or JDBC prepared statements—expect a String argument.

  • Display numeric values in user interfaces or console output.
  • Build dynamic messages (e.g., “You have scored 42 points”).
  • Serialize data for storage or transmission (JSON, CSV, XML).
  • Avoid concatenation errors that can arise when mixing primitives with strings.

Understanding the nuances of each conversion method helps you write code that is both readable and performant.


Core Methods for Integer‑to‑String Conversion

Java provides several built‑in ways to turn an integer into a string. Below are the most widely used techniques, each with its own strengths The details matter here. Still holds up..

1. String.valueOf(int i)

int number = 123;
String str = String.valueOf(number);
  • What it does: Internally delegates to Integer.toString(i), but handles null safely (returns "null" if the argument were null; not relevant for primitives).
  • When to use: Preferred for generic code where the argument might be an Object or you want a single, consistent utility method.
  • Performance: Very fast; the JVM often inlines the call.

2. Integer.toString(int i)

int number = 123;
String str = Integer.toString(number);
  • What it does: Directly converts the primitive int to its decimal string representation.
  • When to use: When you are certain you are working with an int (or Integer) and want the most explicit, type‑specific call.
  • Performance: Slightly faster than String.valueOf because it skips the extra indirection, though the difference is negligible in most applications.

3. Empty String Concatenation ("" + i)

int number = 123;
String str = "" + number;
  • What it does: The + operator triggers string concatenation, which the compiler translates into a StringBuilder.append chain.
  • When to use: Quick‑and‑dirty debugging or one‑liners where readability is not a concern.
  • Performance: Creates a temporary StringBuilder object each time, making it less efficient than the dedicated conversion methods, especially inside loops.

4. String.format("%d", i)

int number = 123;
String str = String.format("%d", number);
  • What it does: Uses the formatter syntax familiar from C’s printf. The %d specifier formats an integer in base‑10.
  • When to use: When you need additional formatting (padding, locale‑specific grouping, etc.) alongside the conversion.
  • Performance: Slightly slower due to parsing the format pattern, but still acceptable for infrequent calls.

5. DecimalFormat for Custom Patterns

int number = 123;
DecimalFormat df = new DecimalFormat("00000");
String str = df.format(number); // "00123"
  • What it does: Allows sophisticated patterns such as leading zeros, thousand separators, or custom symbols.
  • When to use: Financial reports, ID generation, or any scenario where the raw integer needs a specific visual layout.
  • Performance: Higher overhead because it creates a formatter object; reuse the same DecimalFormat instance if you call it repeatedly.

6. StringBuilder or StringBuffer Append

int number = 123;
StringBuilder sb = new StringBuilder();
sb.append(number);
String str = sb.toString();
  • What it does: Manual append to a mutable character sequence, then extracts the final string.
  • When to use: Building a larger string that already contains other parts; avoids multiple immutable string creations.
  • Performance: Efficient for concatenating many pieces in a loop.

7. Apache Commons Lang StringUtils

import org.apache.commons.lang3.StringUtils;

int number = 123;
String str = StringUtils.valueOf(number);
  • What it does: Wrapper around String.valueOf that also handles null gracefully.
  • When to use: Projects already depending on Apache Commons Lang for other utilities.
  • Performance: Same as String.valueOf; the benefit is consistency with other null‑safe helpers.

Choosing the Right Method: Decision Factors

Factor Best Choice Reason
Simplicity & readability String.Which means valueOf or Integer. Because of that, toString Clear intent, no extra objects. Plus,
Need for formatting (padding, commas) String. format or DecimalFormat Direct pattern support.
Inside a tight loop Integer.toString or StringBuilder.That's why append Minimal allocation overhead.
Already using Apache Commons StringUtils.valueOf Leverages existing dependency.
Debugging / quick test "" + number Fast to type, acceptable for non‑performance‑critical code.
Null safety with Object input String.valueOf(Object) Returns "null" instead of throwing NPE.

Easier said than done, but still worth knowing.


Under the Hood: How Java Performs the Conversion

When the JVM executes Integer.toString(int i), it follows these steps:

  1. Sign handling: If i is negative, a '-' character is prefixed and the absolute value is processed.
  2. Digit extraction: The algorithm repeatedly divides the number by 10, collecting remainders (the least‑significant digit) into a character array.
  3. Reverse: Because digits are obtained backwards, the array is reversed to produce the correct order.
  4. String construction: A new String is created from the character array, using the UTF‑16 encoding that Java strings employ internally.

String.valueOf simply calls Integer.toString for primitive int arguments, adding a null‑check branch that is bypassed for primitives.

new StringBuilder().append("").append(i).toString()

which explains why it creates an extra StringBuilder object each time.

Understanding this process helps you appreciate why the direct Integer.toString

method avoids the intermediate StringBuilder allocation and the extra method call indirection, making it the fastest option for raw conversion Took long enough..


Micro‑Benchmark Perspective (JMH)

To quantify the differences, a simple JMH benchmark running on a modern JDK (21+) with default GC settings yields results in the same ballpark as the table below. Numbers are nanoseconds per operation (lower is better); actual values vary by hardware and JVM warm‑up state.

| Benchmark Mode | Integer.Plus, toString | String. valueOf | "" + i | String.format | `StringBuilder No workaround needed..

Quick note before moving on.

Key Takeaways:

  • Integer.toString and String.valueOf are statistically tied. The JIT compiler inlines the trivial String.valueOf call, eliminating any overhead.
  • "" + i is measurably slower due to the mandatory StringBuilder allocation (though Escape Analysis can sometimes scalar-replace it, it is not guaranteed).
  • String.format is an order of magnitude slower because it parses the format string, creates a Formatter instance, and uses locale-sensitive machinery. Reserve it for actual formatting needs.
  • StringBuilder shines only when aggregating multiple values; for a single integer, it adds object allocation without benefit.

Common Pitfalls & Edge Cases

  1. Integer.MIN_VALUE (-2,147,483,648): The absolute value of Integer.MIN_VALUE cannot be represented as a positive int (overflow). The JDK implementation handles this special case explicitly before the standard division loop. Custom implementations often fail here.

  2. Locale Sensitivity: String.format("%d", number) and DecimalFormat respect the default Locale (e.g., using , as a grouping separator or different digit shapes in Arabic/Thai locales). Integer.toString always produces ASCII digits 0-9 and an ASCII minus sign -. For machine-readable output (logs, JSON, DB keys), Integer.toString is safer But it adds up..

  3. Boxing Overhead: Passing an int to a method accepting Object (e.g., String.valueOf(Object)) triggers autoboxing to Integer The details matter here. Simple as that..

    // Avoid in hot paths:
    String s = String.valueOf((Object) myInt); // Allocates Integer object
    // Prefer:
    String s = String.valueOf(myInt); // Primitive overload, no boxing
    
  4. Null Handling:

    • String.valueOf(null) → "null" (String literal).
    • String.valueOf((Integer) null) → "null".
    • Integer.toString(null) → Compile Error (primitives cannot be null).
    • Objects.toString(null, "default") → "default" (Java 9+).

Summary: The "Default" Rule

For the vast majority of production code converting an int to a String:

  1. Use Integer.toString(i) — It communicates intent precisely ("convert this primitive"), has zero overhead, and is the intrinsic the JIT expects.
  2. Use String.valueOf(i) — If you prefer a method that works uniformly on primitives and object references without changing the call site.
  3. Reach for String.format / DecimalFormat — Only when the requirement includes padding, grouping separators, or locale-specific rendering.
  4. Use StringBuilder — Only when building a composite string containing multiple data points.

By aligning your choice with the specific context—performance-critical loop, formatted report, or quick log statement—you ensure the code remains readable, maintainable, and efficient Not complicated — just consistent..

Currently Live

Latest from Us

Readers Also Checked

Similar Stories

Thank you for reading about How To Convert Integer Into String In Java. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home