3

What are the alternative methods for converting and integer to a string?

1

7 Answers 7

10
Integer.toString(your_int_value);

or

your_int_value+"";

and, of course, Java Docs should be best friend in this case.

Sign up to request clarification or add additional context in comments.

4 Comments

your_edit_value + ""; causes the allocation of an extra empty string object, call Integer.toString(your_int_value) and concatenates both of them. 3 strings allocations where the first statement requires only one. The first one is faster.
the seoncd version is awful. Java is not PHP or JavaScript.
Implicit conversion to String has a big downside. val1 + val2 + "" is very different from "" + val1 + val2
yes, totally agree value+""; is not a good approach. i was just trying to mention different ways of doing that.
4

Here are all the different versions:

a) Convert an Integer to a String

Integer one = Integer.valueOf(1);
String oneAsString = one.toString();

b) Convert an int to a String

int one = 1;
String oneAsString = String.valueOf(one);

c) Convert a String to an Integer

String oneAsString = "1";
Integer one = Integer.valueOf(oneAsString);

d) Convert a String to an int

String oneAsString = "1";
int one = Integer.parseInt(oneAsString);

There is also a page in the Sun Java tutorial called Converting between Numbers and Strings.

Comments

3
String one = Integer.toString(1);

Comments

3
String myString = Integer.toString(myInt);

Comments

2
String.valueOf(anyInt);

Comments

2

There is Integer.toString() or you can use string concatenation where 1st operand is string (even empty): String snr = "" + nr;. This can be useful if you want to add more items to String variable.

1 Comment

I think both are useful. Example: if you want to convert some number to string in loop then you can use new_name = old_name + i + ".txt" or new_name = old_name + Integer.toString(i) + ".txt". In this case I prefer shorter method.
0

You can use String.valueOf(thenumber) for conversion. But if you plan to add another word converting is not nessesary. You can have something like this:
String string = "Number: " + 1
This will make the string equal Number: 1.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.