| Author |
interconversions
|
Deepesh Misra
Greenhorn
Joined: Jan 20, 2010
Posts: 2
|
|
|
when we take input from user as a string we can convert it into related integer by using " Integer.parseInt() " , but how to convert an integer into String so as we can display integer results on to an Applet window.
|
 |
Rob Spoor
Saloon Keeper
Joined: Oct 27, 2005
Posts: 17259
|
|
|
Check out which nifty static methods java.lang.String has.
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
Deepesh Misra
Greenhorn
Joined: Jan 20, 2010
Posts: 2
|
|
Its easy to convert an integer into String....
let you have int x=10;
Now you wish to convert into String, then...
Ans- you need to have a empty string and then add concatenate the integer variable with String ...
String str = ""+x;
Now at String str, you have 10 as a string.....
|
 |
Rob Spoor
Saloon Keeper
Joined: Oct 27, 2005
Posts: 17259
|
|
Except you don't want to do that, since it's less efficient. Your code will be compiled into this with Java 6's compiler:
That's one StringBuilder object, the empty String, then appending an int which internally calls Integer.getChars (it has default access so it won't show up in the API), then toString to create the String object.
The method in String I hinted at in my previous post, String.valueOf(int), calls Integer.toString(x, 10). That in turn calls Integer.toString(x) which creates a char[] and also calls Integer.getChars, then creates a new String.
So let's compare the two calls:
- String.valueOf(x): one char[], one String
- "" + x: one StringBuilder, the empty String, one String
Even if you take out the empty String then the StringBuilder will be less efficient than the char[] of Integer.toString - that char[] is just as large as it needs to be whereas StringBuilder has an internal char[] which may need to be replaced if it becomes too small. And the StringBuilder has more overhead of course.
So please, stop using "" + x to convert anything into a String. Use String.valueOf(x).
|
 |
 |
|
|
subject: interconversions
|
|
|