This is something I never truly understood in Java. Lets say I have:
int x = 4;
now I can not do this
functionThatRequiresString(x) or functionThatRequiresString((String)x)
Now I can not pass a function that requires a string the variable x. I am also unable to cast it from an int to a string. Now the normal ways of doing this would be:
Integer.toString(x) or String.valueOf(x)
Now why can I do this though?
functionThatRequiresString(""+x)
How is this different from casting an integer to a string?
Casting means that you tell the compiler “I have an object of type A here, but I want you to treat it as if it is of type B. Don’t give an error because it doesn’t look like a B to you”.
Casting does not do any conversions (at least not for non-primitive types). If, when running the program, the object really is not of type B, you will get a
ClassCastException.You cannot cast an
intto aStringbecause anintis simply not aString– you can tell the compiler to pretend that it is, but you’ll get aClassCastExceptionwhen you run the program.The other examples you give will convert (not cast) an
intto aString.