I have been trying this int and long conversion where I have tried assigning an int
variable to a long
variable. The code is as follows:
public static void main(String []args){
int i = 1024;
long j = i;
long k = i*i*i*i;
System.out.println("j= " +j+ ", k= " +k);
}
So, while printing j
, it simply gave an output of 1024
. But while printing k
, it showed an overflow (k
=0). I sorted out this problem by using this technique, where I have explicitly casted each i
to long
. i.e.
public static void main(String []args){
int i = 1024;
long j = i;
long k = ((long)i)*((long)i)*((long)i)*((long)i);
System.out.println("j= " +j+ ", k= " +k);
}
Now, it showed correct values of both j
and k
.
So, I wanted to know why is this needed to cast int
in the second case but not in the first one. k
, being a long
can retain this value after this heavy assignment. But, why it is not been correctly assigned?
The reason is that your line
long k = i*i*i*i;
can be thought of as
long k = ((i*i)*i)*i;
or...
int k1 = i*i;
int k2 = k1*i;
int k3 = k2*i;
long k = k3;
So when any of kn
overflows, you get the error.
When you do your casts you're obviously circumventing this problem by always multiplying long
s together.
Of course the simplest modification to your initial program is to define i
as a long
straight away, instead of an int
.
long i = 1024L;