sriram
sriram

Reputation: 9032

What is the difference between these casts? Which one is preferred?

Hi I'm very new to Java and I wonder what is the difference between these two statements:

long statusId = (long)(Some_Valid_Cast); 

and:

Long statusId = (Long)(Some_Valid_Cast); 

Which one should be preferred for casting and why?

Thanks in advance.

Upvotes: 1

Views: 154

Answers (3)

sreemanth pulagam
sreemanth pulagam

Reputation: 953

long is primitive type and Long is Object type. Its based on your need. >=Java5 version , explicit type cast not required

Upvotes: 1

mbatchkarov
mbatchkarov

Reputation: 16039

The first one casts to the primitive type long, and the second to an object of type Long. These are different- see this related question.

Upvotes: 3

Brian Agnew
Brian Agnew

Reputation: 272237

Do you want an object representation of a long, or just the number (the primitive) ?

Primitives (int, long etc.) can be interchanged with their object equivalents (Integer, Long etc.). If you use the object variants they can then be inserted in collections that normally take objects (e.g. Map, List, Set) and used wherever an Object is expected. I would, however, normally expect you to be using the primitive variant for most applications.

It's worth looking at this SO question for more information on the pros/cons.

Upvotes: 1

Related Questions