In my coding various places i need to change integer values to string values. To convert the cast integer to string i use concatenation with "" to integer.
i found an another way that is using String.parseInt(..); method.
my question is i do not know which is optimized method to do casting in java and how it is optimized?. is there any other way to cast except my code?
my sample code:
int total = mark1 + mark2;
String str_total = ""+total; // currently doing.
.......
String str_total = String.parseInt(total); // i am planning to do.
You can also use -
String str_total = String.valueOf(total);
OR
Use Integer rahter than int in your code and then use toString() on Integer like
Integer total = mark1 + mark2;
String str_total = total.toString();
In your code -
String str_total = "" + total;
Actually you are creating 2 new string objects first for "" and second str_total
but in my code only one new string object will be created.
Implementation of valueOf in String class is as follows -
public static String valueOf(int i) {
return Integer.toString(i);
}
here toString will create a new String object
The String.valueOf(int) method calls Integer.toString(int).
Doing string concatenation (""+i), first i is converted to an Integer and then the function Integer.toString is called to get String value of the integer.
Therefor calling String.valueOf(int) will perform better than string concatenation since it skips the creation of the Integer object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With