Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String valueOf vs concatenation with empty string

Tags:

java

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?

like image 840
Cool Java guy מוחמד Avatar asked Oct 13 '11 09:10

Cool Java guy מוחמד


People also ask

Can you concatenate an empty string?

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.

What is the difference between string valueOf and toString?

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.

What is the use of string valueOf ()?

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.

What is string valueOf null in Java?

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.


1 Answers

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()

like image 107
jmj Avatar answered Oct 12 '22 06:10

jmj