11

How do I convert an integer variable to a string variable in Java?

1
  • 2
    This is a very general java question
    – the_drow
    Jan 30, 2011 at 11:45

5 Answers 5

28

you can either use

String.valueOf(intVarable)

or

Integer.toString(intVarable)
10

There are at least three ways to do it. Two have already been pointed out:

String s = String.valueOf(i);

String s = Integer.toString(i);

Another more concise way is:

String s = "" + i;

See it working online: ideone

This is particularly useful if the reason you are converting the integer to a string is in order to concatenate it to another string, as it means you can omit the explicit conversion:

System.out.println("The value of i is: " + i);
2
  • Does this really work? :o 'i' is an int i presume. huh i'm gonna have to try that out later.
    – Holly
    Jan 30, 2011 at 11:13
  • @Holly: Yes, it might seem surprising that you can do this in a type-safe language like Java but it does actually work. See the ideone link I've posted.
    – Mark Byers
    Jan 30, 2011 at 11:18
1

Here is the method manually convert the int to String value.Anyone correct me if i did wrong.

/**
 * @param a
 * @return
 */
private String convertToString(int a) {

    int c;
    char m;
    StringBuilder ans = new StringBuilder();
    // convert the String to int
    while (a > 0) {
        c = a % 10;
        a = a / 10;
        m = (char) ('0' + c);
        ans.append(m);
    }
    return ans.reverse().toString();
}
0
  Integer yourInt;
  yourInt = 3;
  String yourString = yourInt.toString();
0

There are many different type of wat to convert Integer value to string

 // for example i =10

  1) String.valueOf(i);//Now it will return "10"  

  2 String s=Integer.toString(i);//Now it will return "10" 

  3) StringBuilder string = string.append(i).toString();

   //i = any integer nuber

  4) String string = "" + i; 

  5)  StringBuilder string = string.append(i).toString();

  6) String million = String.format("%d", 1000000)

Your Answer

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