I am working in Java code optimization. I'm unclear about the difference between String.valueOf
or the +""
sign:
int intVar = 1; String strVar = intVar + ""; String strVar = String.valueOf(intVar);
What is the difference between line 2 and 3?
Concatenating with an Empty String VariableYou can use the concat() method with an empty string variable to concatenate primitive string values. By declaring a variable called totn_string as an empty string or '', you can invoke the String concat() method to concatenate primitive string values together.
String. valueOf will transform a given object that is null to the String "null" , whereas . toString() will throw a NullPointerException . The compiler will use String.
The java string valueOf() method converts different types of values into string. By the help of string valueOf() method, you can convert int to string, long to string, boolean to string, character to string, float to string, double to string, object to string and char array to string.
The String. valueOf(Object) method, as its Javadoc-generated documentation states, returns "null" if the passed in object is null and returns the results on the passed-in Object 's toString() call if the passed-in Object is not null. In other words, String. valueOf(String) does the null checking for you.
public void foo(){ int intVar = 5; String strVar = intVar+""; }
This approach uses StringBuilder to create resultant String
public void foo(); Code: 0: iconst_5 1: istore_1 2: new #2; //class java/lang/StringBuilder 5: dup 6: invokespecial #3; //Method java/lang/StringBuilder."<init>":()V 9: iload_1 10: invokevirtual #4; //Method java/lang/StringBuilder.append:(I)Ljava/lan g/StringBuilder; 13: ldc #5; //String 15: invokevirtual #6; //Method java/lang/StringBuilder.append:(Ljava/lang/ String;)Ljava/lang/StringBuilder; 18: invokevirtual #7; //Method java/lang/StringBuilder.toString:()Ljava/la ng/String; 21: astore_2 22: return
public void bar(){ int intVar = 5; String strVar = String.valueOf(intVar); }
This approach invokes simply a static method of String
to get the String version of int
public void bar(); Code: 0: iconst_5 1: istore_1 2: iload_1 3: invokestatic #8; //Method java/lang/String.valueOf:(I)Ljava/lang/Stri ng; 6: astore_2 7: return
which in turn calls Integer.toString()
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