Java - Convert integer to string
There are multiple ways:
String.valueOf(number)
(my preference)"" + number
(I don't know how the compiler handles it, perhaps it is as efficient as the above)Integer.toString(number)
How do I convert a String to an int in Java?
String myString = "1234";
int foo = Integer.parseInt(myString);
If you look at the Java documentation you'll notice the "catch" is that this function can throw a NumberFormatException
, which you can handle:
int foo;
try {
foo = Integer.parseInt(myString);
}
catch (NumberFormatException e) {
foo = 0;
}
(This treatment defaults a malformed number to 0
, but you can do something else if you like.)
Alternatively, you can use an Ints
method from the Guava library, which in combination with Java 8's Optional
, makes for a powerful and concise way to convert a string into an int:
import com.google.common.primitives.Ints;
int foo = Optional.ofNullable(myString)
.map(Ints::tryParse)
.orElse(0)
How to convert an integer to a String without buildin Java methods?
If you want to avoid any numeric to String type conversion, and you're not allowed to use built in functions, I think the options would be a switch statement or an array.
String[] digits = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"};
int inputNumber=1234;
String convertedNumber = "";
for(int n=inputNumber; n>0; n/=10)
convertedNumber = digits[n % 10] + convertedNumber;
System.out.println(convertedNumber);
What is the most efficient way to convert an int to a String?
tested it for 10m assignments of the number 10
One:
real 0m5.610s
user 0m5.098s
sys 0m0.220s
Two:
real 0m6.216s
user 0m5.700s
sys 0m0.213s
Three:
real 0m12.986s
user 0m11.767s
sys 0m0.489s
One seems to win
Edit:
JVM is standard '/usr/bin/java' under Mac OS X 10.5
java version "1.5.0_16"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_16-b06-284)
Java HotSpot(TM) Client VM (build 1.5.0_16-133, mixed mode, sharing)
More edit:
Code as requested
public class One {
public static void main(String[] args) {
int someValue = 10;
for (int i = 0; i < 10000000; i++) {
String stringValue = Integer.toString(someValue);
}
}
}
case 2 and 3 similarly
run using
javac *.java; time java One; time java Two; time java Three
Is converting Integer to String by appending it to double quotes like 'return ( + 2)' costly operation? If yes, what is alternative?
No need - if you decompile the class file, you'll see that the compiler does this for you anyway. I think this makes the code very readable, however you might want to ask yourself why are you doing this anyway... if you are confident that returning a number as a string from a method is correct, this is a good way to do it, IMO.
Best way to convert integers to Strings in Java
The option 1 ""+i
is actually interpreted by the compiler as option 1b new StringBuilder("").append(i).toString()
.
The second option String.valueOf(i)
internally calls Integer.toString(i)
and therefore has an overhead of one method call.
The third option Integer.toString(i)
seems to be fastest in my benchmark bellow.
In my tests (aprx. average over multiple runs):
- Option 1: ~64000 ms
- Option 1b: ~64000 ms (same as option 1, due to equivalent compilation)
- Option 2: ~86000 ms (due to additional method call)
- Option 3: ~40000 ms
The simplistic benchmark code I used:
public static void main(String[] args) {
int i = 0;
String result;
long time;
time = System.currentTimeMillis();
while (i < Integer.MAX_VALUE) {
result = ""+i;
i++;
}
System.out.println("Option 1: " + (System.currentTimeMillis() - time));
i = 0;
time = System.currentTimeMillis();
while (i < Integer.MAX_VALUE) {
result = new StringBuilder("").append(i).toString();
i++;
}
System.out.println("Option 1b: " + (System.currentTimeMillis() - time));
i = 0;
time = System.currentTimeMillis();
while (i < Integer.MAX_VALUE) {
result = String.valueOf(i);
i++;
}
System.out.println("Option 2: " + (System.currentTimeMillis() - time));
i = 0;
time = System.currentTimeMillis();
while (i < Integer.MAX_VALUE) {
result = Integer.toString(1);
i++;
}
System.out.println("Option 3: " + (System.currentTimeMillis() - time));
}
As a conclusion, at least on my JVM (JDK 1.7.0_60 64bit) the option 3: Integer.toString(i)
is the fastest and I'd recommend to use it.
The conclusion that ""+i
is the fastest in one of the other posts is likely due to a flawed benchmark which enabled compilation into a constant.
Fastest way of converting integer to string in java
""
and 1
are known at compile time. This is why in function_2
"" + 1
is really replaced by "1"
while convertion to bytecode.
getOne()
result is unknown at the compilation time so the concatenation will be done in runtime. BUT because concatenation (+) is not efficient it is likely that compiler will change this to StringBuilder.append()
based implementation.
Don't believe me? Try: javap -c ClassName.class
and you will see something like this:
public static void function_2();
Code:
0: ldc #39 // String 1
2: putstatic #16 // Field j:Ljava/lang/String;
5: return
public static void function_3();
Code:
0: new #42 // class java/lang/StringBuilder
3: dup
4: invokespecial #44 // Method java/lang/StringBuilder."<init>":()V
7: invokestatic #28 // Method getOne:()I
10: invokevirtual #45 // Method java/lang/StringBuilder.append:(I)Ljava/lang/StringBuilder;
13: invokevirtual #49 // Method java/lang/StringBuilder.toString:()Ljava/lang/String;
16: putstatic #16 // Field j:Ljava/lang/String;
19: return
function_2()
have only one String "1", while function_3 have all these method calls with additional StringBuilder inside :)
Keep in mind that some optimization may occur at runtime, but this behavior is JVM and it's configuration dependent.
Java 9 integer to String cast
First of all, the assumption that Integer.toString(i)
is always faster than ""+i
does not hold.
Most notably, if i
is a compile time constant, ""+i
will be as well, contrary to String.valueOf(i)
. Of course, if the definition is like final int i=16;
, readers will object the use of ""+i
, as "16"
would be much clearer. But if we’re talking about final int DEFAULT_USER = DEFAULT_GROUP << GROUP_BIT;
, ""+DEFAULT_USER
is much clearer than a literal string containing the actual number. And being a compile-time constant is more than just a performance issue, it allows using the string in annotations or case
labels of a switch
statement.
If i
is not a compile-time constant, there is no mandatory compiled form, so in principle, compilers are allowed to compile ""+i
to Integer.toString(i)
anyway. If we compare the usual naive (or let’s call it “straight-forward”) implementation new StringBuilder().append("").append(i).toString()
with the Integer.toString(i)
variant or the hypothetical optimized Java 9 implementation, only the final copying action from the StringBuilder
’s buffer to the result String
’s value array may have a performance impact, but this can get optimized away by the HotSpot JVM. The other issue, that the Java 9 solution aims at, the StringBuilder
’s initial capacity, is not relevant here, as an int
’s string representation easily fits into the default capacity of 16
char
s.
For most nontrivial int
values, the costs of the conversion to the decimal form will outweigh the other costs significantly, so if you prefer ""+i
over Integer.toString(i)
you should not let performance concerns be the reason not to use it. This also implies that you should not expect a dramatical speedup with the Java 9 implementation. The main operation is still the same.
I think, the biggest improvement of the Java 9 solution is the reduction of the code size, as all these similar invocation sequences, generated for every string concatenation expression, will be fold to one instruction (that’s especially relevant to concatenations of multiple expressions). The opportunity to improve the performance, is only a nice add-on, but I wouldn’t expect the improvements to be dramatic, especially not in the first versions of JRE 9.
So the decision between ""+i
and Integer.toString(i)
or String.valueOf(i)
is merely a stylistic question (which we don’t discuss here), not a performance issue.
Related Topics
Only Using @JSONignore During Serialization, But Not Deserialization
A Simple Scenario Using Wait() and Notify() in Java
How to Deploy a War File in Tomcat 7
Why Are Interface Variables Static and Final by Default
Differencebetween Integer and Int in Java
Mockito - Difference Between Doreturn() and When()
How to Ignore Ssl Certificate Errors in Apache Httpclient 4.0
What Does the Question Mark in Java Generics' Type Parameter Mean
Java Ee 6 @Javax.Annotation.Managedbean VS. @Javax.Inject.Named VS. @Javax.Faces.Managedbean
Order of Xml Attributes After Dom Processing
Keyword for the Outer Class from an Anonymous Inner Class
Abstract Class VS Interface in Java
How Is an Overloaded Method Chosen When a Parameter Is the Literal Null Value
What Is the Use of Interface Constants
String.Replaceall(Regex) Makes the Same Replacement Twice