In some places i saw (String)value
.In some places value.toString()
What is the difference between these two.In which scenario which one i need to use.
And what is the difference between new Long(value)
and (Long)value
?
(String) value casts object value to string, which has to extends String. value.toString() calls method on object value, which is inherritated from class Object and this method return String, that show information of this object. If you have some yourClass value, it is reccomended to overrite toString()
new Long(value) creates new object of type Long and sets value of Long to your variable value. (Long)value get object value and cast it to object of type Long. in Long(value) value has to be number or string.
In
new Long(value)
creates new wrapper class Object
and
(Long)value
type cast value to Long( to wrapper) if possible.
similarly
String(value)
type cast value to to String
but toString() is a method which is a object class method and One must override it according to need, eg.
class User
{
String name;
int age;
public String toString()
{
return "name :"+name+" \n age :"+age;
}
}
In no language (that I know of) will a cast change the type of an object.
You use the cast (String)
when you have, say, a reference that the compiler thinks is an Object, but you know is really a String, and you want the compiler to know that. If you have an Integer and try to cast to String you will get a ClassCastException when you run the code.
So if you have an Integer and want its String representation you'd use toString.
(Note that a cast WILL change the type of a "scalar". Ie, you can cast from int to char with (char)
and the compiler will perform the appropriate conversion. The "cast" in this case is an entirely different concept. It's unfortunate that tradition has led the same syntax to be used for both.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With