• Post Reply Bookmark Topic Watch Topic
  • New Topic

Long and Int  RSS feed

 
Lee Cage
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello People,

Well, I have a question about long and int. Actually I have discovered it today when writing a date difference method.

this small program outputs 530. correct result is 24.

public class TestDrive
{
public static void main(String[] args)
{
long q = 1000*60*60*24*365;

long c = 780184260000L / q;
System.out.println(c);
}

}

but if i change it to this,
public class TestDrive
{
public static void main(String[] args)
{
long q = (long) 1000*60*60*24*365;

long c = 780184260000L / q;
System.out.println(c);
}

}


viola! it works.. but the point I don't get is why does jvm outputs 530? as far as I know, java will convert all int to long automatically.. plus why does casting require to convert from int to long? i mean casting is used for converting from big primitives to small ones.. it is not for widening.
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Java can automatically promote an int to a long. However numeric whole numbers are ints. On the right-hand side of the calculation, all of the numbers are ints, so the product is an int. However, the product is larger than the capacity of an int, so the upper-level bits of the result are lost. So when the conversion to long takes place, it is a conversion of the lower 32 bits of the result.
[ February 19, 2007: Message edited by: Keith Lynn ]
 
Lee Cage
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
so when I use casting, all right-side calculation is done under long type instead of int?
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When one operand of * is of type long, the other (if it is int or less) will be promoted to long.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!