Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between (String)value and value.toString() , new Long(value) and (Long)value

Tags:

java

casting

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?

like image 344
PSR Avatar asked Apr 09 '13 11:04

PSR


3 Answers

(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.

like image 155
Miloš Lukačka Avatar answered Oct 21 '22 05:10

Miloš Lukačka


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;
}
}
like image 4
Nirbhay Mishra Avatar answered Oct 21 '22 06:10

Nirbhay Mishra


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.)

like image 3
Hot Licks Avatar answered Oct 21 '22 06:10

Hot Licks