Question

I know that implicit casting is done automatically by the compiler and virtual machine, and that explicit casting is needed to convert types of data when Java is not sure if the result will be valid. Casting should be done between primitives or between objects.

My question is: If my application uses both integers as well as long integers - should I use long for both types? Or downcasting for long? Or casting for int?

Can usage of long for both types causes some problems?

Était-ce utile?

La solution

I will probably go with the right datatype for right operations , long if I need long , int if int is enough for my requirements . Common sense would be to think using long for int probably will slow you down in general, but again this depends on the specific JVM implementation. You will have to decide based on the range which you want to target .

Again , if there are lots of casting involved in your program , then better to go for a datatype like long which can accommodate a larger range than int and save you from casts and loss of data in that process . Having said that , long might be slower than intalthough in modern processors and JVMs I doubt that might affect much .

May be , enlightened ones here can answer this question better.

You can also read some nice SO Q&A here and here.

Autres conseils

I think you should use a data type that covers all your values, so I would use long for everything, because it simplifies the code and avoids potentially risky conversions.

  • Casting from long to int can make you lose data since a long is bigger than an int (thus data is truncated in the cast).
  • Casting from int to long is almost (see Colin Morelli's comment about this below) the same as using long from the beginning and you avoid juggling with 2 types . Also this casting just doesn't make sense as you're taking up memory for nothing actually (unless you were using an int and a method explicitly requires a long as parameter, then you obviously have no choice but cast).

The downsides I see using long are:

  • long doubles the memory needed instead of int (still take into account Colin Morelli's comment below).
  • long might yield slower performance (as said above, but I'm not sure about this)

It Depends on your date range. Take a look at The Java Tutorials: Primitive Data types if you know that your numbers will be between Integer.MIN_VALUE and Integer.MAX_VALUE don't sweet, casting will work as expected. Else, go for long or BigInteger.

You really need to be more clear on the range of numbers you are dealing with. Well with the given input the best bet would be to go with long. But If you really need to make it generic and memory is not a constraint then you could use BigInteger.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top