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?