This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Java Interview Guide and have Anthony DePalma on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes cast between  long and int. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "cast between  long and int." Watch "cast between  long and int." New topic

cast between long and int.

james gong
Ranch Hand

Joined: May 29, 2001
Posts: 48
can you automataiclly convert a long primitive to a int ,if the value of the long is samll enough to fit the int?
sandip karmarkar

Joined: Jan 08, 2001
Posts: 26
You can carry out narrowing of conversion if range of the variable is not a problem. If range of long variable for conversion is within range of interger then narrowing of conversion is possible.
Dave Vick
Ranch Hand

Joined: May 10, 2001
Posts: 3244
If by automatically convert you mean without a cast then no you can't do it (not from long to int anyway. You can do it by casting but may lose information when the leftmost bits of the value being cast get cut off. Going from a long to an int the 32 most significant bits would get truncated. For example the largest long you can have is -9223372036854775807. This is
01111111 11111111 11111111 11111111 11111111 11111111 11111111 11111111 in binary. Casting this to an int would result in the left most 32 bits getting chopped so it would be: 11111111 11111111 11111111 11111111 or -1 in decimal.
run this to see it in action:
hope that helps
[This message has been edited by Dave Vick (edited June 26, 2001).]

I agree. Here's the link:
subject: cast between long and int.
It's not a secret anymore!