Converting Integer to String there are different approaches that can help to get your desire output.
First, why you need to convert an int value to String as you know while converting int to string, String has a different type of methods which you can use to perform various operations on String, So sometimes you need int to a String value in java.
There are many ways to convert an Integer to String in java. But we can share with you some best and easy way to convert int to String.
1) Using String Concatenation to convert an int to String.
public class ConvertIntToString { public static void main(String[] args) { String string = "120"; int num = 120; String intToString = "" + num; System.out.println(string.equals(intToString)); } }
OUTPUT: true.
The concatenation will work, but it is an unconventional way to convert an int to String.
In Java, if we used + operator which translates the code into.
StringBuilder sb = new StringBuilder(); sb.append(""); sb.append(num); String str = sb.toString();
NOTE: This will be done at compile-time. It's slightly less efficient and slows your performance, but it works.
Then you simply say, I don't want to append an Integer to an (empty) String using + operator. I want to convert an integer to String.
Also, if performance is a concern, then + operator it seems slower.
2) Using String valueOf method to convert an int to String.
The technique is simple and quick and much faster than using the String + operator.The String class provides valueOf methods for all primitive types and Object type.
String.valueOf(i) has lots of overload method which return you a String value.
public static String valueOf(int i): int to String
public class ConvertIntToString { public static void main(String[] args) { String string = "120"; int num = 120; String intToString = String.valueOf(num); System.out.println(string.equals(intToString)); } }
OUTPUT: true.
Moreover, the static valueOf() of String class takes different primitive parameters and offers a more flexible way to operate on String but still better than concatenation.
3) Using Integer.toString(i) method to convert an int to String.
Integer class has static method toString() you can use it to convert int to a String object.
public static String toString(int i)
public class ConvertIntToString { public static void main(String[] args) { String string = "120"; int num = 120; String intToString = Integer.toString(num); System.out.println(string.equals(intToString)); } }
OUTPUT: true.
NOTE: I prefer you to used Integer.toString() if you want to increase your performance much faster way this could help you to achieve that.
Conclusion:
String operator "" + num technique was slower than both String.valueOf() and Integer.toString(). Integer.toString() being a tiny bit faster than String.valueOf().
For converting int to string.
- Integer.toString(int i)
- String.valueOf(int i)
- "" + num
There are many different ways to convert a String to an Integer
Hope this will help you.
إرسال تعليق