• Post Reply Bookmark Topic Watch Topic
  • New Topic

interconversions  RSS feed

 
Deepesh Misra
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Sheriff
Posts: 20897
81
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Check out which nifty static methods java.lang.String has.
 
Deepesh Misra
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Sheriff
Posts: 20897
81
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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).
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!