Stepan Stepan - 1 year ago 45
Java Question

Java type casting. Logic behind (String), .toString() and "" + int

Java is a strongly typed language. Hence, less bugs in compiled code and better readability at a cost of slower coding. Hence, explicit type casting is required, this part is clear.

What is the difference between:



"" + myInt

Is it purely for historical reasons, or there is some meaning behind it?

Which method is appropriate?

Answer Source

As was mentioned before, (Sting) myInt is a typecast. You can either cast within primitives or upwards in the object-hierachy. Since int is a primitive and String is an ojbect, we have a problem. Even Autoboxing cannot resolve this dilemma since Integer and String do not stand in an inheritance-relationship. Therefore, it is perfectly plausible for (String) myInt to result in a compilation error.

The semantics of Integer.toString(myInt) and "" + myInt are identical. The specifics, however, are different.

When executing Integer.toString(myInt), a new String is constructed, containing a String-representation of myInt.

When executing "" + myInt, you first construct a global String-constant, having the value "" (this is done by the JVM, you do not see this 1). The lexer demands a String on the right side of + since it fond a String of the left side of +. For primitives, the JVM "knows" how to convert them into Strings. For objects, toString() is called. Since Object has this method and each class is (at least implicitly) derived from Object, each object is guaranteed to have a toString() method. This is the second String constructed. Since Strings are immutable, the JVM might create a third String, representing the concatenation of the first two Strings2.

And then, at execution time, the JIT-compiler strikes and most of this might be irrelevant since the JIT-optimized versions of both variants may look equal. Or not. Or maybe only sometimes. JIT does funny stuff. So in the end it is more a question of personal style than performance :)

1 This is actually a lie. When writing

String s1 = "";
String s2 = "";
System.out.println(s1 == s2);

one will observe that the result is true, where false would be expected. This is due to the fact that the JVM creates a pool for all String constants to save some memory.

2 It is well possible that the JVM "recognizes" that something + "" == "" + something == something and therefore does not create this third String. I did neither test nor researched this.