Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implicit cast to string - toString and int + ""

Why when i use this:

int a = 1;
methodWithParamString(a + "");

a is cast to String, bu i can't use toString() on integer?

int a = 1;
methodWithParamString(a.toString());

Doesn't this: a+"" works like: a.toString() + "" ?

like image 650
MicNeo Avatar asked Feb 06 '12 11:02

MicNeo


People also ask

Can you cast from int to string?

We can convert int to String in java using String. valueOf() and Integer. toString() methods.

Does Java automatically cast int to string?

No. It is converted to a String. (You can't cast a primitive type to a String, either implicitly or explicitly.)

Can strings be Typecasted?

As was mentioned before, (String) myInt is a typecast. In Java, we can either cast within primitives or upwards in the object-hierarchy.

Can you cast an int to a string C#?

Converting int to string in C# is used to convert non-decimal numbers to string character. This can be done by using int to string conversion, int to string with Int32. ToString(), int to string with string concatenation, int to string with StringBuilder, int to string with Convert.


1 Answers

No, it works like String.valueOf( a ) + "", which in turn behaves like new StringBuilder( String.valueOf( a ) ).append( "" ).toString().

The important thing to know is that it's all just done by the compiler, in other words it's syntactic sugar. This is why adding strings together in a loop isn't a good idea for example. (Although modern VMs might have some mechanism to reduce the performance overhead.)

like image 101
biziclop Avatar answered Sep 26 '22 02:09

biziclop