• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Getting from long to int

 
Geoffrey Dagley
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a question about the extra credit on the second problem. The number 999,999,999,999 is obviously too large to be an integer. So instead I have used a long. The problem comes when I want to convert the long to an int. I have not seen a way to do this. However, I saw something about Integer and int. Is there a similar long and Long adn would there be a method for Long to convert it an int?
 
paul wheaton
Trailboss
Pie
Posts: 21390
Firefox Browser IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm not sure if this will answer your question, but here goes:
If you want to convert a long to an int and you are sure that the value in the long will fit in the int, do it like this:
long myLong = 500 ;
int i = (int) myLong ;
This is called "casting". The only problem comes from when the value in the long is too big for the int. In that case, I think an exception is thrown (in C and C++ it just "makes the best of it" copies the lowest order bytes, so you end up with a modulo of MAXINT).

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic