Reputation: 27
I'm a little confused about type casting in general.
As I understand it at the moment (or misunderstand it, perhaps ), type casting is just a way to change a data type of a variable. For instance, when I have:
String stringVar = "1";
I could change the data type of stringVar to integer with:
int intVar = (int)stringVar;
Correct?
But I could just as well use this to accomplish the same goal:
int intVar = Integer.parseInt(stringVar);
I have also seen other methods of converting data types. So should I just think of type casting and those methods as multiple ways of accomplishing the same thing, or all they somehow different?
Also, I have seen something like this occasionally too, is this good practice or just redundant?
String stringVar = (String)intVar.toString();
Upvotes: 1
Views: 80
Reputation: 206786
No, you cannot convert a String
to an int
by casting. Casting does not automatically convert objects from one type to another*.
With a cast, you circumvent the compiler's type checking. You tell the compiler "I have this object here, and I know better than you what this is exactly, so I want you to treat it as if it is of type X". No automatic conversion will be done.
The compiler will not check the type of the object, but a type check will still be done - at runtime instead of at compile time. If the type is wrong when you run the program, you'll get a ClassCastException
.
*: There are some automatic conversions when you cast from one primitive type to another, but not with reference types.
Upvotes: 1
Reputation: 393781
You can't cast a String
to an int
, since that conversion can only be done for very specific String
s (that contain only digits, and not too many digits). Casting only works if the source type can be converted to the target type. The JLS has strict rules concerning which types can be converted to which types. Some conversions are done automatically while others require an explicit cast.
In order to convert a String to an integer, you must use Integer.parseInt(stringVar)
or Integer.valueOf(stringVar)
.
As to (String)intVar.toString()
, first of all it will only work if intVar
is Integer
(not int
). And the casting to String
is redundant, since toString
already returns a String
.
Upvotes: 1